<?php
/**
 * This object handles all database connections, and queries of the coppermine database
 * @package coppermine
 * @version $Revision: 1.9 $
 *
 * Release Version: 1.6.2 
 *
 * 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 object handles all database transactions with the backend
  *
  *
  * @package coppermine
  */
class cpm_dao {

	var $dbname;			
	var $dbhost;
	var $dbuser;
	var $dbpass;
	
	var $cpm_table_prefix = "";
	var $dbconnection = "";
	
	var $fullpathtocpm = "";
	var $partialUrltocpm = "";
	
	var $fullpathtoalbums = "";
	var $partialUrltoalbums = "";

	var $prefixThumbnail = "thumb_";
	var $prefixIntermediate = "normal_";
	var $prefixLarge = "";
		
	var $lastSQLRowsReturned = "";
	var $lastSQLErrorMessage = "";
	
	var $privacyfilter = " AND a.visibility = 0 ";
	var $filetypefilter = "";
	
	var $debugMode = false;
	
	var $defaultDateFormatString = "d-M-Y";
	var $dateFormatString = "";
	
   var $topPercentForTopRated = 10;
	//var $topPercentForMostViewed = 25;
	
// This is for CPG versions prior to 1.4
	//var $sqlPictureAlbumSelect = ' p.filepath AS pFilepath, p.filename AS pFilename, p.aid AS pAid, p.filesize AS pFilesize, p.title AS pTitle, p.caption AS pCaption, p.owner_name AS pOwner_name, p.owner_id as pOwnerId, p.ctime AS pCtime, p.hits AS pHits, a.title AS aTitle, a.description AS aDescription, p.pid AS pPid, p.pic_rating AS pPic_Rating,  p.votes AS pVotes, p.pwidth AS pWidth, p.pheight AS pHeight, u.user_lastvisit AS uUser_lastvisit, u.user_regdate AS uUser_regdate, u.user_email AS uUser_email, u.user_website AS uUser_website, u.user_location AS uUser_location, u.user_interests AS uUser_interest, u.user_occupation AS uUser_occupation';


// This is for CPG v 1.4.1 beta 1	

	var $sqlPictureAlbumSelect = ' p.filepath AS pFilepath, p.filename AS pFilename, p.aid AS pAid, p.filesize AS pFilesize, p.title AS pTitle, p.caption AS pCaption, p.owner_name AS pOwner_name, p.owner_id as pOwnerId, p.ctime AS pCtime, p.hits AS pHits, a.title AS aTitle, a.description AS aDescription, p.pid AS pPid, p.pic_rating AS pPic_Rating,  p.votes AS pVotes, p.pwidth AS pWidth, p.pheight AS pHeight, u.user_lastvisit AS uUser_lastvisit, u.user_regdate AS uUser_regdate, u.user_email AS uUser_email';




	var $sqlPictureSourceSelect = "";

	var $VERSION = "1.6.2";

	// Initializes the object
	function cpm_dao($database_name, $database_host, $database_user, $database_pass, $database_table_prefix, $urltocpm) {
		$this->dbname = $database_name;
		$this->dbhost = $database_host;
		$this->dbuser = $database_user;
		$this->dbpass = $database_pass;
		$this->cpm_table_prefix = $database_table_prefix;
				
		$this->partialUrltocpm = $urltocpm;
		
	   if (array_key_exists("DOCUMENT_ROOT",$_SERVER )) {
				$this->fullpathtocpm = $_SERVER['DOCUMENT_ROOT'] . $this->partialUrltocpm;
		} elseif (ini_get("doc_root") != "" ) {
				$this->fullpathtocpm = ini_get('doc_root') . $this->partialUrltocpm;
		} else {
				$this->fullpathtocpm = $this->partialUrltocpm;
		}

		$this->OverridePathToAlbums($this->fullpathtocpm . "/albums", $this->partialUrltocpm . "/albums");

				
		$this->setPrivateLockOn(true);
		$this->dateFormatString = $this->defaultDateFormatString;

		$this->sqlPictureSourceSelect = " " . $database_table_prefix . "pictures as p, " . $database_table_prefix . "albums as a, " 
				. "phpbb_users AS u ";
	}

	 // Cleans up the object when we are done
	function destroy ( ) {
	 	$this->dbDisconnect();	 
	}
		
	function OverridePathToAlbums($_fullpathtoalbums, $_partialUrltoalbums ) {

		if (substr($_fullpathtoalbums,-1) != '/') $_fullpathtoalbums .= '/';	
		$this->fullpathtoalbums = $_fullpathtoalbums;
	 	
		if (substr($_partialUrltoalbums,-1) != '/') $_partialUrltoalbums .= '/';	
		$this->partialUrltoalbums = $_partialUrltoalbums;
	}

	function OverridePathToCoppermine($newpath_) {
		$this->fullpathtocpm = $newpath_;
	}	
		
	function OverrideUrlToCoppermine($newpath_) {
		$this->partialUrltocpm = $newpath_;	
	}	
		
	function setFilter($filterarray) {
		if ($filterarray == "") {
				$this->filetypefilter = "";
		} else {
			$this->filetypefilter = " and (";
			foreach ($filterarray as $filter) {
				$this->filetypefilter .= " p.filename like '%" . strtolower($filter) . "'";
				$this->filetypefilter .= " or p.filename like '%" . strtoupper($filter) . "'";
				$this->filetypefilter .= " or ";
			}
			$this->filetypefilter = substr($this->filetypefilter,0, strlen($this->filetypefilter) - 4);
			$this->filetypefilter .= ') ';
		}
	}
		
	function setDebugMode($bool) {
		if ($bool) {
			$this->debugMode = true;  
		}
		else {
			$this->debugMode = false;  
		}
	}
		
	function setPrivateLockOn($bool) {
		if ($bool) {
			$this->privacyfilter = " and a.visibility = 0 ";  
		}
		else {
			$this->privacyfilter = "";  
		}
	}
	
	function setPhotoPrefix( $_thumb, $_intermediate, $_large) {
		$this->prefixThumbnail = $_thumb;
		$this->prefixIntermediate = $_intermediate;
		$this->prefixLarge = $_large;
	}
	
	function setDateFormatString( $newFormat) {
		if ($newFormat == "") {
			$this->dateFormatString = $this->defaultDateFormatString;
		} else {
			$this->dateFormatString = $newFormat;
		}
	}
	
	// Returns the total number of items in cpm
	function getMediaCount ( ) { 	
		
		$sqlcode = "SELECT COUNT(*) FROM " . $this->cpm_table_prefix . "pictures AS p, " 
				.	$this->cpm_table_prefix . "albums AS a WHERE p.aid = a.aid " . $this->filetypefilter 
				.	" AND p.approved='YES'" .  $this->privacyfilter;
		
		$resultset = $this->dbExecuteSql($sqlcode);
		$row = mysql_fetch_row($resultset);
		return ($row[0]);
	}

	function getMediaCountFrom ($source) { 

		$retval = "";
			
			$sourceSql = $this->makeSourceSql($source);
			
			if ($sourceSql != "") {
				$sourceSql = " and " . $sourceSql; 
				}
								
				$sqlcode = "SELECT COUNT(*) FROM  " . $this->cpm_table_prefix . "pictures as p, " 
						. $this->cpm_table_prefix . "albums as a where p.aid = a.aid " . $this->filetypefilter ." and p.approved='YES' " 
						. $sourceSql . " {$this->privacyfilter} "; 
				
						
				$resultset = $this->dbExecuteSql($sqlcode);
		      $row = mysql_fetch_row($resultset);
				$retval = $row[0];

		return ($retval);
	}

	function getMediaCountForAlbum( $albumid ) {
		$retval = "";
		if (is_numeric($albumid)) {

		  $sqlcode = "SELECT COUNT(*) FROM " . $this->cpm_table_prefix . "pictures AS p, " 
					. $this->cpm_table_prefix . "albums AS a WHERE p.aid=$albumid AND p.aid = a.aid " 
					. $this->filetypefilter . " AND p.approved='YES'" .  $this->privacyfilter;
			
			$resultset = $this->dbExecuteSql($sqlcode);
			$row = mysql_fetch_row($resultset);
			$retval = $row[0];
		}
				
		return ($retval);
	}
			
	function getMediaCountAddedSince ($timestamp) {
		$retval = "";
		if (is_numeric($timestamp)) {
			
		   $sqlcode = "SELECT COUNT(*) FROM " . $this->cpm_table_prefix . "pictures AS p, " 
					. $this->cpm_table_prefix . "albums AS a WHERE p.aid = a.aid " . $this->filetypefilter 
					. " AND ctime > " . $timestamp . " AND p.approved='YES'" .  $this->privacyfilter;
			
			$resultset = $this->dbExecuteSql($sqlcode);
			$row = mysql_fetch_row($resultset);
			$retval = $row[0];
		}
		return ($retval);
	}
	
	function getAlbumCount( ) {
		$sqlcode = "SELECT COUNT(*) FROM ". $this->cpm_table_prefix . "albums AS a";
		
		if ($this->privacyfilter != "") {
			$sqlcode .= " where a.visibility = 0" ;
		}
		
		$resultset = $this->dbExecuteSql($sqlcode);
		$row = mysql_fetch_row($resultset);
		return($row[0]);
	}
	
	function getCommentCount( ) {
		$sqlcode = "SELECT count(*) FROM ". $this->cpm_table_prefix . "comments as c";
		$resultset = $this->dbExecuteSql($sqlcode);
		$row = mysql_fetch_row($resultset);
		return($row[0]);
	}
	
	function getViewcount( ) {
	
			$sqlcode = "SELECT sum(p.hits) FROM " . $this->cpm_table_prefix . "pictures AS p, " 
					.	$this->cpm_table_prefix . "albums AS a WHERE p.aid = a.aid " . $this->filetypefilter 
					.	" AND p.approved='YES'" .  $this->privacyfilter;
		
		$resultset = $this->dbExecuteSql($sqlcode);
		$row = mysql_fetch_row($resultset);
		return($row[0]);
	}
	
	function getCategoryCount( ) {
		$sqlcode = "SELECT count(*) FROM ". $this->cpm_table_prefix . "categories as c";
		$resultset = $this->dbExecuteSql($sqlcode);
		$row = mysql_fetch_row($resultset);
		return($row[0]);
	}
	

// END OF STATISTICAL SECTION

	function getMediaByPid ($pid) {
		$retval = "";
		if (is_numeric($pid)) {
		 	$sqlcode = "SELECT " . $this->sqlPictureAlbumSelect . " FROM " . $this->cpm_table_prefix 
					. "pictures AS p, " . $this->cpm_table_prefix . "albums AS a, "  . 	$this->cpm_table_prefix . "users AS u WHERE p.aid = a.aid and p.pid = $pid AND p.owner_id = u.user_id " . $this->filetypefilter ." " 
					. 	$this->privacyfilter . " AND p.approved='YES'";
			
			$retval = $this->dbExecuteSql($sqlcode);
		}
		return($this->covertResultsetToArray($retval));	
	}
	
  function getTopRatedMediaFrom ($source, $count = 1) { 
		$retval = "";
		if (is_numeric($count)) {
			
			$sourceSql = $this->makeSourceSql($source);
			
			if ($sourceSql != "") {
				$sourceSql = " and " . $sourceSql; 
				}
								
				$sqlcode = "SELECT " . $this->sqlPictureAlbumSelect . " FROM " . $this->sqlPictureSourceSelect . " where p.aid = a.aid AND p.owner_id = u.MEMBER_ID " . $this->filetypefilter ." and p.approved='YES' " 
						. $sourceSql . " {$this->privacyfilter} " 
						. " ORDER BY p.pic_rating DESC LIMIT 0,$count";
				
				$retval = $this->dbExecuteSql($sqlcode);
			
		}
		elseif ($this->debugMode) {
			print "Non numeric count submitted";
		}
		
		return ($this->covertResultsetToArray($retval));
	}


function getMostVotedMediaFrom ($source, $count = 1) { 
		$retval = "";
		if (is_numeric($count)) {
			
			$sourceSql = $this->makeSourceSql($source);
			
			if ($sourceSql != "") {
				$sourceSql = " and " . $sourceSql; 
				}
								
				$sqlcode = "SELECT " . $this->sqlPictureAlbumSelect . " FROM " . $this->sqlPictureSourceSelect . " where p.aid = a.aid AND p.owner_id = u.user_id " . $this->filetypefilter ." and p.approved='YES' " 
						. $sourceSql . " {$this->privacyfilter} " 
						. " ORDER BY p.votes DESC LIMIT 0,$count";
				
				$retval = $this->dbExecuteSql($sqlcode);
			
		}
		elseif ($this->debugMode) {
			print "Non numeric count submitted";
		}
		
		return ($this->covertResultsetToArray($retval));
	}

  function getRandomTopRatedMediaFrom ($source, $count = 1) { 
		
	$retval = "";
	if (is_numeric($count)) {

		$countForSource = $this->getMediaCountFrom ($source);

		if ($countForSource == 0) {
			$rangeLimit = 0;
		} else {
			$rangeLimit =round(($countForSource * ($this->topPercentForTopRated / 100)),0);
		}
	
		if ($rangeLimit < $count) $rangeLimit = $count;
		
		$sourceSql = $this->makeSourceSql($source);
			
		if ($sourceSql != "") {
				$sourceSql = " and " . $sourceSql; 
		}
								
		$sqlcode = "SELECT " . $this->sqlPictureAlbumSelect . " FROM " . $this->sqlPictureSourceSelect . " where p.aid = a.aid AND p.owner_id = u.user_id " . $this->filetypefilter ." and p.approved='YES' " 
				. $sourceSql . " {$this->privacyfilter} " 
				. " ORDER BY p.pic_rating DESC LIMIT 0,$rangeLimit";
			
		// This should give an array from which to randomly draw images
		$allresults = $this->covertResultsetToArray($this->dbExecuteSql($sqlcode));
		$retval = array();		

		srand((float)$this->getRandomSeed());
		shuffle($allresults);
		for ($cnt = 0; $cnt < $count; $cnt++) {
			array_push($retval,$allresults[$cnt]);
		}

	}
   elseif ($this->debugMode) {
			print "Non numeric count submitted";
	}

	   return ($retval);
	}

function getRandomMostViewedMediaFrom ($source, $count = 1) { 

	// $this->topPercentToBePopular 

		$retval = "";
		if (is_numeric($count)) {

				$countForSource = $this->getMediaCountFrom ($source);
				if ($countForSource == 0) {
					$rangeLimit = 0;
				} else {
					$rangeLimit =round(($countForSource * ($this->topPercentForMostViewed / 100)),0);
				}
	
		if ($rangeLimit < $count) $rangeLimit = $count;
			$sourceSql = $this->makeSourceSql($source);
			
			if ($sourceSql != "") {
				$sourceSql = " and " . $sourceSql; 
				}
								
				$sqlcode = "SELECT " . $this->sqlPictureAlbumSelect . " FROM " . $this->sqlPictureSourceSelect . " where p.aid = a.aid AND p.owner_id = u.user_id " . $this->filetypefilter ." and p.approved='YES' " 
						. $sourceSql . " {$this->privacyfilter} " 
						. " ORDER BY p.hits DESC LIMIT 0,$count";
				
		// This should give an array from which to randomly draw images
		$allresults = $this->covertResultsetToArray($this->dbExecuteSql($sqlcode));
		$retval = array();		

		srand((float)$this->getRandomSeed());
		shuffle($allresults);
		for ($cnt = 0; $cnt < $count; $cnt++) {
			array_push($retval,$allresults[$cnt]);
		}

	}
   elseif ($this->debugMode) {
			print "Non numeric count submitted";
	}
	   return ($retval);
	}


  function getLastAddedMediaFrom ($source, $count = 1) { 
		$retval = "";
		if (is_numeric($count)) {
			
			$sourceSql = $this->makeSourceSql($source);
			
			if ($sourceSql != "") {
				$sourceSql = " and " . $sourceSql; 
				}
								
				$sqlcode = "SELECT " . $this->sqlPictureAlbumSelect . " FROM " . $this->sqlPictureSourceSelect . " where p.aid = a.aid AND p.owner_id = u.user_id" . $this->filetypefilter ." and p.approved='YES' " 
						. $sourceSql . " {$this->privacyfilter} " 
						. " ORDER BY p.ctime DESC LIMIT 0,$count";
				
				$retval = $this->dbExecuteSql($sqlcode);
			
		}
		elseif ($this->debugMode) {
			print "Non numeric count submitted";
		}
		
		return ($this->covertResultsetToArray($retval));
	}
	
	
	// Returns a random image from a category in cpm
	function getRandomImageFrom ($source, $count) { 
	$retval = "";
	
	 if (is_numeric($count)) {
		
		$sourceSql = $this->makeSourceSql($source);

		if ($sourceSql != "") {
			$sourceSql = " and " . $sourceSql;
		}	
					
			$sqlcode = "SELECT " . $this->sqlPictureAlbumSelect . " FROM " . $this->sqlPictureSourceSelect . " WHERE a.aid = p.aid AND p.owner_id = u.user_id AND p.approved='YES' " 
					. $this->filetypefilter . " " . $this->privacyfilter . $sourceSql 
					. " ORDER BY rand(" .  $this->getRandomSeed()   . ") LIMIT $count";
			
			$retval = $this->dbExecuteSql($sqlcode);
		
	  } //end if		
		elseif ($this->debugMode) {
			print "Non numeric count submitted";
		}
		
		return($this->covertResultsetToArray($retval));	
	
	} //end function


	function getLastImagesWithComments($limit) {
		$retval = "";
		if (is_numeric($limit)) {
			$sqlcode = "SELECT " . $this->sqlPictureAlbumSelect . ", m.msg_body AS mMsg_body, m.msg_author AS mMsg_author " 
					. " FROM " . $this->sqlPictureSourceSelect. ", " . $this->cpm_table_prefix . "comments AS m " 
					.	" WHERE m.pid = p.pid AND p.aid = a.aid AND p.owner_id = u.user_id" . $this->filetypefilter 
					. " AND p.approved='YES' $this->privacyfilter" 
					. " ORDER BY m.msg_date DESC LIMIT 0,$limit";

			$retval = $this->dbExecuteSql($sqlcode);
		}	
		return ($this->covertResultsetToArray($retval));
	
	}
	

	// Returns a report of media added since a timestamp
	function getMediaAddedToCategoriesSince ($timestamp) { 
		$retval = "";
		if (is_numeric($timestamp)) {
			//$sqlcode = 'SELECT c.name, a.title, a.aid, count( p.pid ), a.description , p.filepath, p.filename, p.pid ' .
			$sqlcode = 'SELECT ' . $this->sqlPictureAlbumSelect . ', c.name AS cName, c.cid AS cCid, count( p.pid ) AS count ' 
					.	' FROM ' . $this->sqlPictureSourceSelect	.	", " . $this->cpm_table_prefix . 'categories AS c '  
					.	" WHERE p.aid = a.aid  AND p.owner_id = u.user_id and p.approved='YES' $this->privacyfilter and p.ctime > " . $timestamp 
					.	' AND a.category = c.cid' 
					.  ' GROUP BY a.category'  
					. 	' ORDER BY c.name, p.mtime';
	
			$retval = $this->dbExecuteSql($sqlcode);
		}
			
		return($this->covertResultsetToArray($retval));	
	}
				
	// Returns a report of media added since a timestamp
	function getMediaAddedSince ($timestamp) { 
		$retval = "";
		if (is_numeric($timestamp)) {
			//$sqlcode = 'SELECT c.name, a.title, a.aid, count( p.pid ), a.description , p.filepath, p.filename, p.pid ' .
			$sqlcode = 'SELECT ' . $this->sqlPictureAlbumSelect . ', c.name AS cName, count( p.pid ) AS count ' 
					. 	' FROM ' . $this->sqlPictureSourceSelect . ", " . $this->cpm_table_prefix . 'categories AS c ' 
					.	" WHERE p.aid = a.aid  AND p.owner_id = u.user_id AND p.approved='YES' $this->privacyfilter and p.ctime > " . $timestamp 
 					.	' AND a.category = c.cid' 
					.	' GROUP BY a.category, a.aid' 
					.	' ORDER BY c.name, p.mtime';
	
			$retval = $this->dbExecuteSql($sqlcode);
		}
			
		return($this->covertResultsetToArray($retval));	
	}
	
	
	/**
	* Provides shortcuts into different function that return data
	*
	* The format is specified by placeholders indicated by percent signs '%'.  If you actually want a percent sign
	* you will need to put two percent signs in a row '%%'.  The most up to date list for supported placeholders 
	* can be found in the coppermine_dao formatStats function.  But the main ones are:
	* <ul><li>%f - file count</li>
	* <li>%a - album count</li> 
	* <li>%c - category count</li> 
	* <li>%v - view count</li> 
	* <li>%n - comment count (note count)</li></ul>
	*
	* 
	*/
	function formatStats ($format) {
		$output = "";
		$curpos = 0;
		$nextfind = 0;
		$lastpos = strlen($format);
		
		while ($curpos <= $lastpos) {
			$nextfind = strpos($format,'%',$curpos);
			
			if (false === $nextfind) {
				$output .= substr($format,$curpos);
				break;
			}
		
			$output .= substr($format,$curpos, ($nextfind - $curpos));
			$curpos = $nextfind + 1;
			
			switch ($format[$curpos]) {
				case ('f'):
					$output .= $this->getMediaCount();
					break;
				case ('a'):
					$output .= $this->getAlbumCount();
					break;
				case ('c'):
					$output .= $this->getCategoryCount();
					break;
				case ('v'):
					$output .= $this->getViewCount();
					break;
				case ('n'):
					$output .= $this->getCommentCount();
					break;
				case ('%'):
					$output .= '%';
					break;
				default:
					$output .= $format[$curpos];	
			}
			$curpos++;
		}
		return ($output);
	}
	
		
	// ********************************************************************************
	// DATABASE RELATED FUNCTIONS	
	// ********************************************************************************

	function makeSourceSql ($source) {
	
		$sourceSql = " (";
	
		$source=strtolower($source);

		$albumlist = array();
		$categorylist = array();
		$ownerlist = array();		

		$parts = explode(':',$source);
		
		foreach ($parts as $thispart) {
			$sections = explode('=',$thispart);
					
			if ("album" == $sections[0]) {
				$albumlist = explode(',',$sections[1]);
			}
			elseif ("cat" == $sections[0]) {
				$categorylist = explode(',',$sections[1]);
			}
			elseif("owner" == $sections[0]) {
				$ownerlist = explode(',',$sections[1]);
			}
		} // end foreach
						
		if (sizeof($albumlist)) {
		  	foreach ($albumlist as $aid) {
				if (is_numeric($aid)) {
					$sourceSql .= " p.aid=$aid or ";
				}
			}
		}
		
		if (sizeof($categorylist)) {
			foreach($categorylist as $cid) {
			
				if (is_numeric($cid)) {
					if ("1" == $cid) {
						$sourceSql .= " a.category > 10000 or ";
					}else {
						$sourceSql .= " a.category=$cid or ";
					}
				}
			}
		}

		if (sizeof($ownerlist)) {
		  	foreach ($ownerlist as $ownername) {
				//if (is_numeric($aid)) {
					$sourceSql .= " p.owner_name='" . mysql_escape_string($ownername) . "' or ";
				//}
			}
		}
		
		if (' or ' == substr($sourceSql,-4)) {
				$sourceSql = substr($sourceSql,0,-3);
		}	
			
		$sourceSql .= ") ";
	
		if (" () " == $sourceSql) $sourceSql = "";
								
		return ($sourceSql);
	
	}
	

	function dbConnect ( ) { 
		if ($this->dbconnection == "") {
			
			if (version_compare(phpversion(), "4.2.0", ">=")) {
				$this->dbconnection = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass, true);
			} else {
				$this->dbconnection = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass);
			}
			mysql_select_db($this->dbname, $this->dbconnection);
			print (mysql_error($this->dbconnection));
		}
	}
	
	function dbDisconnect ( ) {
		mysql_close($this->dbconnection);
	}
	
	function dbExecuteSql ($sqlcode) { 
		$this->dbConnect();
		$this->lastSQLRowsReturned = 0;
		$this->lastSQLErrorMessage = "";
								
		$resultset = mysql_query($sqlcode, $this->dbconnection);
		
		if (!$resultset) {
			print mysql_error($this->dbconnection);
			$this->lastSQLErrorMessage = mysql_error($this->dbconnection);
			$this->lastSQLRowsReturned = 0;
		}
		else
		{		
			$this->lastSQLRowsReturned = mysql_num_rows($resultset);
			$this->lastSQLErrorMessage = "";
		}
	
		if ($this->debugMode) {
		
			print "<!-- ";		
			print "SQL : $sqlcode\n";
			print "ROWS: {$this->lastSQLRowsReturned}\n";
			print " -->";
		}
			
		return ($resultset);
	}

	/**
	* Takes a MySql result set and converts it to an assoc array
	*
	*/
	function covertResultsetToArray($resultset) {
			$resultarray = array();	

		while ($row = mysql_fetch_assoc($resultset)) {
   		array_push ($resultarray,$row);
		}
	
		return ($resultarray);
	}	


/** The following methods are not data access per say, but do provide data back
    independing of formatting, and I did not want to include another file... */
	
	//function getImageToUse($row, $fileprefix) {
	function getImageToUse($filepath,$filename, $fileprefix) {
	
			$imagetoshow = '';
			$extension = strtolower(substr($filename,strrpos($filename,'.')));
						
			if ($extension == '.jpg' || $extension == '.jpeg' || $extension == '.gif' || $extension == '.png' ) {
				//code added to upgrade or downgrade a size if int or large not present	
				
				if (file_exists($this->fullpathtoalbums . $filepath . $fileprefix . $filename)) {
					$imagetoshow = $this->partialUrltoalbums .  $filepath . $fileprefix . $filename;
				}
				elseif ($fileprefix == $this->prefixIntermediate) {
					$imagetoshow = $this->partialUrltoalbums .  $filepath . $this->prefixLarge . $filename;
				}
				elseif ($fileprefix == $this->prefixLarge) {
					$imagetoshow = $this->partialUrltoalbums .  $filepath . $this->prefixIntermediate . $filename;
				}
				else {
					print "Error in getImageTouse: Extension (strtolower): $extension  File:" .  $this->fullpathtoalbums .  $filepath . $fileprefix . $filename . "<br />\n";
				}
			}
			// We are not going after a normal image file here, something special that needs to be handled differently
			else {
				$filetolookfor = substr($filename,0,strlen($filename) - strlen($extension));
				
				if (file_exists($this->fullpathtoalbums .  $filepath . $fileprefix . $filetolookfor . '.jpg')) {
					$imagetoshow = $this->partialUrltoalbums .  $filepath . $fileprefix . $filetolookfor . '.jpg';
				}
				elseif (file_exists($this->fullpathtoalbums .  $filepath . $fileprefix . $filetolookfor . '.gif')) {
					$imagetoshow = $this->partialUrltoalbums  . $filepath . $fileprefix . $filetolookfor . '.gif';
				}
				elseif ($fileprefix != $this->prefixThumbnail && (file_exists($this->fullpathtoalbums .  $filepath .$this->prefixThumbnail . $filetolookfor . '.jpg'))) {   
					$imagetoshow = $this->partialUrltoalbums .  $filepath . $this->prefixThumbnail . $filetolookfor . '.jpg';
				}	
				elseif ($fileprefix != $this->prefixThumbnail && (file_exists($this->fullpathtoalbums  . $filepath .$this->prefixThumbnail . $filetolookfor . '.gif'))) {   
					$imagetoshow = $this->partialUrltoalbums .  $filepath . $this->prefixThumbnail . $filetolookfor . '.gif';
				}	
				// This means we are gonna use the representative image that came with CPG
				else {
					$imagetoshow = $this->partialUrltoalbums . 'images/' . $this->getdefaultimagename($extension);
				}		
			}
		
			return ($imagetoshow);	
	}
		
	function urlEncodeImagePath($_name) {
			$newname = "";			

			if ($_name == "") {

			} else {
				$pathparts = pathinfo($_name);
				$newname = $pathparts['dirname'] . '/' . rawurlencode($pathparts['basename']);	
			}
			return ($newname);
	}

	function getdefaultimagename ($ext) {
		
		$ext = strtolower($ext);
	
		switch ($ext) {

			case ('.mp3'):
				$defImage='thumb_mp3.jpg';
				break;		
			case ('.mpeg'):
				$defImage='thumb_mpeg.jpg';
				break;		
			case ('.mpg'):
				$defImage='thumb_mpg.jpg';
				break;		
			case ('.avi'):
				$defImage='thumb_avi.jpg';
				break;		
			case ('.doc'):
				$defImage='thumb_doc.jpg';
				break;		
			case ('.wmv'):
				$defImage='thumb_wmv.jpg';
				break;		
			case ('.audio'): 
				$defImage='thumb_audio.jpg';
				break;		
			case ('.document'):
				$defImage='thumb_document.jpg';
				break;		
			case ('.gz'):
				$defImage='thumb_gz.jpg';
				break;		
			case ('.htm'):
				$defImage='thumb_htm.jpg';
				break;		
			case ('.html'):
				$defImage='thumb_html.jpg';
				break;		
			case ('.mid'):
				$defImage='thumb_mid.jpg';
				break;		
			case ('.midi'):
				$defImage='thumb_midi.jpg';
				break;		
			case ('.mov'):
				$defImage='thumb_mov.jpg';
				break;		
			case ('.movie'):
				$defImage='thumb_movie.jpg';
				break;		
			case ('.ogg'):
				$defImage='thumb_ogg.jpg';
				break;		
			case ('.qtv'):
				$defImage='thumb_qtv.jpg';
				break;		
			case ('.ra'):
				$defImage='thumb_ra.jpg';
				break;		
			case ('.ram'):
				$defImage='thumb_ram.jpg';
				break;		
			case ('.rar'):
				$defImage='thumb_rar.jpg';
				break;		
			case ('.rm'):
				$defImage='thumb_rm.jpg';
				break;		
			case ('.rmj'):
				$defImage='thumb_rmj.jpg';
				break;		
			case ('.swf'):
				$defImage='thumb_swf.jpg';
				break;		
			case ('.txt'):
				$defImage='thumb_txt.jpg';
				break;		
			case ('.wav'):
				$defImage='thumb_wav.jpg';
				break;		
			case ('.wma'):
				$defImage='thumb_wma.jpg';
				break;		
			case ('.xls'):
				$defImage='thumb_xls.jpg';
				break;		
			case ('.zip'):
				$defImage='thumb_zip.jpg';
				break;		
		
			default:
				$defImage=""; 
		}
	
		return ($defImage);
	
	}

   /**
	* Creates the href and img tags to be displayed
	*
	*
	*/	
	//function createlink($row) {
	function createlink($filepath, $filename, $aid, $pos, $imagelink="int") {
	
		$link= $this->partialUrltocpm;
					
		if ($imagelink == 'album' || $imagelink == 'thumb') {
			$link .= 'thumbnails.php?album=' . $aid;
		} elseif ($imagelink == 'int') {
			$link .= 'displayimage.php?pos=-' .	$pos;
		} elseif ($imagelink == 'large') {
			$link .= 'albums/' . $filepath . $filename;
		} elseif ($imagelink == 'none') {
			$link = '';
		} else {
			$link .=  'displayimage.php?pos=-' .	$pos;	
		}		
		
		return ($link);			
	
	} //end function
	
	
	function createDescription($format,$row, $failOnMissing=false) {
		$output = "";
		
		$didIfail = false;
		
		if ($format != "") {	
			
			$curpos = 0;
			$nextfind = 0;
			$lastpos = strlen($format);
					
			while ($curpos <= $lastpos) {
				$nextfind = strpos($format,'%',$curpos);
				
				if (false === $nextfind) {
					$output .= substr($format,$curpos);
					break;
				}
			
				$output .= substr($format,$curpos, ($nextfind - $curpos));
				$curpos = $nextfind + 1;
				
				switch ($format[$curpos]) {
					
					case ('a'):
						$output .= $row['aTitle'];
						if ("" == $row['aTitle']) $didIfail = true;					
						break;
					
					case ('A'):
						$output .= $row['mMsg_author'];
						break;
				
				 case ('c'):
						$output .= $row['pCaption'];
						if ("" == $row['pCaption']) $didIfail = true;					
						break;

					case ('C'):
						$output .= $row['mMsg_body'];
						break;

				  case ('d'):
						$output .= $row['aDescription'];
						if ("" == $row['aDescription']) $didIfail = true;					
						break;
					
				 case ('D'):
				 	  $timediff = time() - $row['pCtime'];
					  $output .= round($timediff / 86400, 0);
					  break;

				   case ('e'):
						$output .= $row['uUser_email'];
						break;
					
					case ('f'):
						$output .= $row['pFilename'];
						if ("" == $row['pFilename']) $didIfail = true;					
						break;
					
				   case ('h'):
						$output .= $row['pHits'];
						break;

				   case ('H'):
						$output .= $row['uUser_website'];
						break;
			
				   case ('i'):
						$output .= $row['pPid'];
						break;

				   case ('I'):
						$output .= $row['uUser_interest'];
						break;

				   case ('l'):
						$output .= $row['uUser_lastvisit'];
						break;

				   case ('L'):
						$output .= $row['uUser_location'];
						break;
		
					case ('o'):
						$output .= $row['pOwner_name'];
						if ("" == $row['pOwner_name']) $didIfail = true;
						break;

				   case ('O'):
						$output .= $row['uUser_occupation'];
						break;

					case ('p'):
						$output .= $row['pFilepath'];
						if ("" == $row['pFilepath']) $didIfail = true;					
						break;
				
				   case ('r'):
						$output .= $row['uUser_regdate'];
						break;

					case ('s'):
						$output .= $row['pFilesize'];
						if ("" == $row['pFilesize']) $didIfail = true;					
						break;
					
					case ('S'):
						// Formatted as KBytes
						$output .= round($row['pFilesize'] / 1024,1);
						break;
					
					case ('t'):
						$output .= $row['pTitle'];
						if ("" == $row['pTitle']) $didIfail = true;					
						break;
					
					// Number of votes for a given photo					
					case ('v'):
						$output .= $row['pVotes'];
						break;
					
					// Number of stars (Vote results)
					case ('V'):
						$output .= round($row['pPic_Rating'] / 2000,1);
						break;

					case ('w'):
						// Date formatted CTime				
						$output .= date($this->dateFormatString,$row['pCtime']);
						break;
					
					case ('W'):
						$output .= $row['pCtime'];
						break;

					case ('x'):
						$output .= $row['pWidth'];
						break;

					case ('y'):
						$output .= $row['pHeight'];
						break;
					
					case ('%'):
						$output .= '%';
						break;
					default:
						$output .= $format[$curpos];
				}
				$curpos++;
			}
		
			}// End of check to see if there is content
		
		if ($didIfail && $failOnMissing) {
			return (false);
		} else {
			return $output;
		}
	}


	function getRandomSeed() {
		return microtime()*1000000;
	}

}


?>