<?php

//  CPMFETCH INSTALL SCRIPT
//  RELEASE VERSION: 2.0.0

/*

The install script can take / recognize the following parameters

	do=install
	do=install-path
		path=../relative/path/to/cpg

	force=true 	// skip the checks for versions, etc...

*/




$INSTALLER_VERSION = "2.0.0";
//$INSTALLER_VERSION = "1.9.9";

// This indicates the last time the install was modified.  If the existing config is older than this, we will
// need to have the installer re-run.  If it is the same or newer, the install is optional.
$LAST_FLAGGED_VERSION = "1.9.9";  

$DBGO = array();	//Array to shove debug info into
$DBGO_MAX_LEN = 80;
$CURRCMD = "";		//Command we are executing
$PATHTOCPG = "..";	//Default path to CPG config files
$PATHTOCONFIG = ""; //Full relative path to config file
$PATHTOINIT = "";	//Full relative path to init file
$CPMFETCH_CONFIG_FILE = 'cpmfetch_config.php';

$SUPPORT_FORUM_URL = "http://coppermine-gallery.net/forum/index.php?board=87.0";
$SUPPORT_WEBSITE_URL = "http://cpmfetch.fistfullofcode.com";

$ERRMSG = "";		//Error messages
$ERRINSTCODE = 0;	//Instructions code on what to do with this error

$MYCONFIG;

// Global information on parameters
$settings = array (
	'cfBridgedTo' => 'false',
	'cfShowPrivate' => 'false',
	'cfDebugMode' => 'false',
	'cfDateFormatString' => 'd-M-Y',
	'cfDefaultDateFormatString' => 'd-M-Y',
	'cfTopPercentForTopRated' => '10',
	'cfTopPercentForMostViewed' => '25',
	'cfFileTypeFilter' => '',
	'cfShowPrivateOnSqlDefault' => ' ',
	'cfShowPrivateOffSqlDefault' => 'AND ((a.visibility = 0 OR a.visibility IS NULL) AND (a.alb_password IS NULL OR a.alb_password = "")) ',
	'cfDefaultImageSize' => 'thumb',
	'cfENABLE_cfrssget' => 'false',
	'cfENABLE_cfimageget' => 'false',
	'cfUseExistingDBConnection' => 'false',

	'cfSQLPictureSelect' => '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, p.pid AS pPid, p.pic_rating AS pPic_Rating,  p.votes AS pVotes, p.pwidth AS pWidth, p.pheight AS pHeight, p.user1 as pUser1, p.user2 as pUser2, p.user3 as pUser3, p.user4 as pUser4, c.cid as cCid, c.name as cName, c.description as cDescription, c.pos as cPos, c.parent as cParent, c.thumb as cThumb',

	'cfSQLAlbumSelect' => 'a.aid AS aAid, a.title AS aTitle, a.description AS aDescription, a.visibility as aVisibility, a.pos as aPos, a.category as aCategory, a.thumb as aThumb, a.keyword as aKeyword',

	'cfSQLUserSelect13' => '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',

	'cfSQLUserSelect' => 'u.user_lastvisit AS uUser_lastvisit,u.user_regdate AS uUser_regdate,u.user_email AS uUser_email,u.user_profile1 AS uUser_profile1,u.user_profile2 AS uUser_profile2,u.user_profile3 AS uUser_profile3,u.user_profile4 AS uUser_profile4,u.user_profile5 AS uUser_profile5,u.user_profile6 AS uUser_profile6',

	// This removed in 1.9.7 as it was causing issues with anonymous users
	//'cfSQLUserDataLink' => ' AND p.owner_id = u.user_id ',
	'cfSQLUserDataLink' => ' ',

	'cfSQLUserTableName' => 'users' //Updated when we read the CPG config table
);

$comments = array (
	'cfBridgedTo' => 'if not bridged leave as false, if is bridged you can put in a valid bridge name or just true for a default approach to bridging.',
	'cfSQLPictureDataSelect' => '**CAREFUL** SQL Fragment for selections from pictures table',
	'cfSQLAlbumDataSelect' => '**CAREFUL** SQL Fragment for selections from album table',
	'cfSQLUserDataSelect13' => '**CAREFUL** SQL Fragment for CPG 1.3 user tables',
 	'cfSQLUserDataSelect' => '**CAREFUL** SQL Fragment for CPG user tables',
	'cfSQLUserTableName' => '**CAREFUL** Name of user table to seek user information in',
	'cfSQLUserDataLink' => '**CAREFUL** SQL to link picture to user',
	'cfShowPrivate' => 'Consider non-public albums as displayable',
	'cfDebugMode' => 'Toggles debug mode on / off - put inline as HTML comments',
	'cfDateFormatString'  => 'How to format dates',
	'cfDefaultDateFormatString' => 'A date format as defined at http://www.php.net/manual/en/function.date.php',
	'cfTopPercentForTopRated'  => 'What percentage will be evaluated as being top rated',
	'cfTopPercentForMostViewed' => 'What percentage will be evaluated as being most viewed',
	'cfFileTypeFilter' => 'Filters out file types to display or not-display',
	'cfShowPrivateOnSqlDefault' => 'Do not touch unless you really need too',
	'cfShowPrivateOffSqlDefault' => 'Do not touch unless you really need too',
	'cfDefaultImageSize' => 'What size image to show?',
	'cfENABLE_cfrssget' => '',
	'cfENABLE_cfimageget' => '',
	'cfUseExistingDBConnection' => '',
	'filesystem_path_to_cpg' => 'File system path to your Coppermine Photo Gallery',
	'domain_name' => 'Your sites domain name',
	'cpg_album_url' => 'Full URL to your CPG gallerys album directory',
	'cpg_url' => 'Full URL to your CPG gallery'

);

printd("CpmFetch Install Script version 2.0.0");

//Check for command actions

printd ("do={$_REQUEST['do']}");
printd ("path={$_REQUEST['path']}");
printd ("force={$_REQUEST['force']}");

if (array_key_exists("do",$_REQUEST)) {
	switch ($_REQUEST['do']) {
		case ('install'):
			$CURRCMD = "install";
			printd("Command install issued to script");
			break;
		case ('install-path'):
			printd("Command install-path issued to script");
			if (array_key_exists('path',$_REQUEST)) {
				$PATHTOCPG = $_REQUEST['path'];
				printd("Install-path path setting: " . $PATHTOCPG);
			} else {
				printd("ERROR: Install-path path not submitted");
				$ERRMSG = 'install-path called without path submitted';
				$ERRINSTCODE = 10;
			}
			break;
	}

} else {
	printd("Running default command: install");
	$CURRCMD = "install";
}

// Get SERVER Vars
printd("* * BEGIN SERVER SETTINGS * *");
foreach ($_SERVER as $key => $value) {
	printd("SERVER $key: " . $value);
}
printd("* * END SERVER SETTINGS * *");




// Checking for path to coppermine photo gallery config file
if (! $ERRMSG) {
	$PATHTOCONFIG = $PATHTOCPG . "/include/config.inc.php";
	if (file_exists($PATHTOCONFIG)) {
		printd("Found config file at $PATHTOCONFIG");
	} else {
		printd("ERROR: Did not find config file at $PATHTOCONFIG");
		$ERRMSG = "ERROR: Did not find config file at $PATHTOCONFIG";
		$ERRINSTCODE = 20;
	}
}

// Checking for path to coppermine photo gallery init file
if (! $ERRMSG) {
	$PATHTOINIT = $PATHTOCPG . "/include/init.inc.php";
	if (file_exists($PATHTOINIT)) {
		printd("Found init file at $PATHTOINIT");
	} else {
		printd("ERROR: Did not find init file at $PATHTOINIT");
		$ERRMSG = "ERROR: Did not find init file at $PATHTOINIT";
		$ERRINSTCODE = 30;
	}
}

// Check to see if a the cpmfetch_config.php file exists
//  if so load it and check version numbers
//  if older than last flagged version continue
//  if newer then abort and prompt
if (! $ERRMSG) {
	if (! array_key_exists('force',$_REQUEST) || $_REQUEST['force'] != "true" ) {
		printd("Checking for existing cpmfetch config file");
		if (file_exists($CPMFETCH_CONFIG_FILE)) {
			printd("Found {$CPMFETCH_CONFIG_FILE} file - now reading");
			require("cpmfetch_config.php");

			if ($CONFIG_WRITTEN_VERSION == "INSTALL") {
				printd("Blank installation config found");
			} else {
				printd("Config file is version {$CONFIG_WRITTEN_VERSION} read in");
				printd("Last flagged version is {$LAST_FLAGGED_VERSION}");
				if (version_compare($LAST_FLAGGED_VERSION, $CONFIG_WRITTEN_VERSION) == 1 &&
				    version_compare($INSTALLER_VERSION, $CONFIG_WRITTEN_VERSION) == 1) {
					printd("Config written version is older than last flagged version - reinstall needed");
					$ERRINSTCODE = 35;
					$ERRMSG = "We need to re-run the install.php program";
					$INSTALLPARAMETERS = buildInstallParameters() . "&force=true";
				} elseif (version_compare($CONFIG_WRITTEN_VERSION, $INSTALLER_VERSION) == 1) {
					printd("Config written version is newer than install version - reinstall needed");
					$ERRINSTCODE = 37;
					$ERRMSG = "We need to re-run the install.php program";
					$INSTALLPARAMETERS = buildInstallParameters() . "&force=true";
				} else {
					printd("Config written version same or newer than last flagged version - reinstall optional");
					$ERRINSTCODE = 36;
					$ERRMSG = "A re-install is optional";
					$INSTALLPARAMETERS = buildInstallParameters() . "&force=true";
				}
			}
		} else {
			printd("No {$CPMFETCH_CONFIG_FILE} file found - normal in new installs");
		}

	} else {
		printd("force set, skipping version checks");
	}
}


// Check for write permission to cpmfetch_config.php

if (! $ERRMSG) {
	if (! is_writeable($CPMFETCH_CONFIG_FILE)) {
		printd("ERROR: $CPMFETCH_CONFIG_FILE is not writeable");
		$ERRMSG = "ERROR:  $CPMFETCH_CONFIG_FILE is not writeable";
		$ERRINSTCODE = 70;
		$INSTALLPARAMETERS = buildInstallParameters() . "&force=true";
	}
}

// Open and read in CPG config file
if (! $ERRMSG) {
	printd("Opening config file at $PATHTOCONFIG");
	include "$PATHTOCONFIG";
	regSetting("dbserver",$CONFIG['dbserver']);
	regSetting("dbuser", $CONFIG['dbuser']);
	regSetting("dbpass", $CONFIG['dbpass']);
	regSetting("dbname", $CONFIG['dbname']);
	regSetting("table_prefix",$CONFIG['TABLE_PREFIX']);
	printd("Retrieving config from database");
	
	$dbconnection = mysql_connect($CONFIG['dbserver'], $CONFIG['dbuser'], $CONFIG['dbpass']);

	if ($dbconnection) {
	
		//print (mysql_error($dbconnection));
		mysql_select_db($CONFIG['dbname'], $dbconnection);
		$SQLCode = 'SELECT * FROM `' .  $CONFIG['TABLE_PREFIX']  . 'config`';
	
		$resultset = mysql_query($SQLCode, $dbconnection);

		if ($resultset) {
			$array = covertResultsetToArray($resultset);
		
			printd("* * BEGIN CPG CONFIG TABLE * *");
		
			foreach ($array as $entry) {
				regSetting($entry['name'],$entry['value']);
				printd("CONFIG: " . $entry['name']. ": " . $entry['value']);
			}
		
			printd("* * END CPG CONFIG TABLE * *");
		} else {
			printd("ERROR: Database Config query problem:" . mysql_error($dbconnection));
			$ERRMSG = "ERROR: Database Config query problem:" . mysql_error($dbconnection);
			$ERRINSTCODE = 50;
		}

		$SQLCode = 'SELECT * FROM `' .  $CONFIG['TABLE_PREFIX']  . 'bridge`';
		$resultset = mysql_query($SQLCode, $dbconnection);
		if ($resultset) {
			$array = covertResultsetToArray($resultset);
		
			printd("* * BEGIN CPG BRIDGE TABLE * *");
		
			foreach ($array as $entry) {
				regSetting('bridge_'.$entry['name'],$entry['value']);
				printd("BRIDGE: " . $entry['name']. ": " . $entry['value']);
			}
		
			printd("* * END CPG BRIDGE TABLE * *");
		} else {
			printd("ERROR: Database Bridge query problem:" . mysql_error($dbconnection));
			$ERRMSG = "ERROR: Database Bridge query problem:" . mysql_error($dbconnection);
			$ERRINSTCODE = 50;
		}

		mysql_close($dbconnection);
		printd("Closed database connection");
	} else {
		printd("ERROR: Database connection to " . $CONFIG['dbserver'] . " failed:" . mysql_error($dbconnection));
		$ERRMSG = "ERROR: Database connection to " . $CONFIG['dbserver'] . " failed" . mysql_error($dbconnection);
		$ERRINSTCODE = 40;
	}

	//Update the user table with the prefix
	$settings['cfSQLUserTableName'] = $MYCONFIG['table_prefix'] .  $settings['cfSQLUserTableName'];

}

// Open and scan CPG Init file
if (! $ERRMSG) {
	printd("Opening init file at $PATHTOINIT");

	$initfile = @fopen ($PATHTOINIT, "r");

	if ($initfile) {
		printd("Reading init file at $PATHTOINIT");
		while (! feof($initfile)) {
			$buffer = fgets ($initfile,4096);
	
			//print strpos($buffer,"//") . "\n";
	
			if (strpos($buffer,"//") !== 0) { 
	
				if (strpos($buffer,"define('COPPERMINE_VERSION'") !== false) {
					//echo rtrim(ltrim($buffer));
					$parts = split("'",$buffer);
					regSetting("coppermine_version", $parts[3]);
					printd("InitFile: CPG Version " . $parts[3]);
				}
			}
		}		
		fclose($initfile);
		printd("Closing init file");
	} else {
		printd("ERROR: Could not open init file at $PATHTOINIT");
		$ERRMSG = "ERROR: Could not open init file at $PATHTOINIT";
		$ERRINSTCODE = 60;
	}
}

// Set some defaults we need to generate
if (! $ERRMSG) {
	printd("* * Generating Dynamic Defaults * *");

	if ($_GET['do'] == 'install-path') {
		// Ugly hack to support outside the CPG directory, should be rewritten to parse
		// the .. and . and form a real path
		$startpos = strpos($_SERVER["SCRIPT_FILENAME"],'/install.php');
		$fullpath = substr($_SERVER["SCRIPT_FILENAME"],0,$startpos+1) . $_GET['path'];
	} else {
		$startpos = strpos($_SERVER["SCRIPT_FILENAME"],'/cpmfetch/install.php');
		$fullpath = substr($_SERVER["SCRIPT_FILENAME"],0,$startpos+1);
	}

	$settings['filesystem_path_to_cpg'] = $fullpath;
	printd("filesystem_path_to_cpg:" . $settings['filesystem_path_to_cpg'] );

	$settings['domain_name'] = $_SERVER['SERVER_NAME'];
	printd("domain_name:" . $settings['domain_name']);
	$settings['cpg_album_url'] = $MYCONFIG['ecards_more_pic_target'] . $MYCONFIG['fullpath'];
	printd("cpg_album_url:" . $settings['cpg_album_url']);
	$settings['cpg_url'] = $MYCONFIG['ecards_more_pic_target'];
	printd("cpg_url:" . $settings['cpg_url']);
//	$settings['cpgdirectoryname'] = '';
}


// Lets set the bridged thing, hopefully this works for everyone :)
if (! $ERRMSG) {
	printd("* * Assigning bridged settings * *");

	printd("Bridge_enable: " . $MYCONFIG['bridge_enable']);
	printd("Bridge_short_name: " . $MYCONFIG['bridge_short_name']);

	if ($MYCONFIG['bridge_enable'] != 0 && $MYCONFIG['bridge_short_name'] != "") {
		printd("Setting bridge as {$MYCONFIG['bridge_short_name']} ");
		$settings['cfBridgedTo'] = $MYCONFIG['bridge_short_name'];
	} else {
		printd("Bridging is not enabled in CPG");
	}
}


// Open a configuration file for cpmfetch (cpmfetch_config.php)
if (! $ERRMSG) {
	printd("Opening cpmfetch config file: $CPMFETCH_CONFIG_FILE");
	$FH = @fopen ($CPMFETCH_CONFIG_FILE,"w+");
	// Write the configuration file for cpmfetch
	if ($FH) {
		printd("Writing cpmfetch config file $CPMFETCH_CONFIG_FILE");
		writeConfigHeader($FH);
		writeConfigUserDefined($FH);
		writeConfigOverrides($FH);
		writeConfigDefaults($FH);
		writeConfigSettings($FH);
		writeConfigFooter($FH);
		fclose($FH);
		printd("Completed writing config file");
	} else {
		printd("ERROR: Could not write cpmfetch config $CPMFETCH_CONFIG_FILE");
		$ERRMSG = "ERROR: Could not write cpmfetch config $CPMFETCH_CONFIG_FILE";
		$ERRINSTCODE = 80;
	}
}

printd("Producing output screen and exiting");
include "screen.php";
exit;


/*
* Build up a combination of the do= path= 
*
*
*/
function buildInstallParameters() {

	$text = "?";
	if (array_key_exists('do',$_GET)) {
		$text .= "do={$_GET['do']}"; 
	} else {
		$text .= "do=install"; 
	}

	if (array_key_exists('path',$_GET)) {
		$text .= "&path={$_GET['path']}";
	}

	return ($text);

}




function writeConfigHeader (&$FH) {
	global $INSTALLER_VERSION;
	fwrite($FH,"<?php\n\n");
	fwrite($FH,'$CONFIG_WRITTEN_VERSION="' . $INSTALLER_VERSION . '";' . "\n");
	fwrite($FH,"\n");

	$code = "/*\n";
	$code .= "Date generated: " . date("D M j G:i:s T Y") . " \n\n";

$code .= <<<EOT
This is your configuration file.  I recommend only editing the userDefined and the
override section.  There should be no earthly reason to touch any other part.

EOT;

	$code .= "\n*/\n\n\n";


	fwrite($FH,$code);
}

function writeConfigOverrides(&$FH) {
	global $settings, $comments;
	$code = "";

	$code = "\n\n";
	$code = "/*\n";
	$code .= headerline("User override settings go here");
	$code .= "These settings placed here will override settings elsewhere in the\n";
	$code .= "config file.  I have placed commented out copies of the cpmFetch created\n";
	$code .= "values for convienence along with a brief comment.\n";
	$code .= "*/ \n";

	$code .= "\n\n";
	$code .= '$config_overrides = array();' . "\n";

	foreach (array_keys($settings) as $entry) {

		if (array_key_exists($entry,$comments)) {
			$code .= "// " . $comments[$entry] . "\n";
		}

		$code .= "//  ";
		$code .= '$config_overrides[\'';
		$code .= $entry;
		$code .= '\'] = \'';
		$code .= $settings[$entry];
		$code .= '\';';
		$code .="\n\n";
	}

	$code .= "\n\n";

	fwrite($FH,$code);

}

function writeConfigDefaults(&$FH) {
	global $settings, $comments;

	$code = "\n\n";
	$code = "/* \n";
	$code .= headerline("CpmFetch default values - No need to change");
	$code .= "These settings were created by the cpmFetch install program.  If you want to override\n";
	$code .= "any of these, you can add them into the config_overrides section.\n";
	$code .= "\n*/ \n";

	$code .= '$config_cpmfetchSettings = array(';
	foreach (array_keys($settings) as $entry) {
		$code .= "\n\t'" .  $entry . "'" . " => " . "'" .  $settings[$entry]  . "',";
	}

	$code = rtrim ($code,",");
	
	$code .= "\n);\n";
	$code .= "\n\n\n\n\n";

	fwrite($FH,$code);
}

function writeConfigSettings(&$FH) {
		global $MYCONFIG;


		$code = "/*\n";
		$code .= headerline("Settings retrieved from Coppermine Photo Gallery");
		$code .= "These settings were copied from your CPG database.  If you want to override\n";
		$code .= "any of these, you can add them into the config_overrides section.\n";
		$code .= "*/ \n";
		$code .= '$config_cpgSettings = array(';
		foreach (array_keys($MYCONFIG) as $entry) {
			$code .= "\n\t'" .  $entry . "'" . " => " . "'" .  $MYCONFIG[$entry]  . "',";
		}
		$code = rtrim ($code,",");
		$code .= "\n);\n";
		$code .= "\n\n\n\n";

		fwrite($FH,$code);
}


function writeConfigUserDefined(&$FH) {

	$code = '';
	$code = "/* \n";
	$code .= headerline("User defined configuration settings go here");
	$code .= "This allows you to set your own information into the configuration\n";
	$code .= "by simply expanding this associative array\n";
	$code .= "*/ \n";

	$code .= '$config_userDefined = array();' . "\n";
	$code .= "\n\n\n";
	fwrite($FH,$code);

}

function writeConfigFooter(&$FH) {
	fwrite($FH,"?>\n");
}

function regSetting ($name, $value) {
	global $MYCONFIG;
	if (strtolower($name) != "forbiden_fname_char") {
		$MYCONFIG[strtolower($name)] = $value;
	}
}


function printArray(&$DBGO, $EOL) {
	foreach ($DBGO as $element) {
		print $element . $EOL;
	}
}

/**
* 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);
}


function printd ($msg) {
	global $DBGO, $DBGO_MAX_LEN;

	while (strlen($msg) > 0) {
		$linemsg = substr($msg,0,$DBGO_MAX_LEN);
		$msg = substr($msg,$DBGO_MAX_LEN);
		array_push($DBGO,$linemsg);
	}
}

function headerline($_text) {
	$border = str_repeat('=',strlen($_text));
	$text = strtoupper($_text);
	return ($border . "\n" . $text . "\n" . $border . "\n\n");
}




?>
