<?php

/*
Plugin Name: CoppermineSC
Plugin URI: http://www.55rueplumet.com/plugins/copperminesc/
Description: Include images from Coppermine Galleries in WordPress entries. Based on original script by <a href="http://www.lennartgroetzbach.de">Lennart Groetzbach</a> that was enhanced and adapted as a plugin by <a href="http://www.texx.org">Matthias Jell</a>.
Version: 0.4.5
Author: Brad Guilford
Author URI: http://www.55rueplumet.com
*/

/*
Copyright 2005-2006 Brad Guilford

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/*
Usage:
	Add one of the following lines into an entry:

	[cpg_image:2,myimage.jpg]					--> inserts full size/original image for image in album id 2 named 'myimage.jpg'
	[cpg_imagenormal:2,myimage.jpg]				--> inserts normalized image for image in album id 2 named 'myimage.jpg'
	[cpg_imagethumb:2,myimage.jpg]				--> inserts thumbnail image for image in album id 2 named 'myimage.jpg'

	[cpg_imagefix:1234]							--> inserts full size/original image with permanent id 1234
	[cpg_imagefixnormal:1234]					--> inserts normalized image with permanent id 1234
	[cpg_imagefixthumb:1234]					--> inserts thumbnail image with permanent id 1234

	[cpg_album:4]								--> inserts thumbnails for all images in album id 4
	[cpg_album:4,10]							--> inserts thumbnails for the first 10 images in album 4
	[cpg_albumnew:4]							--> inserts thumbnails for all images in album id 4 in order from newest to oldest
	[cpg_albumnew:4,10]							--> inserts thumbnails for the 10 latest uploads from the images in album id 4
	[cpg_albumrand:4]							--> inserts thumbnails for all images in album id 4 in random order
	[cpg_albumrand:4,10]						--> inserts 10 random thumbnails from the images in album id 4

	[cpg_albumfullsize:4]						--> inserts full size/original images for all images in album id 4
	[cpg_albumfullsize:4,10]					--> inserts full size/original images for the first 10 images in album 4
	[cpg_albumnewfullsize:4]					--> inserts full size/original images for all images in album id 4 in order from newest to oldest
	[cpg_albumnewfullsize:4,10]					--> inserts full size/original images for the 10 latest uploads from the images in album id 4
	[cpg_albumrandfullsize:4]					--> inserts full size/original images for all images in album id 4 in random order
	[cpg_albumrandfullsize:4,10]				--> inserts 10 random full size/original images from the images in album id 4

	[cpg_cat:5]									--> inserts thumbnails for all images in category id 5
	[cpg_cat:5,12]								--> inserts thumbnails for the first 12 images in category id 5
	[cpg_catnew:5]								--> inserts thumbnails for all images in category id 5 in order from newest to oldest
	[cpg_catnew:5,12]							--> inserts thumbnails for the 12 latest uploads from the images in category id 5
	[cpg_catrand:5]								--> inserts thumbnails for all images in category id 5 in random order
	[cpg_catrand:5,12]							--> inserts 12 random thumbnails from the images in category id 5

	[cpg_catfullsize:5]							--> inserts full size/original images for all images in category id 5
	[cpg_catfullsize:5,12]						--> inserts full size/original images for the first 12 images in category id 5
	[cpg_catnewfullsize:5]						--> inserts full size/original images for all images in category id 5 in order from newest to oldest
	[cpg_catnewfullsize:5,12]					--> inserts full size/original images for the 12 latest uploads from the images in category id 5
	[cpg_catrandfullsize:5]						--> inserts full size/original images for all images in category id 5 in random order
	[cpg_catrandfullsize:5,12]					--> inserts 12 random full size/original images from the images in category id 5

	[cpg_galnew:3]								--> insert thumbnails for the 3 latest uploads from all the images in the gallery
	[cpg_galrand:3]								--> insert 3 random thumbnails from all the images in the gallery

	[cpg_galnewfullsize:3]						--> insert full size/original images for the 3 latest uploads from all the images in the gallery
	[cpg_galrandfullsize:3]						--> insert 3 random full size/original images from all the images in the gallery

	[cpg_dbimage:mydbname,2,myimage.jpg]		--> inserts full size/original image for image in album id 2 named 'myimage.jpg' from database named 'mydbname'
	[cpg_dbimagenormal:mydbname,2,myimage.jpg]	--> inserts normalized image for image in album id 2 named 'myimage.jpg' from database named 'mydbname'
	[cpg_dbimagethumb:mydbname,2,myimage.jpg]	--> inserts thumbnail image for image in album id 2 named 'myimage.jpg' from database named 'mydbname'

	[cpg_dbimagefix:mydbname,1234]				--> inserts full size/original image with permanent id 1234 from database named 'mydbname'
	[cpg_dbimagefixnormal:mydbname,1234]		--> inserts normalized image with permanent id 1234 from database named 'mydbname'
	[cpg_dbimagefixthumb:mydbname,1234]			--> inserts thumbnail image with permanent id 1234 from database named 'mydbname'

	[cpg_dbalbum:mydbname,4]					--> inserts thumbnails for all images in album id 4 from database named 'mydbname'
	[cpg_dbalbum:mydbname,4,10]					--> inserts thumbnails for the first 10 images in album 4 from database named 'mydbname'
	[cpg_dbalbumnew:mydbname,4]					--> inserts thumbnails for all images in album id 4 in order from newest to oldest from database named 'mydbname'
	[cpg_dbalbumnew:mydbname,4,10]				--> inserts thumbnails for the 10 latest uploads from the images in album id 4 from database named 'mydbname'
	[cpg_dbalbumrand:mydbname,4]				--> inserts thumbnails for all images in album id 4 in random order from database named 'mydbname'
	[cpg_dbalbumrand:mydbname,4,10]				--> inserts 10 random thumbnails from the images in album id 4 from database named 'mydbname'

	[cpg_dbalbumfullsize:mydbname,4]			--> inserts thumbnails for all images in album id 4 from database named 'mydbname'
	[cpg_dbalbumfullsize:mydbname,4,10]			--> inserts thumbnails for the first 10 images in album 4 from database named 'mydbname'
	[cpg_dbalbumnewfullsize:mydbname,4]			--> inserts thumbnails for all images in album id 4 in order from newest to oldest from database named 'mydbname'
	[cpg_dbalbumnewfullsize:mydbname,4,10]		--> inserts thumbnails for the 10 latest uploads from the images in album id 4 from database named 'mydbname'
	[cpg_dbalbumrandfullsize:mydbname,4]		--> inserts thumbnails for all images in album id 4 in random order from database named 'mydbname'
	[cpg_dbalbumrandfullsize:mydbname,4,10]		--> inserts 10 random thumbnails from the images in album id 4 from database named 'mydbname'

	[cpg_dbcat:mydbname,5]						--> inserts thumbnails for all images in category id 5 from database named 'mydbname'
	[cpg_dbcat:mydbname,5,12]					--> inserts thumbnails for the first 12 images in category id 5 from database named 'mydbname'
	[cpg_dbcatnew:mydbname,5]					--> inserts thumbnails for all images in category id 5 in order from newest to oldest from database named 'mydbname'
	[cpg_dbcatnew:mydbname,5,12]				--> inserts thumbnails for the 12 latest uploads from the images in category id 5 from database named 'mydbname'
	[cpg_dbcatrand:mydbname,5]					--> inserts thumbnails for all images in category id 5 in random order from database named 'mydbname'
	[cpg_dbcatrand:mydbname,5,12]				--> inserts 12 random thumbnails from the images in category id 5 from database named 'mydbname'

	[cpg_dbcatfullsize:mydbname,5]				--> inserts thumbnails for all images in category id 5 from database named 'mydbname'
	[cpg_dbcatfullsize:mydbname,5,12]			--> inserts thumbnails for the first 12 images in category id 5 from database named 'mydbname'
	[cpg_dbcatnewfullsize:mydbname,5]			--> inserts thumbnails for all images in category id 5 in order from newest to oldest from database named 'mydbname'
	[cpg_dbcatnewfullsize:mydbname,5,12]		--> inserts thumbnails for the 12 latest uploads from the images in category id 5 from database named 'mydbname'
	[cpg_dbcatrandfullsize:mydbname,5]			--> inserts thumbnails for all images in category id 5 in random order from database named 'mydbname'
	[cpg_dbcatrandfullsize:mydbname,5,12]		--> inserts 12 random thumbnails from the images in category id 5 from database named 'mydbname'

	[cpg_dbgalnew:mydbname,3]					--> insert thumbnails for the 3 latest uploads from all the images in the gallery from database named 'mydbname'
	[cpg_dbgalrand:mydbname,3]					--> insert 3 random thumbnails from all the images in the gallery from database named 'mydbname'

	[cpg_dbgalnewfullsize:mydbname,3]			--> insert thumbnails for the 3 latest uploads from all the images in the gallery from database named 'mydbname'
	[cpg_dbgalrandfullsize:mydbname,3]			--> insert 3 random thumbnails from all the images in the gallery from database named 'mydbname'

	For use outside an entry, use the following snippet in your sidebar or template:
		<?php if (function_exists('cpgsc_sidebar')) {
			cpgsc_sidebar('replace_with_any_tag_from_list_above'); }
		?>
	For example, to insert thumbnails for all images in album id 4:
		<?php if (function_exists('cpgsc_sidebar')) {
			cpgsc_sidebar('[cpg_album:4]'); }
		?>

Layout:
	CSS image span:						cpg_img
	CSS image div:						cpg_img
	CSS IMG classes:					cpg_image, cpg_normalimage, cpg_thumbimage
	CSS image link:						cpg_imagelink

	CSS album span:						cpg_album
	CSS album div:						cpg_album
	CSS album link:						cpg_albumlink
	CSS album full size IMG:			cpg_albumimage
	CSS album thumbnail IMG:			cpg_albumthumbimage
	CSS album thumbnail image link:		cpt_albumimagelink

	CSS category span:					cpg_cat
	CSS category div:					cpg_cat
	CSS category link:					cpg_catlink
	CSS category full size IMG:			cpg_catimage
	CSS category thumbnail IMG:			cpg_catthumbimage
	CSS category image link:			cpg_catimagelink

	CSS gallery span:					cpg_gal
	CSS gallery div:					cpg_gal
	CSS gallery link:					cpg_gallink
	CSS gallery full size IMG:			cpg_galimage
	CSS gallery thumbnail IMG:			cpg_galthumbimage
	CSS gallery image link:				cpg_galimagelink
*/

/////////////////////////////////////////////////////////////////////

define ('CPGSC_DBUSER', 'mysql_user_here');
define ('CPGSC_DBPASS', 'mysql_password_here');
define ('CPGSC_DBSERVER', 'mysql_db_server_here');
define ('CPGSC_DBNAME', 'mysql_db_name_here');
define ('CPGSC_TABLE_PREFIX', 'cpg_');
// for previous line, enter prefix for tables in db, might be based on Coppermine version number like 'cpg132_' 

// set prefix for normalized and thumbnail images (these are the defaults, but you can change them if you have customized Coppermine)
define ('CPGSC_NORMAL_PREFIX', 'normal_');
define ('CPGSC_THUMB_PREFIX', 'thumb_');

// set sort order for images when including non-random images from an album, comment out all but one of the following four lines
//define ('CPGSC_IMAGE_SORT', 'database');
//define ('CPGSC_IMAGE_SORT', 'date');
define ('CPGSC_IMAGE_SORT', 'filename');
//define ('CPGSC_IMAGE_SORT', 'title');

// set sort order for albums (within the selected category) when including non-random images from a category, comment out all but one of the following three lines
//define ('CPGSC_ALBUM_SORT', 'database');
define ('CPGSC_ALBUM_SORT', 'albumorder');
//define ('CPGSC_ALBUM_SORT', 'title');

// set whether individual image links should link to the normal size image or to the album they belong to  (does not effect album, category, or gallery based thumbnails), comment out exactly one of the following two lines
define ('CPGSC_SINGLEIMAGE_LINK', 'album');
//define ('CPGSC_SINGLEIMAGE_LINK', 'normalimage');

// optional text for album link (blank text means no link will be created), comment out exactly one of the following two lines
//define ('CPGSC_ALBUM_TEXT', '');
define ('CPGSC_ALBUM_TEXT', 'view more images from this album');

// optional text for category link (blank text means no link will be created), comment out exactly one of the following two lines
//define ('CPGSC_CATEGORY_TEXT', '');
define ('CPGSC_CATEGORY_TEXT', 'view more images from this category');

// optional text for gallery link (blank text means no link will be created), comment out exactly one of the following two lines
//define ('CPGSC_GALLERY_TEXT', '');
define ('CPGSC_GALLERY_TEXT', 'view more images from this gallery');

// optional forced width for full size original image (blank forced width means actual width will be used, you can customize the fixed width if you want to), comment out exactly one of the following two lines
define ('CPGSC_MAX_WIDTH', '');
//define ('CPGSC_MAX_WIDTH', ' style="width:400px;"');

// optional forced horizontal alignment for images (blank means follow css tags as listed in Layout section above), comment out all but one of the following four lines
define ('CPGSC_ALIGNMENT', '');
//define ('CPGSC_ALIGNMENT', 'left');
//define ('CPGSC_ALIGNMENT', 'center');
//define ('CPGSC_ALIGNMENT', 'right');

// set whether or not clicking on an image should open a new window, comment out exactly one of the following two lines
define ('CPGSC_NEWWINDOW', 'no');
//define ('CPGSC_NEWWINDOW', 'yes');

// set whether or not CoppermineSC tags work in comments, comment out exactly one of the following two lines
//define ('CPGSC_ALLOW_COMMENTS', 'allowed');
define ('CPGSC_ALLOW_COMMENTS', 'notallowed');

// set whether the image containing element is a span or a div tag, comment out exactly one of the following two lines
//define ('CPGSC_CONTAINER_ELEMENT', 'div');
define ('CPGSC_CONTAINER_ELEMENT', 'span');

// set whether or not you want to use a containing element for tags that include individual images, comment out exactly one of the following two lines
//define ('CPGSC_CONTAINER_INDIVIDUAL', 'no');
define ('CPGSC_CONTAINER_INDIVIDUAL', 'yes');

/////////////////////////////////////////////////////////////////////

function cpgsc_process($text) {
	$cpgsccmdb = new cpgscdb(CPGSC_DBUSER, CPGSC_DBPASS, CPGSC_DBNAME, CPGSC_DBSERVER);

	// look for coppermine tags
	$offset = 0;
	do {
		$start = @strpos($text, '[cpg_', $offset);
		if ($start !== false) {
			$validtag = false;
			$tagtype = '';
			$tagdb = false;
			$tagtypelength = 0;
			$tagrand = false;
			$tagnew = false;
			$tagsize = '';
			$tagoverridefullsize = false;
			$imageforcedwidth = '';

			// check for valid tag strings
			if (substr($text, $start, 11) == '[cpg_album:') {
				$validtag = true;
				$tagtype = 'album';
				$tagtypelength = 11;
			} elseif (substr($text, $start, 14) == '[cpg_albumnew:') {
				$validtag = true;
				$tagtype = 'album';
				$tagtypelength = 14;
				$tagnew = true;
			} elseif (substr($text, $start, 15) == '[cpg_albumrand:') {
				$validtag = true;
				$tagtype = 'album';
				$tagtypelength = 15;
				$tagrand = true;
			} elseif (substr($text, $start, 19) == '[cpg_albumfullsize:') {
				$validtag = true;
				$tagtype = 'album';
				$tagtypelength = 19;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 22) == '[cpg_albumnewfullsize:') {
				$validtag = true;
				$tagtype = 'album';
				$tagtypelength = 22;
				$tagnew = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 23) == '[cpg_albumrandfullsize:') {
				$validtag = true;
				$tagtype = 'album';
				$tagtypelength = 23;
				$tagrand = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 9) == '[cpg_cat:') {
				$validtag = true;
				$tagtype = 'category';
				$tagtypelength = 9;
			} elseif (substr($text, $start, 12) == '[cpg_catnew:') {
				$validtag = true;
				$tagtype = 'category';
				$tagtypelength = 12;
				$tagnew = true;
			} elseif (substr($text, $start, 13) == '[cpg_catrand:') {
				$validtag = true;
				$tagtype = 'category';
				$tagtypelength = 13;
				$tagrand = true;
			} elseif (substr($text, $start, 17) == '[cpg_catfullsize:') {
				$validtag = true;
				$tagtype = 'category';
				$tagtypelength = 17;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 20) == '[cpg_catnewfullsize:') {
				$validtag = true;
				$tagtype = 'category';
				$tagtypelength = 20;
				$tagnew = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 21) == '[cpg_catrandfullsize:') {
				$validtag = true;
				$tagtype = 'category';
				$tagtypelength = 21;
				$tagrand = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 12) == '[cpg_galnew:') {
				$validtag = true;
				$tagtype = 'gallery';
				$tagtypelength = 12;
				$tagnew = true;
			} elseif (substr($text, $start, 13) == '[cpg_galrand:') {
				$validtag = true;
				$tagtype = 'gallery';
				$tagtypelength = 13;
				$tagrand = true;
			} elseif (substr($text, $start, 20) == '[cpg_galnewfullsize:') {
				$validtag = true;
				$tagtype = 'gallery';
				$tagtypelength = 20;
				$tagnew = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 21) == '[cpg_galrandfullsize:') {
				$validtag = true;
				$tagtype = 'gallery';
				$tagtypelength = 21;
				$tagrand = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 11) == '[cpg_image:') {
				$validtag = true;
				$tagtype = 'image';
				$tagtypelength = 11;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 17) == '[cpg_imagenormal:') {
				$validtag = true;
				$tagtype = 'image';
				$tagtypelength = 17;
				$tagsize = CPGSC_NORMAL_PREFIX;
			} elseif (substr($text, $start, 16) == '[cpg_imagethumb:') {
				$validtag = true;
				$tagtype = 'image';
				$tagtypelength = 16;
				$tagsize = CPGSC_THUMB_PREFIX;
			} elseif (substr($text, $start, 14) == '[cpg_imagefix:') {
				$validtag = true;
				$tagtype = 'imagefix';
				$tagtypelength = 14;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 20) == '[cpg_imagefixnormal:') {
				$validtag = true;
				$tagtype = 'imagefix';
				$tagtypelength = 20;
				$tagsize = CPGSC_NORMAL_PREFIX;
			} elseif (substr($text, $start, 19) == '[cpg_imagefixthumb:') {
				$validtag = true;
				$tagtype = 'imagefix';
				$tagtypelength = 19;
				$tagsize = CPGSC_THUMB_PREFIX;
			} elseif (substr($text, $start, 13) == '[cpg_dbalbum:') {
				$validtag = true;
				$tagtype = 'album';
				$tagdb = true;
				$tagtypelength = 13;
			} elseif (substr($text, $start, 16) == '[cpg_dbalbumnew:') {
				$validtag = true;
				$tagtype = 'album';
				$tagdb = true;
				$tagtypelength = 16;
				$tagnew = true;
			} elseif (substr($text, $start, 17) == '[cpg_dbalbumrand:') {
				$validtag = true;
				$tagtype = 'album';
				$tagdb = true;
				$tagtypelength = 17;
				$tagrand = true;
			} elseif (substr($text, $start, 21) == '[cpg_dbalbumfullsize:') {
				$validtag = true;
				$tagtype = 'album';
				$tagdb = true;
				$tagtypelength = 21;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 24) == '[cpg_dbalbumnewfullsize:') {
				$validtag = true;
				$tagtype = 'album';
				$tagdb = true;
				$tagtypelength = 24;
				$tagnew = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 25) == '[cpg_dbalbumrandfullsize:') {
				$validtag = true;
				$tagtype = 'album';
				$tagdb = true;
				$tagtypelength = 25;
				$tagrand = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 11) == '[cpg_dbcat:') {
				$validtag = true;
				$tagtype = 'category';
				$tagdb = true;
				$tagtypelength = 11;
			} elseif (substr($text, $start, 14) == '[cpg_dbcatnew:') {
				$validtag = true;
				$tagtype = 'category';
				$tagdb = true;
				$tagtypelength = 14;
				$tagnew = true;
			} elseif (substr($text, $start, 15) == '[cpg_dbcatrand:') {
				$validtag = true;
				$tagtype = 'category';
				$tagdb = true;
				$tagtypelength = 15;
				$tagrand = true;
			} elseif (substr($text, $start, 19) == '[cpg_dbcatfullsize:') {
				$validtag = true;
				$tagtype = 'category';
				$tagdb = true;
				$tagtypelength = 19;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 22) == '[cpg_dbcatnewfullsize:') {
				$validtag = true;
				$tagtype = 'category';
				$tagdb = true;
				$tagtypelength = 22;
				$tagnew = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 23) == '[cpg_dbcatrandfullsize:') {
				$validtag = true;
				$tagtype = 'category';
				$tagdb = true;
				$tagtypelength = 23;
				$tagrand = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 14) == '[cpg_dbgalnew:') {
				$validtag = true;
				$tagtype = 'gallery';
				$tagdb = true;
				$tagtypelength = 14;
				$tagnew = true;
			} elseif (substr($text, $start, 15) == '[cpg_dbgalrand:') {
				$validtag = true;
				$tagtype = 'gallery';
				$tagdb = true;
				$tagtypelength = 15;
				$tagrand = true;
			} elseif (substr($text, $start, 22) == '[cpg_dbgalnewfullsize:') {
				$validtag = true;
				$tagtype = 'gallery';
				$tagdb = true;
				$tagtypelength = 22;
				$tagnew = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 23) == '[cpg_dbgalrandfullsize:') {
				$validtag = true;
				$tagtype = 'gallery';
				$tagdb = true;
				$tagtypelength = 23;
				$tagrand = true;
				$tagoverridefullsize = true;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 13) == '[cpg_dbimage:') {
				$validtag = true;
				$tagtype = 'image';
				$tagdb = true;
				$tagtypelength = 13;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 19) == '[cpg_dbimagenormal:') {
				$validtag = true;
				$tagtype = 'image';
				$tagdb = true;
				$tagtypelength = 19;
				$tagsize = CPGSC_NORMAL_PREFIX;
			} elseif (substr($text, $start, 18) == '[cpg_dbimagethumb:') {
				$validtag = true;
				$tagtype = 'image';
				$tagdb = true;
				$tagtypelength = 18;
				$tagsize = CPGSC_THUMB_PREFIX;
			} elseif (substr($text, $start, 16) == '[cpg_dbimagefix:') {
				$validtag = true;
				$tagtype = 'imagefix';
				$tagdb = true;
				$tagtypelength = 16;
				$imageforcedwidth = CPGSC_MAX_WIDTH;
			} elseif (substr($text, $start, 22) == '[cpg_dbimagefixnormal:') {
				$validtag = true;
				$tagtype = 'imagefix';
				$tagdb = true;
				$tagtypelength = 22;
				$tagsize = CPGSC_NORMAL_PREFIX;
			} elseif (substr($text, $start, 21) == '[cpg_dbimagefixthumb:') {
				$validtag = true;
				$tagtype = 'imagefix';
				$tagdb = true;
				$tagtypelength = 21;
				$tagsize = CPGSC_THUMB_PREFIX;
			};

			// if we found a valid tag string, parse the parameters
			if ($validtag == true) {
				$commasecond = false;
				$comma = strpos($text, ',', $start);
				$end = strpos($text, ']', $start);

				if ($end !== false) {
					if ($comma > $end) {
						$comma = false;
					};

					if ($comma !== false) {
						$commasecond = strpos($text, ',', $comma + 1);
						if ($commasecond > $end) {
							$commasecond = false;
						}
					};

					$paramcount = 0;
					if ($comma === false) {
						$param1 =  substr($text, $start + $tagtypelength, $end - $start - $tagtypelength);               
						$paramcount = 1;
					} elseif (($comma !== false) and ($commasecond === false)) {
						$param1 = substr($text, $start + $tagtypelength, $comma - $start - $tagtypelength);
						$param2 = substr($text, $comma + 1, $end - $comma - 1);
						$paramcount = 2;
					} elseif (($comma !== false) and ($commasecond !== false)) {
						$param1 = substr($text, $start + $tagtypelength, $comma - $start - $tagtypelength);
						$param2 = substr($text, $comma + 1, $commasecond - $comma - 1);
						$param3 = substr($text, $commasecond + 1, $end - $commasecond - 1);
						$paramcount = 3;
					};

					// based on the tag string, see if we have a valid set of parameters
					$validparam = false;
					if (($tagtype == 'album') and ($tagdb == false)) {
						if ($paramcount == 1) {
							$albumid = $param1;
							$albumlimit = 0;
							$validparam = true;
						} elseif ($paramcount == 2) {
							$albumid = $param1;
							$albumlimit = $param2;
							$validparam = true;
						}
					} elseif (($tagtype == 'album') and ($tagdb == true)) {            
						if ($paramcount == 2) {
							$dbname = $param1;
							$albumid = $param2;
							$albumlimit = 0;
							$validparam = true;
						} elseif ($paramcount == 3) {
							$dbname = $param1;
							$albumid = $param2;
							$albumlimit = $param3;
							$validparam = true;
						}
					} elseif (($tagtype == 'category') and ($tagdb == false)) {
						if ($paramcount == 1) {
							$categoryid = $param1;
							$categorylimit = 0;
							$validparam = true;
						} elseif ($paramcount == 2) {
							$categoryid = $param1;
							$categorylimit = $param2;
							$validparam = true;
						}
					} elseif (($tagtype == 'category') and ($tagdb == true)) {            
						if ($paramcount == 2) {
							$dbname = $param1;
							$categoryid = $param2;
							$categorylimit = 0;
							$validparam = true;
						} elseif ($paramcount == 3) {
							$dbname = $param1;
							$categoryid = $param2;
							$categorylimit = $param3;
							$validparam = true;
						}
					} elseif (($tagtype == 'gallery') and ($tagdb == false)) {
						if ($paramcount == 1) {
							$albumid = 0;
							$gallerylimit = $param1;
							$validparam = true;
						}
					} elseif (($tagtype == 'gallery') and ($tagdb == true)) {            
						if ($paramcount == 2) {
							$dbname = $param1;
							$albumid = 0;
							$gallerylimit = $param2;
							$validparam = true;
						}
					} elseif (($tagtype == 'image') and ($tagdb == false)) {
						if ($paramcount == 2) {
							$albumid = $param1;
							$imagename = $param2;
							$validparam = true;
						}
					} elseif (($tagtype == 'image') and ($tagdb == true)) {
						if ($paramcount == 3) {
							$dbname = $param1;
							$albumid = $param2;
							$imagename = $param3;
							$validparam = true;
						}
					} elseif (($tagtype == 'imagefix') and ($tagdb == false)) {
						if ($paramcount == 1) {
							$imagepermid = $param1;
							$validparam = true;
						}
					} elseif (($tagtype == 'imagefix') and ($tagdb == true)) {
						if ($paramcount == 2) {
							$dbname = $param1;
							$imagepermid = $param2;
							$validparam = true;
						}
					};

					// if we have a valid tag string and a valid set of parameters to go with it, then process the tag
					if ($validparam == true) {
						if ($tagdb == true) {
							if (cpgsc_getalternatedatabase($dbname, $dbuser, $dbpass, $dbserver, $prefix) == true) {
								$cpgsctempdb = new cpgscdb($dbuser, $dbpass, $dbname, $dbserver);
								if ($tagtype == 'album') {
									$text = substr($text, 0, $start) . cpgsc_getalbum($cpgsctempdb, $prefix, $albumid, $albumlimit, $tagrand, $tagnew, $tagoverridefullsize, $imageforcedwidth) . substr($text, $end + 1);
								} elseif ($tagtype == 'category') {
									$text = substr($text, 0, $start) . cpgsc_getcategory($cpgsctempdb, $prefix, $categoryid, $categorylimit, $tagrand, $tagnew, $tagoverridefullsize, $imageforcedwidth) . substr($text, $end + 1);
								} elseif ($tagtype == 'gallery') {
									$text = substr($text, 0, $start) . cpgsc_getgallery($cpgsctempdb, $prefix, $gallerylimit, $tagrand, $tagnew, $tagoverridefullsize, $imageforcedwidth) . substr($text, $end + 1);
								} elseif ($tagtype == 'image') {
									$text = substr($text, 0, $start) . cpgsc_getimage($cpgsctempdb, $prefix, $albumid, $imagename, $tagsize, $imageforcedwidth) . substr($text, $end + 1);
								} elseif ($tagtype == 'imagefix') {
									$text = substr($text, 0, $start) . cpgsc_getimagefix($cpgsctempdb, $prefix, $imagepermid, $tagsize, $imageforcedwidth) . substr($text, $end + 1);
								};
								$offset = $end;								
							} else {
								$offset = $offset + 5;
							}
						} else {
							if ($tagtype == 'album') {
								$text = substr($text, 0, $start) . cpgsc_getalbum($cpgsccmdb, CPGSC_TABLE_PREFIX, $albumid, $albumlimit, $tagrand, $tagnew, $tagoverridefullsize, $imageforcedwidth) . substr($text, $end + 1);
							} elseif ($tagtype == 'category') {
								$text = substr($text, 0, $start) . cpgsc_getcategory($cpgsccmdb, CPGSC_TABLE_PREFIX, $categoryid, $categorylimit, $tagrand, $tagnew, $tagoverridefullsize, $imageforcedwidth) . substr($text, $end + 1);
							} elseif ($tagtype == 'gallery') {
								$text = substr($text, 0, $start) . cpgsc_getgallery($cpgsccmdb, CPGSC_TABLE_PREFIX, $gallerylimit, $tagrand, $tagnew, $tagoverridefullsize, $imageforcedwidth) . substr($text, $end + 1);
							} elseif ($tagtype == 'image') {
								$text = substr($text, 0, $start) . cpgsc_getimage($cpgsccmdb, CPGSC_TABLE_PREFIX, $albumid, $imagename, $tagsize, $imageforcedwidth) . substr($text, $end + 1);
							} elseif ($tagtype == 'imagefix') {
								$text = substr($text, 0, $start) . cpgsc_getimagefix($cpgsccmdb, CPGSC_TABLE_PREFIX, $imagepermid, $tagsize, $imageforcedwidth) . substr($text, $end + 1);
							};
							$offset = $end;
						}
					} else {
						$offset = $offset + 5;
					}
				} else {
					$offset = $offset + 5;
				}
			} else {
				$offset = $offset + 5;
			}
		}
	} while ($start !== false);

	// the following line is not required for most WordPress installs, but is included to prevent crashes in some setups
	$wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);

	return $text;
}

/////////////////////////////////////////////////////////////////////

function cpgsc_getalternatedatabase ($dbname, &$user, &$pass, &$server, &$prefix) {
	$validdbfile = false;
	$filename = $dbname.".php";
	$dbfile = (ABSPATH."wp-content/".$filename);
	if (!file_exists($dbfile)) {
		touch($dbfile);
		chmod($dbfile, 0644);
	} else {
		$dbinfo = file("$dbfile");
		$server = $dbinfo[1];
		$pass = $dbinfo[3];
		$user = $dbinfo[4];
		$prefix = $dbinfo[5];
	
		$server = str_replace("\$alternateserver = '", "", $server);
		$server = str_replace("';", "", $server);
		$server = ltrim(rtrim($server));
		$pass = str_replace("\$alternatepassword = '", "", $pass);
		$pass = str_replace("';", "", $pass);
		$pass = ltrim(rtrim($pass));
		$user = str_replace("\$alternateuser = '", "", $user);
		$user = str_replace("';", "", $user);
		$user = ltrim(rtrim($user));
		$prefix = str_replace("\$alternatetableprefix = '", "", $prefix);
		$prefix = str_replace("';", "", $prefix);
		$prefix = ltrim(rtrim($prefix));
		
		$validdbfile = true;
	};
	return $validdbfile;
}

/////////////////////////////////////////////////////////////////////

function cpgsc_getimage(& $cpgdb, $tableprefix, $albumid, $imagename, $imagesize='', $forcewidth='') {
	$newwindow = '';
	if (CPGSC_NEWWINDOW == 'yes') {
		$newwindow = ' target="_blank"';
	};

	$alignment = '';
	if (CPGSC_ALIGNMENT == 'left') {
		$alignment = ' style="text-align:left;"';
	} elseif (CPGSC_ALIGNMENT == 'center') {
		$alignment = ' style="text-align:center;"';
	} elseif (CPGSC_ALIGNMENT == 'right') {
		$alignment = ' style="text-align:right;"';
	};

	if ($imagesize == CPGSC_NORMAL_PREFIX) {
		$imageimgtag = 'normal';
	} elseif ($imagesize == CPGSC_THUMB_PREFIX) {
		$imageimgtag = 'thumb';	
	} else {
		$imageimgtag = '';
	};
	
	$res = '';
	$cpgdb->cpgscquery('SELECT value FROM '.$tableprefix.'config WHERE name="ecards_more_pic_target" OR name="fullpath"');
	$config = $cpgdb->cpgscget_col();
	
	if ($config[0]{strlen($config[0])-1} == '/') {
		$separatorslash = '';
	} else {
		$separatorslash = '/';
	};
	
	$cpgdb->cpgscquery('SELECT filepath, filename, title, pid FROM '.$tableprefix.'pictures WHERE aid='.$albumid.' AND filename="'.$imagename.'"');
	$image = $cpgdb->cpgscget_row();
	if ($image) {
		if (CPGSC_CONTAINER_INDIVIDUAL == 'yes') {
			$res .= '<'.CPGSC_CONTAINER_ELEMENT.' class="cpg_img"'.$alignment.'>';
		};

		$uri = $config[0].$separatorslash.$config[1].$image->filepath.$imagesize.$image->filename;

		if (CPGSC_SINGLEIMAGE_LINK == 'normalimage') {
			$res .= '<a href="'.$config[0].$separatorslash.'displayimage.php?pos=-'.$image->pid.'" class="cpg_imagelink"'.$newwindow.'><img border="0"'.$forcewidth.$alignment.' src="'.$uri.'" class="cpg_'.$imageimgtag.'image" alt="'.$image->title.'" title="'.$image->title.'" /></a>';
		} else {
			$res .= '<a href="'.$config[0].$separatorslash.'thumbnails.php?album='.$albumid.'" class="cpg_imagelink"'.$newwindow.'><img border="0"'.$forcewidth.$alignment.' src="'.$uri.'" class="cpg_'.$imageimgtag.'image" alt="'.$image->title.'" title="'.$image->title.'" /></a>';
		};

		if (CPGSC_CONTAINER_INDIVIDUAL == 'yes') {
			$res .= '</'.CPGSC_CONTAINER_ELEMENT.'>';
		}
	}
	return $res;
}

/////////////////////////////////////////////////////////////////////

function cpgsc_getimagefix(& $cpgdb, $tableprefix, $permanentimageid, $imagesize='', $forcewidth='') {
	$newwindow = '';
	if (CPGSC_NEWWINDOW == 'yes') {
		$newwindow = ' target="_blank"';
	};

	$alignment = '';
	if (CPGSC_ALIGNMENT == 'left') {
		$alignment = ' style="text-align:left;"';
	} elseif (CPGSC_ALIGNMENT == 'center') {
		$alignment = ' style="text-align:center;"';
	} elseif (CPGSC_ALIGNMENT == 'right') {
		$alignment = ' style="text-align:right;"';
	};

	if ($imagesize == CPGSC_NORMAL_PREFIX) {
		$imageimgtag = 'normal';
	} elseif ($imagesize == CPGSC_THUMB_PREFIX) {
		$imageimgtag = 'thumb';	
	} else {
		$imageimgtag = '';
	};

	$res = '';
	$cpgdb->cpgscquery('SELECT value FROM '.$tableprefix.'config WHERE name="ecards_more_pic_target" OR name="fullpath"');
	$config = $cpgdb->cpgscget_col();
	
	if ($config[0]{strlen($config[0])-1} == '/') {
		$separatorslash = '';
	} else {
		$separatorslash = '/';
	};
	
	$cpgdb->cpgscquery('SELECT filepath, filename, title, aid, pid FROM '.$tableprefix.'pictures WHERE pid='.$permanentimageid);
	$image = $cpgdb->cpgscget_row();
	if ($image) {
		if (CPGSC_CONTAINER_INDIVIDUAL == 'yes') {
			$res .= '<'.CPGSC_CONTAINER_ELEMENT.' class="cpg_img"'.$alignment.'>';
		};

		$uri = $config[0].$separatorslash.$config[1].$image->filepath.$imagesize.$image->filename;

		if (CPGSC_SINGLEIMAGE_LINK == 'normalimage') {
			$res .= '<a href="'.$config[0].$separatorslash.'displayimage.php?pos=-'.$image->pid.'" class="cpg_imagelink"'.$newwindow.'><img border="0"'.$forcewidth.$alignment.' src="'.$uri.'" class="cpg_'.$imageimgtag.'image" alt="'.$image->title.'" title="'.$image->title.'" /></a>';
		} else {
			$res .= '<a href="'.$config[0].$separatorslash.'thumbnails.php?album='.$image->aid.'" class="cpg_imagelink"'.$newwindow.'><img border="0"'.$forcewidth.$alignment.' src="'.$uri.'" class="cpg_'.$imageimgtag.'image" alt="'.$image->title.'" title="'.$image->title.'" /></a>';
		};

		if (CPGSC_CONTAINER_INDIVIDUAL == 'yes') {
			$res .= '</'.CPGSC_CONTAINER_ELEMENT.'>';
		}
	}
	return $res;
}

/////////////////////////////////////////////////////////////////////

function cpgsc_getalbum(& $cpgdb, $tableprefix, $albumid, $limit, $random, $new, $fullsize, $forcewidth='') {
	$newwindow = '';
	if (CPGSC_NEWWINDOW == 'yes') {
		$newwindow = ' target="_blank"';
	};

	$alignment = '';
	if (CPGSC_ALIGNMENT == 'left') {
		$alignment = ' style="text-align:left;"';
	} elseif (CPGSC_ALIGNMENT == 'center') {
		$alignment = ' style="text-align:center;"';
	} elseif (CPGSC_ALIGNMENT == 'right') {
		$alignment = ' style="text-align:right;"';
	};

	$sortorder = '';
	if ($new == true) {
		$sortorder = ' ORDER BY pid DESC';
	} else {
		if (CPGSC_IMAGE_SORT == 'database') {
			$sortorder = ' ORDER BY pid';
		} elseif (CPGSC_IMAGE_SORT == 'date') {
			$sortorder = ' ORDER BY pid';
		} elseif (CPGSC_IMAGE_SORT == 'filename') {
			$sortorder = ' ORDER BY filename';
		} elseif (CPGSC_IMAGE_SORT == 'title') {
			$sortorder = ' ORDER BY title';
		}
	};

	$imageprefix = CPGSC_THUMB_PREFIX;
	if ($fullsize == true) {
		$imageprefix = '';
	} else {
		$forcewidth = '';
	};

	$res = '';
	$cpgdb->cpgscquery('SELECT value FROM '.$tableprefix.'config WHERE name="ecards_more_pic_target" OR name="fullpath"');
	$config = $cpgdb->cpgscget_col();
	
	if ($config[0]{strlen($config[0])-1} == '/') {
		$separatorslash = '';
	} else {
		$separatorslash = '/';
	};
	
	if ($random == true) {
		if ($limit == 0) {
			$cpgdb->cpgscquery('SELECT filepath, filename, title, pid FROM '.$tableprefix.'pictures WHERE aid='.$albumid.' ORDER BY RAND( )');
		} else {
			$cpgdb->cpgscquery('SELECT filepath, filename, title, pid FROM '.$tableprefix.'pictures WHERE aid='.$albumid.' ORDER BY RAND( ) LIMIT '.$limit);
		}
	} else {
		if ($limit == 0) {
			$cpgdb->cpgscquery('SELECT filepath, filename, title, pid FROM '.$tableprefix.'pictures WHERE aid='.$albumid.$sortorder);
		} else {
			$cpgdb->cpgscquery('SELECT filepath, filename, title, pid FROM '.$tableprefix.'pictures WHERE aid='.$albumid.$sortorder.' LIMIT '.$limit);
		}
	};

	$images = $cpgdb->cpgscget_results();
	if ($images) {
		$res .= '<'.CPGSC_CONTAINER_ELEMENT.' class="cpg_album"'.$alignment.'>';
		foreach($images as $image) {
			$uri = $config[0].$separatorslash.$config[1].$image->filepath;
			$res .= '<a href="'.$config[0].$separatorslash.'displayimage.php?pos=-'.$image->pid.'" class="cpg_albumimagelink"'.$newwindow.'><img border="0" src="'.$uri.$imageprefix.$image->filename.'" class="cpg_albumthumbimage" alt="'.$image->title.'" title="'.$image->title.'"'.$forcewidth.$alignment.' /></a>';
		}
		$res .= (CPGSC_ALBUM_TEXT ? '<br /><a href="'.$config[0].$separatorslash.'thumbnails.php?album='.$albumid.'" class="cpg_albumlink">'.CPGSC_ALBUM_TEXT.'</a>' : '');
		$res .= '</'.CPGSC_CONTAINER_ELEMENT.'>';
	}
	return $res;
}

/////////////////////////////////////////////////////////////////////

function cpgsc_getcategory(& $cpgdb, $tableprefix, $categoryid, $limit, $random, $new, $fullsize, $forcewidth='') {
	$newwindow = '';
	if (CPGSC_NEWWINDOW == 'yes') {
		$newwindow = ' target="_blank"';
	};

	$alignment = '';
	if (CPGSC_ALIGNMENT == 'left') {
		$alignment = ' style="text-align:left;"';
	} elseif (CPGSC_ALIGNMENT == 'center') {
		$alignment = ' style="text-align:center;"';
	} elseif (CPGSC_ALIGNMENT == 'right') {
		$alignment = ' style="text-align:right;"';
	};

	$sortorder = '';
	if ($new == true) {
		$sortorder = ' ORDER BY '.$tableprefix.'pictures.pid DESC';
	} else {
		if (CPGSC_ALBUM_SORT == 'database') {
			if (CPGSC_IMAGE_SORT == 'database') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.aid, '.$tableprefix.'pictures.pid';
			} elseif (CPGSC_IMAGE_SORT == 'date') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.aid, '.$tableprefix.'pictures.pid';
			} elseif (CPGSC_IMAGE_SORT == 'filename') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.aid, '.$tableprefix.'pictures.filename';
			} elseif (CPGSC_IMAGE_SORT == 'title') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.aid, '.$tableprefix.'pictures.title';
			}
		} elseif (CPGSC_ALBUM_SORT == 'albumorder') {
			if (CPGSC_IMAGE_SORT == 'database') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.pos, '.$tableprefix.'pictures.pid';
			} elseif (CPGSC_IMAGE_SORT == 'date') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.pos, '.$tableprefix.'pictures.pid';
			} elseif (CPGSC_IMAGE_SORT == 'filename') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.pos, '.$tableprefix.'pictures.filename';
			} elseif (CPGSC_IMAGE_SORT == 'title') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.pos, '.$tableprefix.'pictures.title';
			}
		} elseif (CPGSC_ALBUM_SORT == 'title') {
			if (CPGSC_IMAGE_SORT == 'database') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.title, '.$tableprefix.'pictures.pid';
			} elseif (CPGSC_IMAGE_SORT == 'date') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.title, '.$tableprefix.'pictures.pid';
			} elseif (CPGSC_IMAGE_SORT == 'filename') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.title, '.$tableprefix.'pictures.filename';
			} elseif (CPGSC_IMAGE_SORT == 'title') {
				$sortorder = ' ORDER BY '.$tableprefix.'albums.title, '.$tableprefix.'pictures.title';
			}
		}
	};

	$imageprefix = CPGSC_THUMB_PREFIX;
	if ($fullsize == true) {
		$imageprefix = '';
	} else {
		$forcewidth = '';
	};

	$res = '';
	$cpgdb->cpgscquery('SELECT value FROM '.$tableprefix.'config WHERE name="ecards_more_pic_target" OR name="fullpath"');
	$config = $cpgdb->cpgscget_col();
	
	if ($config[0]{strlen($config[0])-1} == '/') {
		$separatorslash = '';
	} else {
		$separatorslash = '/';
	};
	
	if ($random == true) {
		if ($limit == 0) {
			$cpgdb->cpgscquery('SELECT '.$tableprefix.'pictures.filepath, '.$tableprefix.'pictures.filename, '.$tableprefix.'pictures.title, '.$tableprefix.'pictures.pid FROM '.$tableprefix.'pictures INNER JOIN '.$tableprefix.'albums ON '.$tableprefix.'pictures.aid = '.$tableprefix.'albums.aid WHERE '.$tableprefix.'albums.category='.$categoryid.' AND '.$tableprefix.'albums.visibility=0 ORDER BY RAND( )');
		} else {
			$cpgdb->cpgscquery('SELECT '.$tableprefix.'pictures.filepath, '.$tableprefix.'pictures.filename, '.$tableprefix.'pictures.title, '.$tableprefix.'pictures.pid FROM '.$tableprefix.'pictures INNER JOIN '.$tableprefix.'albums ON '.$tableprefix.'pictures.aid = '.$tableprefix.'albums.aid WHERE '.$tableprefix.'albums.category='.$categoryid.' AND '.$tableprefix.'albums.visibility=0 ORDER BY RAND( ) LIMIT '.$limit);
		}
	} else {
		if ($limit == 0) {
			$cpgdb->cpgscquery('SELECT '.$tableprefix.'pictures.filepath, '.$tableprefix.'pictures.filename, '.$tableprefix.'pictures.title, '.$tableprefix.'pictures.pid FROM '.$tableprefix.'pictures INNER JOIN '.$tableprefix.'albums ON '.$tableprefix.'pictures.aid = '.$tableprefix.'albums.aid WHERE '.$tableprefix.'albums.category='.$categoryid.' AND '.$tableprefix.'albums.visibility=0'.$sortorder);
		} else {
			$cpgdb->cpgscquery('SELECT '.$tableprefix.'pictures.filepath, '.$tableprefix.'pictures.filename, '.$tableprefix.'pictures.title, '.$tableprefix.'pictures.pid FROM '.$tableprefix.'pictures INNER JOIN '.$tableprefix.'albums ON '.$tableprefix.'pictures.aid = '.$tableprefix.'albums.aid WHERE '.$tableprefix.'albums.category='.$categoryid.' AND '.$tableprefix.'albums.visibility=0'.$sortorder.' LIMIT '.$limit);
		}
	};
	$images = $cpgdb->cpgscget_results();
	if ($images) {
		$res .= '<'.CPGSC_CONTAINER_ELEMENT.' class="cpg_cat"'.$alignment.'>';
		foreach($images as $image) {
			$uri = $config[0].$separatorslash.$config[1].$image->filepath;
			$res .= '<a href="'.$config[0].$separatorslash.'displayimage.php?pos=-'.$image->pid.'" class="cpg_catimagelink"'.$newwindow.'><img border="0" src="'.$uri.$imageprefix.$image->filename.'" class="cpg_catthumbimage" alt="'.$image->title.'" title="'.$image->title.'"'.$forcewidth.$alignment.' /></a>';
		}
		$res .= (CPGSC_CATEGORY_TEXT ? '<br /><a href="'.$config[0].$separatorslash.'index.php?cat='.$categoryid.'" class="cpg_catlink">'.CPGSC_CATEGORY_TEXT.'</a>' : '');
		$res .= '</'.CPGSC_CONTAINER_ELEMENT.'>';
	}
	return $res;
}

/////////////////////////////////////////////////////////////////////

function cpgsc_getgallery(& $cpgdb, $tableprefix, $limit, $random, $new, $fullsize, $forcewidth='') {
	$newwindow = '';
	if (CPGSC_NEWWINDOW == 'yes') {
		$newwindow = ' target="_blank"';
	};

	$alignment = '';
	if (CPGSC_ALIGNMENT == 'left') {
		$alignment = ' style="text-align:left;"';
	} elseif (CPGSC_ALIGNMENT == 'center') {
		$alignment = ' style="text-align:center;"';
	} elseif (CPGSC_ALIGNMENT == 'right') {
		$alignment = ' style="text-align:right;"';
	};

	$sortorder = '';
	if ($new == true) {
		$sortorder = ' ORDER BY '.$tableprefix.'pictures.pid DESC';
	};

	$imageprefix = CPGSC_THUMB_PREFIX;
	if ($fullsize == true) {
		$imageprefix = '';
	} else {
		$forcewidth = '';
	};

	$res = '';
	$cpgdb->cpgscquery('SELECT value FROM '.$tableprefix.'config WHERE name="ecards_more_pic_target" OR name="fullpath"');
	$config = $cpgdb->cpgscget_col();
	
	if ($config[0]{strlen($config[0])-1} == '/') {
		$separatorslash = '';
	} else {
		$separatorslash = '/';
	};
	
	if ($random == true) {
		if ($limit == 0) {
			$cpgdb->cpgscquery('SELECT '.$tableprefix.'pictures.filepath, '.$tableprefix.'pictures.filename, '.$tableprefix.'pictures.title, '.$tableprefix.'pictures.pid FROM '.$tableprefix.'pictures INNER JOIN '.$tableprefix.'albums ON '.$tableprefix.'pictures.aid = '.$tableprefix.'albums.aid WHERE '.$tableprefix.'albums.visibility=0 ORDER BY RAND( )');
		} else {
			$cpgdb->cpgscquery('SELECT '.$tableprefix.'pictures.filepath, '.$tableprefix.'pictures.filename, '.$tableprefix.'pictures.title, '.$tableprefix.'pictures.pid FROM '.$tableprefix.'pictures INNER JOIN '.$tableprefix.'albums ON '.$tableprefix.'pictures.aid = '.$tableprefix.'albums.aid WHERE '.$tableprefix.'albums.visibility=0 ORDER BY RAND( ) LIMIT '.$limit);
		}
	} else {
		if ($limit == 0) {
			$cpgdb->cpgscquery('SELECT '.$tableprefix.'pictures.filepath, '.$tableprefix.'pictures.filename, '.$tableprefix.'pictures.title, '.$tableprefix.'pictures.pid FROM '.$tableprefix.'pictures INNER JOIN '.$tableprefix.'albums ON '.$tableprefix.'pictures.aid = '.$tableprefix.'albums.aid WHERE '.$tableprefix.'albums.visibility=0'.$sortorder);
		} else {
			$cpgdb->cpgscquery('SELECT '.$tableprefix.'pictures.filepath, '.$tableprefix.'pictures.filename, '.$tableprefix.'pictures.title, '.$tableprefix.'pictures.pid FROM '.$tableprefix.'pictures INNER JOIN '.$tableprefix.'albums ON '.$tableprefix.'pictures.aid = '.$tableprefix.'albums.aid WHERE '.$tableprefix.'albums.visibility=0'.$sortorder.' LIMIT '.$limit);
		}
	};

	$images = $cpgdb->cpgscget_results();
	if ($images) {
		$res .= '<'.CPGSC_CONTAINER_ELEMENT.' class="cpg_gal"'.$alignment.'>';
		foreach($images as $image) {
			$uri = $config[0].$separatorslash.$config[1].$image->filepath;
			$res .= '<a href="'.$config[0].$separatorslash.'displayimage.php?pos=-'.$image->pid.'" class="cpg_galimagelink"'.$newwindow.'><img border="0" src="'.$uri.$imageprefix.$image->filename.'" class="cpg_galthumbimage" alt="'.$image->title.'" title="'.$image->title.'"'.$forcewidth.$alignment.' /></a>';
		}
		$res .= (CPGSC_GALLERY_TEXT ? '<br /><a href="'.$config[0].$separatorslash.'index.php" class="cpg_gallink">'.CPGSC_GALLERY_TEXT.'</a>' : '');
		$res .= '</'.CPGSC_CONTAINER_ELEMENT.'>';
	}
	return $res;
}

/////////////////////////////////////////////////////////////////////

function cpgsc_sidebar($text = '') {
	$output = cpgsc_process($text);
	echo $output;
}

/////////////////////////////////////////////////////////////////////

//	Customized private code to mirror functionality from WordPress DB Class
//  ORIGINAL CODE FROM:
//  Justin Vincent (justin@visunet.ie)
//	http://php.justinvincent.com

/////////////////////////////////////////////////////////////////////

class cpgscdb {

	var $cpgscshow_errors = true;
	var $cpgscnum_queries = 0;	
	var $cpgsclast_query;
	var $cpgsccol_info;
	var $cpgscqueries;

	//	DB Constructor - connects to the server and selects a database
	function cpgscdb($dbuser, $dbpassword, $dbname, $dbhost) {
		$this->cpgscdbh = @mysql_connect($dbhost, $dbuser, $dbpassword);
		if (!$this->cpgscdbh) {
			$this->cpgscbail("
						<b>Error establishing a database connection</b>
						<p>This either means that the username and password information in your CoppermineSC plugin file is incorrect or we can't contact the database server at <code>$dbhost</code>. This could mean your host's database server is down.</p>
						<ul>
							<li>Are you sure you have the correct username and password?</li>
							<li>Are you sure that you have typed the correct hostname?</li>
							<li>Are you sure that the database server is running?</li>
						</ul>
						");
		};
		$this->cpgscselect($dbname);
	}

	//	Select a DB (if another one needs to be selected)
	function cpgscselect($db) {
		if (!@mysql_select_db($db, $this->cpgscdbh)) {
			$this->cpgscbail("
						<b>Can&#8217;t select CoppermineSC database</b>
						<p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>$db</code> database.</p>
						<ul>
						<li>Are you sure it exists?</li>
						<li>On some systems the name of your database is prefixed with your username, so it would be like username_coppermine. Could that be the problem?</li>
						</ul>
						");
		}
	}

	//	Format a string correctly for safe insert under all PHP conditions
	function cpgscescape($str) {
		return addslashes($str);				
	}

	//	Print SQL/DB error.
	function cpgscprint_error($str = '') {
		if (!$str) $str = mysql_error();
		// Is error output turned on or not..
		if ( $this->cpgscshow_errors ) {
			// If there is an error then take note of it
			print "<div id='error'>
			<p class='cpgscerror'><strong>CoppermineSC database error:</strong> [$str]<br />
			<code>$this->cpgsclast_query</code></p>
			</div>";
		} else {
			return false;	
		}
	}

	//	Kill cached query results
	function cpgscflush() {
		$this->cpgsclast_result = null;
		$this->cpgsccol_info = null;
		$this->cpgsclast_query = null;
	}

	//	Basic Query	- see docs for more detail
	function cpgscquery($query) {
		// initialise return
		$return_val = 0;
		$this->cpgscflush();

		// Keep track of the last query for debug..
		$this->cpgsclast_query = $query;
		
		$this->cpgscresult = @mysql_query($query, $this->cpgscdbh);
		++$this->cpgscnum_queries;

		// If there is an error then take note of it..
		if ( mysql_error() ) {
			$this->cpgscprint_error();
			return false;
		}

		if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
			$this->cpgscrows_affected = mysql_affected_rows();
			// Take note of the insert_id
			if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
				$this->cpgscinsert_id = mysql_insert_id($this->cpgscdbh);	
			}
			// Return number of rows affected
			$return_val = $this->cpgscrows_affected;
		} else {
			$i = 0;
			while ($i < @mysql_num_fields($this->cpgscresult)) {
				$this->cpgsccol_info[$i] = @mysql_fetch_field($this->cpgscresult);
				$i++;
			}
			$num_rows = 0;
			while ( $row = @mysql_fetch_object($this->cpgscresult) ) {
				$this->cpgsclast_result[$num_rows] = $row;
				$num_rows++;
			}

			@mysql_free_result($this->cpgscresult);

			// Log number of rows the query returned
			$this->cpgscnum_rows = $num_rows;
			
			// Return number of rows selected
			$return_val = $this->cpgscnum_rows;
		}

		return $return_val;
	}

	//	Get one variable from the DB - see docs for more detail
	function cpgscget_var($query=null, $x = 0, $y = 0) {
		if ( $query )
			$this->cpgscquery($query);

		// Extract var out of cached results based x,y vals
		if ( $this->cpgsclast_result[$y] ) {
			$values = array_values(get_object_vars($this->cpgsclast_result[$y]));
		}

		// If there is a value return it else return null
		return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
	}

	//	Get one row from the DB - see docs for more detail
	function cpgscget_row($query = null, $output = OBJECT, $y = 0) {
		if ( $query )
			$this->cpgscquery($query);

		if ( $output == OBJECT ) {
			return $this->cpgsclast_result[$y] ? $this->cpgsclast_result[$y] : null;
		} elseif ( $output == ARRAY_A ) {
			return $this->cpgsclast_result[$y] ? get_object_vars($this->cpgsclast_result[$y]) : null;
		} elseif ( $output == ARRAY_N ) {
			return $this->cpgsclast_result[$y] ? array_values(get_object_vars($this->cpgsclast_result[$y])) : null;
		} else {
			$this->cpgscprint_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
		}
	}

	//	Function to get 1 column from the cached result set based in X index, see docs for usage and info
	function cpgscget_col($query = null , $x = 0) {
		if ( $query )
			$this->cpgscquery($query);

		// Extract the column values
		for ( $i=0; $i < count($this->cpgsclast_result); $i++ ) {
			$new_array[$i] = $this->cpgscget_var(null, $x, $i);
		}
		return $new_array;
	}

	// Return the the query as a result set - see docs for more details
	function cpgscget_results($query = null, $output = OBJECT) {
		if ( $query )
			$this->cpgscquery($query);

		// Send back array of objects. Each row is an object
		if ( $output == OBJECT ) {
			return $this->cpgsclast_result;
		} elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
			if ( $this->cpgsclast_result ) {
				$i = 0;
				foreach( $this->cpgsclast_result as $row ) {
					$new_array[$i] = (array) $row;
					if ( $output == ARRAY_N ) {
						$new_array[$i] = array_values($new_array[$i]);
					}
					$i++;
				}
				return $new_array;
			} else {
				return null;
			}
		}
	}

	// Function to get column meta data info pertaining to the last query, see docs for more info and usage
	function cpgscget_col_info($info_type = 'name', $col_offset = -1) {
		if ( $this->cpgsccol_info ) {
			if ( $col_offset == -1 ) {
				$i = 0;
				foreach($this->cpgsccol_info as $col ) {
					$new_array[$i] = $col->{$info_type};
					$i++;
				}
				return $new_array;
			} else {
				return $this->cpgsccol_info[$col_offset]->{$info_type};
			}
		}
	}

	// Just wraps errors in a nice header and footer
	function cpgscbail($message) { 
	if ( !$this->cpgscshow_errors )
		return false;
		echo $message;
		die();
	}
}

/////////////////////////////////////////////////////////////////////

//	End customized private code to mirror functionality from WordPress DB Class

/////////////////////////////////////////////////////////////////////

add_filter('the_content', 'cpgsc_process');

if (CPGSC_ALLOW_COMMENTS == 'allowed') {
	add_filter('comment_text', 'cpgsc_process');
};

?>