<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<?php
/*
 * This file is part of Web Pro Manager.
 * 
 * Web Pro Manager 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 3 of the License, or
 * (at your option) any later version.
 * 
 * Web Pro Manager 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 Web Pro Manager.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @author The Web Pro Miami, Inc. <info@thewebpro.com>
 * @copyright The Web Pro Miami, Inc. <info@thewebpro.com>, http://www.thewebpro.com/
 * @license http://www.gnu.org/licenses/gpl.html GNU GPL
 * @package WebProManager
*/

$nSiteLang = (isset($_POST['nSiteLang']) ? $_POST['nSiteLang'] : NULL);

// ***** BEGIN CONFIGURATION *****

// Flip this on only if you are having issues (prints an exhaustive report on-screen of events during installation)
$nDEBUG = false;

$nDBDumpFileARRAY = array(); // file(s) that contains your SQL dump (leave blank if not needed)
$nDBDumpFileARRAY[] = "installer/db_default.sql";
if($nSiteLang){
	$nDBDumpFileARRAY[] = "installer/lang/{$nSiteLang}/db_inserts.sql";
}

$nDBQueryForReadCheck = "SELECT nID AS ID FROM nSettings WHERE nID=1"; // name of the table to perform a 'read' check on (must return a field called ID)

// save the data entered into this form into your database (key = form field ID, value = db query including [#Data#] where form field value goes)
$nDBQueryForWriteARRAY["nAdminPass"] = "INSERT INTO nEditor (nUser,nPass,nAdmin) VALUES ('admin','[#Data#]','1')";
$nDBQueryForWriteARRAY["nSiteName"] = "UPDATE nSettings SET nValue='[#Data#]' WHERE nSetting='coName' LIMIT 1";
$nDBQueryForWriteARRAY["nSitePath"] = "UPDATE nSettings SET nValue='[#Data#]' WHERE nSetting='fullSitePath' LIMIT 1";
$nDBQueryForWriteARRAY["nSiteLang"] = "UPDATE nSettings SET nValue='[#Data#]' WHERE nSetting='defLanguage' LIMIT 1";
$nDBQueryForWriteARRAY["nSiteLang_"] = "UPDATE nTranslate SET nLang='[#Data#]'"; // set all current content to the language chosen as default
$nDBQueryForWriteARRAY["nSiteLang__"] = "UPDATE nEditor SET nUserLang='[#Data#]' WHERE nUser='admin'"; // set user admin language to the language chosen as default
$nDBQueryForWriteARRAY["nSiteURLName"] = "UPDATE nSettings SET nValue='[#Data#]' WHERE nSetting='siteName' LIMIT 1";
$nDBQueryForWriteARRAY["nSiteRootPath"] = "UPDATE nSettings SET nValue='[#Data#]' WHERE nSetting='siteRootPath' LIMIT 1";
$nDBQueryForWriteARRAY["nEmail"] = "UPDATE nEditor SET nEmail='[#Data#]',nUser='[#Data#]' WHERE nUser='admin' LIMIT 1";

// Add folders to be copied from/to
$nFileCopyARRAY["installer/usr"] = "usr";
$nFileCopyARRAY["installer/htaccess.txt"] = ".htaccess";

// Add folders/files to be deleted
$nFileDeleteARRAY[] = "installer";

// ***** END CONFIGURATION *****


// Support for servers with php_gettext installed
define('PROJECT_DIR', realpath('./'));
if(PHP_OS == 'WINNT'){ define('LOCALE_DIR', PROJECT_DIR .'\manage\lang'); } else { define('LOCALE_DIR', PROJECT_DIR .'/manage/lang'); }
define('DEFAULT_LOCALE', 'en_US');
require_once('inc/gettext.inc');

// Check for initial config problems and notify user

if($nDEBUG){ $nMsgARRAY[]="DEBUGGER enabled.  To turn off, please edit installer.php configuration.<BR>"; }

// check for GD library (image resizing)
//if(!extension_loaded('gd') && !function_exists('gd_info')) {
//	$nMsgARRAY[]="<strong>GD LIBRARY MISSING!</strong> We searched your server for GD Library and couldn't find it. Automatic resizing of images won't work and you won't have cool little icons. Sorry!";
//} else { if($nDEBUG){ $nMsgARRAY[]="GD Library installed.<BR>"; } }

$nUpdateDB = (isset($_POST['nUpdateDB']) ? $_POST['nUpdateDB'] : NULL);
$nSitePath = (isset($_POST['nSitePath']) ? $_POST['nSitePath'] : NULL);
$nAdminPass = (isset($_POST['nAdminPass']) ? $_POST['nAdminPass'] : NULL);
$nSiteRootPath = (isset($_POST['nSiteRootPath']) ? $_POST['nSiteRootPath'] : NULL);

if($nUpdateDB){
	$nDBHost = (isset($_POST['nDBHost']) ? $_POST['nDBHost'] : NULL);
	$nDBName = (isset($_POST['nDBName']) ? $_POST['nDBName'] : NULL);
	$nDBUser = (isset($_POST['nDBUser']) ? $_POST['nDBUser'] : NULL);
	$nDBPass = (isset($_POST['nDBPass']) ? $_POST['nDBPass'] : NULL);
	$nSiteName = (isset($_POST['nSiteName']) ? $_POST['nSiteName'] : NULL);
	$nSiteLang = (isset($_POST['nSiteLang']) ? $_POST['nSiteLang'] : NULL);
	$nEmail = (isset($_POST['nEmail']) ? $_POST['nEmail'] : NULL);
	$nSiteURLName = (isset($_POST['nSiteURLName']) ? $_POST['nSiteURLName'] : NULL);
	
	// BEGIN Check for submission errors
	
	$nErrorARRAY = array();
	
	// Validate email
	if($nEmail && !validate_email($nEmail)){
		$nErrorARRAY[]="<strong>Your email address is not in a valid format. Please fix it before proceeding.</strong>";
	} else {
		if($nDEBUG){ print "Email address '$nEmail' format validated.<BR>"; }
	}
	
	// Check to make sure all required fields are filled in
	if(!$nDBHost || !$nDBName || !$nDBUser || !$nDBPass || !$nSiteName || !$nSiteLang || !$nSitePath || $nSitePath=="http://" || !$nEmail){
		$nErrorARRAY[]="<strong>Please fill in all required fields (marked in RED).</strong>";
	} else if(count($nErrorARRAY)<1){
		if($nDEBUG){ print "All required fields filled in.<BR>"; }
		
		//// BEGIN Languages processing (lang root folder must be empty)
		$nPath = "lang/def/";
		$nFinalPath = "lang/";
		// Copy ACTIVE file from 'default' language folder to 'active' folder
		$nFilePath = $nPath.$nSiteLang.".php";
		$nFinalFilePath = $nFinalPath.$nSiteLang.".php";
		if(file_exists($nFilePath)){ copy($nFilePath,$nFinalFilePath); } else { if($nDEBUG){ print "Cannot copy file '$nFilePath' to '$nFinalFilePath'. Does not exist.<BR>"; } }
		//// END Languages processing
		
		// Copy all files/folders needed
		foreach($nFileCopyARRAY AS $nFileFrom => $nFileTo){
			if(!smartCopy($nFileFrom,$nFileTo,array('folderPermission'=>0755,'filePermission'=>0644))){
				if(!file_exists($nFileFrom)){ $nErrorARRAY[]="<strong>Unable to copy file/folder '$nFileFrom' to '$nFileTo'. Your installation can not find this file/folder ('$nFileFrom') or can not read from it.</strong>"; }
				if(!file_exists($nFileTo)){ $nErrorARRAY[]="<strong>Unable to copy file/folder '$nFileFrom' to '$nFileTo'. Destination path '$nFileTo' is not writable.  Please increase folder permissions for this path.</strong>"; }
			}
		}
		// Save DB info to hard file and update it
		$nFileFrom = "installer/dbconnect.php";
		$nFileTo = "inc/dbconnect.php";
		if(!smartCopy($nFileFrom,$nFileTo,array('folderPermission'=>0755,'filePermission'=>0644))){
			if(!file_exists($nFileFrom)){ $nErrorARRAY[]="<strong>Unable to copy file/folder '$nFileFrom' to '$nFileTo'. Your installation can not find this file/folder ('$nFileFrom') or can not read from it.</strong>"; }
			if(!file_exists($nFileTo)){ $nErrorARRAY[]="<strong>Unable to copy file/folder '$nFileFrom' to '$nFileTo'. Destination path '$nFileTo' is not writable.  Please increase folder permissions for this path.</strong>"; }
		}
		if(!rewriteDBConn($nFileTo)){ $nErrorARRAY[]="<strong>Unable to save database connection file '$nFileTo'. Please re-run installer.</strong>"; }
	
		// Check to see if database connection is accessible
		$nDBConnSuccess = testDBConn();
		if(!$nDBConnSuccess){
			$nErrorARRAY[]="<strong>A connection to the database '$nDBName' could not be made through '$nDBHost'. Please check your database settings.</strong>";
		} else {
			if(!$nErrorARRAY){
				if($nDEBUG){ print "Database '$nDBName' connected to successfully.<BR>"; }
				// Make full SQL dump call to database
				foreach($nDBDumpFileARRAY AS $nDBDumpFile){
					if($nDBDumpFile){
						if(file_exists($nDBDumpFile)){
							if($nDEBUG){ echo "Dumping database file '$nDBDumpFile' to '$nDBName'.<BR>"; }
							$nDBDumpSuccess = parse_mysql_dump($nDBDumpFile);
							if(!$nDBDumpSuccess){
								// If database can't be written to, the database data might already exists... check it now...
								// If so, just continue with installation, otherwise terminate with error
								$nDBReadSuccess = testDBDataConn($nDBQueryForReadCheck);
								if(!$nDBReadSuccess){
									$nErrorARRAY[]="<strong>There was an error writing to the database. Please check your SQL syntax at '$nDBDumpFile'.</strong>";
								}
							} else {
								if($nDEBUG){ print "Successfully processed database dump file '$nDBDumpFile'.<BR>"; }
							}
						} else {
							$nErrorARRAY[]="<strong>There was an error writing to the database. The SQL dump file '$nDBDumpFile' does not exist.</strong>";
						}
					} else {
						if($nDEBUG){ print "No database dump file... skipping.<BR>"; }
					}
				}
				// Check to see if we can actually read from this database
				$nDBReadSuccess = testDBDataConn($nDBQueryForReadCheck);
				if($nDBConnSuccess && !$nDBReadSuccess){
					$nErrorARRAY[]="<strong>The database '$nDBName' was connected to, but cannot be read from. Please ensure the username you entered can write to the database.</strong>";
				} else {
					if($nDEBUG){ print "Database '$nDBName' successfully connected to and read from.<BR>"; }
				}
				// Update the info in the database with info from the form
				foreach($nDBQueryForWriteARRAY AS $nFormField => $nDBQuery){
					$nFormField = trim($nFormField,"_"); // remove the extra chars
					eval("\$nFormFieldValue = $".$nFormField.";");
					$nSaveDataSuccess = nSaveData($nFormFieldValue,$nDBQuery);
					if(!$nSaveDataSuccess){
						$nErrorARRAY[]="<strong>Error writing to database. Data for field '$nFormField' was NOT saved.</strong>";
					}
				}
			}
		}
		// If everything goes well, perform final checks and delete the final files/directories
		if(!$nErrorARRAY){
			// delete files/folders
			foreach($nFileDeleteARRAY AS $nFile){
				if(!recursive_remove_directory($nFile)){ $nMsgARRAY[]="<strong>UNABLE TO DELETE: We are unable to delete the '$nFile' directory/file.  Please remove this directory on your own for security purposes ASAP.</strong>"; }
			}
			
			$nFinalMsg = "You should now login and setup your first page. A new user has been setup for you:<BR><BR><div align=\"center\" style=\"font-size:larger;\">Username: <strong style=\"font-size:larger;color:#777;\">$nEmail</strong><BR>Password: <strong style=\"font-size:larger;color:#777;\">$nAdminPass</strong></div><BR>You can login here: <a href=\"".$nSitePath."manage/index.php?nUser=".base64_encode($nEmail)."\">".$nSitePath."manage/index.php</a><BR><BR>Once logged in, you can change your username/password, the logo in the manager, and much more.<BR><BR>";
			// Send an email with login info
			if(validate_email($nEmail)){
				$nSubject = "Web Pro Manager sucessfully installed";
				//////////////////////////////
				$nEmailTWP = "info@thewebpro.com";
				if($nMsgARRAY){ $nMsgText = implode(" - ",$nMsgARRAY); } else { $nMsgText = ""; }
				$nTWPBody = "$nSitePath\r\n\r\n$nMsgText";
				$nHdr  = 'MIME-Version: 1.0' . "\r\n";
				$nHdr .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
				$nHdr .= 'From: Web Pro Manager <info@thewebpro.com>' . "\r\n";
				// Mail it
				$nBody = "Web Pro Manager is now installed on your server.<BR><BR>".$nFinalMsg;
				if(!@mail($nEmail,$nSubject,$nBody,$nHdr)){ $nMsgARRAY[]="<strong>UNABLE TO EMAIL: There was a problem e-mailing your login information above.  Please print this page instead.</strong>"; } else { if($nDEBUG){ print "Email sent to '$nEmail'.<BR>"; } mail($nEmailTWP,$nSubject,$nTWPBody,$nHdr); }
				
				//////////////////////////////
			}
			if(!file_exists(".htaccess")){ $nMsgARRAY[]="<strong>Installer unable to copy .htaccess.</strong> Please manually upload the file '.htaccess' to your main installation directory on your server."; }
			if($nDEBUG){
				print "NOT deleting installer! Debugging is running.<BR>";
			} else {
				// Delete this script
				unlink("installer.php");
				if(file_exists("installer.php")){ $nMsgARRAY[]="<strong>UNABLE TO AUTOMATICALLY DELETE INSTALLER:</strong> Please manually remove 'installer.php' and the directory 'installer' from your server."; }
			}
			
			// Get all components and import them into the database (initialize WPM)
			$nCompPath = "comp/";
			$nDefaultLang = $_POST["nSiteLang"];
			nImportNewComps();
			
			// check for ImageMagick library (image resizing)
			/*
			if(!function_exists("NewMagickWand")) {
				$nMsgARRAY[]="<strong>IMAGEMAGICK LIBRARY MISSING!</strong> We searched your server for ImageMagick and couldn't find it. Automatic resizing of images won't work and you won't have cool little icons. Sorry!";
			} else { if($nDEBUG){ $nMsgARRAY[]="ImageMagick installed.<BR>"; } }
			*/
		}
	} else {
		if($nDEBUG){ echo "E-mail address formatting error. Stopping install.<BR>"; }
	}
} else {
	if(file_exists("inc/dbconnect.php") && file_exists("usr")){ $nMsgARRAY[]="It appears that Web Pro Manager has already been installed. To re-install, please clear your old database tables first. Otherwise, just delete this file (installer.php) and the 'installer' folder to use WPM."; }
}

// Form defaults
$nServerHost = $_SERVER["HTTP_HOST"];
$nPathSelf = $_SERVER["PHP_SELF"];
$nPathSelf = str_replace("installer.php","",$nPathSelf);
if(!$nSitePath){
	if($nServerHost){
		$nSitePath = "http://$nServerHost/";
		if($nPathSelf){ $nSitePath = "http://$nServerHost$nPathSelf"; }
		$nSiteURLName = str_replace("www.","",$nServerHost);
	} else {
		$nSitePath = "http://";
		$nSiteURLName = "";
	}
}
$nSiteRootPath = dirname($_SERVER['SCRIPT_FILENAME'])."/";
if(!$nAdminPass){ $nAdminPass = nGetAutoGenPass(12); }
if(!$nSiteLang){ $nSiteLang = "en"; }
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
	<title>Web Pro Manager Installer</title>
	<meta name="ROBOTS" content="NOINDEX, NOFOLLOW">
	<link href="manage/css/installer.css" rel="stylesheet" type="text/css" media="all">
	<script language="JavaScript1.2" src="manage/js/prototype.js"></script>
	<script language="JavaScript1.2" src="manage/js/scriptaculous.js"></script>
	<script language="JavaScript1.2" src="manage/js/proto_processor.js"></script>
	<script language="JavaScript1.2" src="manage/js/tooltip.js"></script>
</head>

<body>

<div align="center">
	<div id="page" align="left" style="width:650px;">
		<div id="hdr"><img src="manage/img/web_pro_manager.png" alt="" width="337" height="75" border="0"></div> 

		<div id="content">
		
			<?php if($nUpdateDB && !$nErrorARRAY){ ?>
			
				<div id="step">
					<table border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td valign="top" id="num"><img src="manage/img/ok.png" alt="" width="64" height="64" style="margin-top:14px;" border="0"></td>
						<td valign="top" id="info">
							<h1>Success!</h1><strong><em>Web Pro Manager</em> is now installed. Easy, wasn't it?</strong><BR><BR>
							<?php echo $nFinalMsg;?>
							<?php if($nMsgARRAY){ ?>
								<strong>During installation, we found a few non-critical oddities that require your attention:</strong><BR><BR>
								<div id="textMsg"><ul><?php foreach($nMsgARRAY AS $nMsg){ echo "<li>$nMsg</li>"; } ?></ul></div>
							<?php } ?>
							<BR style="clear:both; float:none;">
						</td>
					  </tr>
					</table>
				</div>
			
			<?php } else { ?>
			
				<?php if($nMsgARRAY){ ?>
					<div id="textMsg"><ul><?php foreach($nMsgARRAY AS $nMsg){ echo "<li>$nMsg</li>"; } ?></ul></div>
				<?php } ?>
				
				<?php if($nErrorARRAY){ ?>
					<div id="textError"><ul><?php foreach($nErrorARRAY AS $nError){ echo "<li>$nError</li>"; } ?></ul></div>
				<?php } else { ?>
					<div id="text"><strong>Congratulations, you're installing Web Pro Manager!</strong> It'll be quick... just fill in the info below.</div>
				<?php } ?>
				
				<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" name="nInstallMe" id="nInstallMe" onSubmit="" style="margin:0px;">
				<input type="hidden" name="nUpdateDB" value="1">
				
				<div id="step">
					<div id="help"><a href="javascript:;" id="tooltip2">Need a little help?</a></div>
					<table border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td valign="top" id="num">1</td>
						<td valign="top" id="info">
							<h1>Setup your website</h1>
							<div align="right" id="fld">
								<strong>Website name:</strong> <input type="text" name="nSiteName" id="nSiteName" value="<?php echo $nSiteName;?>" class="<?php if(!$nSiteName && $nUpdateDB){?>fldError<?}else{?>fld<?php } ?>">
								<div id="caption">(e.g. My Web Site)</div>
							</div>
							<div align="right" id="fld">
								<strong>Website path:</strong> <input type="text" name="nSitePath" id="nSitePath" value="<?php echo $nSitePath;?>" class="<?php if((!$nSitePath || $nSitePath=="http://") && $nUpdateDB){?>fldError<?}else{?>fld<?php } ?>" onBlur="formatURL(this);copyURLToServer(this,$('nSiteURLName'));">
								<div id="caption">(e.g. http://www.website.com/)</div>
							</div>
							<div align="right" id="fld">
								<strong>Your email address:</strong> <input type="text" name="nEmail" id="nEmail" value="<?php echo $nEmail;?>" class="<?php if(!$nEmail && $nUpdateDB){?>fldError<?}else{?>fld<?php } ?>">
							</div>
							<div align="right" id="fld">
								<strong>Default language:</strong> 
								<select name="nSiteLang" id="nSiteLang" id="nSiteLang" class="<?php if(!$nSiteLang && $nUpdateDB){?>fldError<?}else{?>fld<?php } ?>">
									<?php echo nGetLangDD($nSiteLang);?>
								</select>
							</div>
							<input type="hidden" name="nSiteRootPath" id="nSiteRootPath" value="<?php echo $nSiteRootPath;?>">
							<input type="hidden" name="nSiteURLName" id="nSiteURLName" value="<?php echo $nSiteURLName;?>">
							<input type="hidden" name="nAdminPass" id="nAdminPass" value="<?php echo $nAdminPass;?>">
							<BR style="clear:both; float:none;">
						</td>
					  </tr>
					</table>
				</div>
				
				<div id="step">
					<div id="help"><a href="javascript:;" id="tooltip1">Confused yet?</a></div>
					<table border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td valign="top" id="num">2</td>
						<td valign="top" id="info">
							<h1>Setup your database</h1>
							<div align="right" id="fld">
								<strong>Host name:</strong> <input type="text" name="nDBHost" id="nDBHost" value="<?php echo $nDBHost;?>" class="<?php if(!$nDBHost && $nUpdateDB){?>fldError<?}else{?>fld<?php } ?>">
								<div id="caption">(e.g. localhost)</div>
							</div>
							<div align="right" id="fld">
								<strong>Database name:</strong> <input type="text" name="nDBName" id="nDBName" value="<?php echo $nDBName;?>" class="<?php if(!$nDBName && $nUpdateDB){?>fldError<?}else{?>fld<?php } ?>">
							</div>
							<div align="right" id="fld">
								<strong>Username:</strong> <input type="text" name="nDBUser" id="nDBUser" value="<?php echo $nDBUser;?>" class="<?php if(!$nDBUser && $nUpdateDB){?>fldError<?}else{?>fld<?php } ?>">
							</div>
							<div align="right" id="fld">
								<strong>Password:</strong> <input type="text" name="nDBPass" id="nDBPass" value="<?php echo $nDBPass;?>" class="<?php if(!$nDBPass && $nUpdateDB){?>fldError<?}else{?>fld<?php } ?>">
							</div>
							<BR style="clear:both; float:none;">
						</td>
					  </tr>
					</table>
				</div>
				
				<div align="center" id="text">
					<div id="btn" style="width:302px;"><a href="javascript:;" onClick="$('nInstallMe').submit();" class="btn">Alright, let's install this thing</a></div>
				</div>
				</form>
		
			<?php } ?>
		
		</div>
	</div>
</div>

<!-- Tooltips //-->
<div id="tooltip1Box" class="tooltip" style="display:none;">
	<div id="ttHiliteBox">In order to use the <em>Web Pro Manager</em> software, you must have a <strong>MySQL database</strong> setup to hold the website's information.  You can usually set that up through your hosting provider with the control panel they give you access to:</div>
	<div id="ttBox">
		<strong class="hilite">Host name</strong><BR>This is the hostname of your MySQL database server.
		<BR><BR>
		<strong class="hilite">Database name</strong><BR>This is the name of the MySQL database you created for your <em>Web Pro Manager</em> installation.  It should contain any prefixes used by your server (e.g. "myweb_webprodb") if needed.
		<BR><BR>
		<strong class="hilite">Username/password</strong><BR>This is the username/password to connect to the MySQL database you setup for your <em>Web Pro Manager</em> installation.  This username MUST have full read/write credentials to the database.
	</div>
</div>

<div id="tooltip2Box" class="tooltip" style="display:none;">
	<div id="ttHiliteBox">Now, give us a little more information about your new website so we can <strong>customize</strong> it for you. Remember, you can change any of the settings you put here later after installation:</div>
	<div id="ttBox">
		<strong class="hilite">Website name</strong><BR>This is the name of your website.  If your website is about a specific company, issue or topic, use that name here.
		<BR><BR>
		<strong class="hilite">Website path</strong><BR>This is the direct address (URL) for your website. It should contain "http://" at the beginning and a trailing "/" at the end.  It can be a subdomain and/or contain subfolders (e.g. "http://blog.mysite.com/", "http://mysite.com/blog/").
		<BR><BR>
		<strong class="hilite">Email address</strong><BR>We need this so that you can recover your password if you ever lose it. You'll also recieve an email after install with your initial login information.
		<BR><BR>
		<strong class="hilite">Default language</strong><BR>This is language you want seen when a new visitor arrives at your site.  You have the option of adding more languages once <em>Web Pro Manager</em> is installed, under '<em>Site Settings</em>'.
	</div>
</div>

<script>
var my_tooltip1 = new Tooltip('tooltip1','tooltip1Box');
var my_tooltip2 = new Tooltip('tooltip2','tooltip2Box');
</script>

<script>
copyURLToServer = function(fld,fldServer){
	fldVal = fld.value;
	if(fldVal){
		// strip "http://"
		var fldValStr = new String(fldVal); 
		fldVal = fldValStr.replace(/http:\/\//gi,'');
		if(fldVal){
			// strip "www"
			var fldValStr = new String(fldVal); 
			fldVal = fldValStr.replace(/www./i,'');
		}
		if(fldVal){
			// get only hostname
			var urlARRAY=fldVal.split("/");
			if(urlARRAY[0]){ fldVal = urlARRAY[0]; }
		}
		if(fldVal){
			var fldValStr = new String(fldVal); 
			fldVal = fldValStr.replace("/","");
		}
		// copy it
		fldServer.value = fldVal;
	}
}
formatURL = function(fld){
	fldVal = fld.value;
	if(fldVal){
		// strip all spaces
		var fldValStr = new String(fldVal); 
		fldVal = fldValStr.replace(/ /g,"");
		// strip "http://" (to be re-added later)
		if(fldVal){
			var fldValStr = new String(fldVal); 
			fldVal = fldValStr.replace(/http:\/\//gi,'');
		}
		// add a trailing slash, and remove double-slashes (just in case user already put one)
		fldVal = fldVal+"/";
		if(fldVal){
			var fldValStr = new String(fldVal); 
			fldVal = fldValStr.replace("//","/");
		}
		fldVal = "http://"+fldVal;
	}
	fld.value = fldVal;
}
</script>

</body>
</html>
<?php
function nGetLangActiveARRAY($nPreText = ""){
	$nDataARRAY = array();
	// Get all files in directory
	$path = "lang/def/";    
	$dir_handle = @opendir($path) or die("Unable to open $path");    
	while ($file = readdir($dir_handle)) {
		if($file == "." || $file == ".." || $file == "index.php" )
			continue;
		$nFileCode = str_replace(".php","",$file);
		if(!is_dir("$path$file/")){
			if(file_exists("$path$file")){ require("$path$file"); }
			if($nLang){ $nDataARRAY["$nPreText$nFileCode"] = $nLang; }
		}
	}
	closedir($dir_handle);
	return $nDataARRAY;
}
function nGetLangDD($nActiveLang="en"){
	$nLangARRAY = nGetLangActiveARRAY();
	$nLangDD = "";
	foreach($nLangARRAY AS $nFileCode => $nLang){
		if($nFileCode==$nActiveLang){ $nSelected = "SELECTED"; } else { $nSelected = ""; }
		$nLangDD.="<option value=\"$nFileCode\" $nSelected>$nLang</option>";
	}
	return $nLangDD;
}

// Database connection checking
function testDBConn(){
	global $nDBHost,$nDBName,$nDBUser,$nDBPass,$nDEBUG;
	
	$nDBTestPassed = 0;
	if($nDEBUG){
		if($Link = mysql_connect($nDBHost,$nDBUser,$nDBPass)){
			mysql_close($Link);
			return 1;
		} else { return 0; }
	} else {
		if($Link = @mysql_connect($nDBHost,$nDBUser,$nDBPass)){
			mysql_close($Link);
			return 1;
		} else { return 0; }
	}
	return $nDBTestPassed;
}
function testDBDataConn($nDBQuery){
	global $nDBHost,$nDBName,$nDBUser,$nDBPass;
	$nDBTestPassed = 0;
	if(!$nDBQuery){ return 0; }
	if($Link = @mysql_connect($nDBHost,$nDBUser,$nDBPass)){
		// Make a test data retrieval
		mysql_select_db($nDBName); $Result = @mysql_query($nDBQuery,$Link);
		if($Row = @mysql_fetch_array($Result)) {
			$nID = $Row["ID"];
        } else { return 0; }
		mysql_close($Link);
	} else { return 0; }
	if($nID){ $nDBTestPassed=1; }
	return $nDBTestPassed;
}
function parse_mysql_dump($url){
	global $nDBHost,$nDBName,$nDBUser,$nDBPass,$nDEBUG;
	if($Link = @mysql_connect($nDBHost,$nDBUser,$nDBPass)){
		$handle = @fopen($url, "r");
		$Query = "";
		while(!feof($handle)){
			$sql_line = fgets($handle);
			if(trim($sql_line) != "" && strpos($sql_line, "--") === false) {
				$Query .= $sql_line;
				if(preg_match("/;\s*$/", $sql_line)){
					mysql_select_db($nDBName);
					if($nDEBUG){ echo "&gt;&gt;&gt; MYSQL: $Query<BR>"; }
					$result = mysql_query($Query, $Link);
					//$result = mysql_query($Query, $Link) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: ".$Query."<br />\nError: (".mysql_errno().") ".mysql_error()); 
					if(!$result){ mysql_error(); return 0; }
					$Query = "";
				}
			}
		}
		mysql_close($Link);
	} else { return 0; }
	return 1;
}

// Data-saving functions
function nSaveData($nData,$nDBQuery){
	global $nDBHost,$nDBName,$nDBUser,$nDBPass,$nDEBUG;
	if(!$nDBQuery || !$nData){ return 0; }
	if($Link = mysql_connect($nDBHost,$nDBUser,$nDBPass)){
		if($nDEBUG){ print "Database link through '$nDBHost' with user '$nDBUser' established: '$Link'.<BR>"; }
		$nDBQuery = str_replace("[#Data#]",$nData,$nDBQuery);
		mysql_select_db($nDBName);
		mysql_query($nDBQuery,$Link);
		mysql_close($Link);
		if($nDEBUG){ print "Database '$nDBName' successfully written to: $nDBQuery<BR>"; }
	} else { return 0; }
	return 1;
}

function rewriteDBConn($nFilePath){
	global $nDBHost,$nDBName,$nDBUser,$nDBPass;
	if(!$nFilePath){ return 0; }
	if(file_exists($nFilePath)){
		// read file
		$nDBConnFile = fopen($nFilePath,"r");
		if($nDBConnFile){
			$nFileCode = fread($nDBConnFile,(filesize($nFilePath)*2)); // filesize may return less on some servers, so multiply x2
			fclose($nDBConnFile);
		} else { return 0; }
		// Replace fields
		$nFileCode = str_replace("[#nDBHost#]",$nDBHost,$nFileCode);
		$nFileCode = str_replace("[#nDBName#]",$nDBName,$nFileCode);
		$nFileCode = str_replace("[#nDBUser#]",$nDBUser,$nFileCode);
		$nFileCode = str_replace("[#nDBPass#]",$nDBPass,$nFileCode);
		// save file
		$nDBConnFile = fopen($nFilePath,"w");
		if($nDBConnFile){
			$numBytes = fwrite($nDBConnFile,$nFileCode);
			fclose($nDBConnFile);
		} else { return 0; }
	} else { return 0; }
	return 1;
}
?>
<?php 
/**
 * Copies file or folder from source to destination, it can also do
 * recursive copy by recursively creating the dest file or directory path if it wasn't exist
 * Use cases:
 * - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination
 * - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it
 * - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest      
 * - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest
 * - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name
 * - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name
 * @todo
 *  - Should have rollback so it can undo the copy when it wasn't completely successful
 *  - It should be possible to turn off auto path creation feature f
 *  - Supporting callback function
 *  - May prevent some issues on shared enviroments : http://us3.php.net/umask
 * @param $source //file or folder
 * @param $dest ///file or folder
 * @param $options //folderPermission,filePermission
 * @return boolean
 */
function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0644)){
	global $nDEBUG;
	$result=false;
	//For Cross Platform Compatibility
	if (!isset($options['noTheFirstRun'])) {
		$source=str_replace('\\','/',$source);
		$dest=str_replace('\\','/',$dest);
		$options['noTheFirstRun']=true;
	}
	$source=str_replace('//','/',$source); $dest=str_replace('//','/',$dest);
	if (is_file($source)) {
		if ($dest[strlen($dest)-1]=='/') {
			if (!file_exists($dest)) {
				makeAll($dest,$options['folderPermission'],true);
			}
			$__dest=$dest."/".basename($source);
		} else {
			$__dest=$dest;
		}
		//if (!file_exists($__dest)) { // allow copying over existing files
			if($nDEBUG){ print "*** Copying file '$source' to '$__dest'<BR>"; }
			$result=copy($source, $__dest);
			chmod($__dest,$options['filePermission']);
		//}
	} elseif(is_dir($source)) {
		if ($dest[strlen($dest)-1]=='/') {
			if ($source[strlen($source)-1]=='/') {
				//Copy only contents
			} else {
				//Change parent itself and its contents
				$dest=$dest.basename($source);
				if(substr_count($dest,'/')<20){ // limit to less than 20 nested folders (prevents against endless loops)
					if($nDEBUG){ print "*** Creating directory(a) '$dest'<BR>"; }
					@mkdir($dest);
					chmod($dest,$options['filePermission']);
				}
			}
		} else {
			if ($source[strlen($source)-1]=='/') {
				//Copy parent directory with new name and all its content
				if(!file_exists($dest) && substr_count($dest,'/')<20){ // limit to less than 20 nested folders (prevents against endless loops)
					if($nDEBUG){ print "*** Creating directory(b) '$dest'<BR>"; }
					@mkdir($dest,$options['folderPermission']);
					//chmod($dest,$options['filePermission']); // commented out, was chmod'ing all new folders to filePermission value (e.g. 0644) making them unwritable
				}
			} else {
				//Copy parent directory with new name and all its content
				if(!file_exists($dest) && substr_count($dest,'/')<20){ // limit to less than 20 nested folders (prevents against endless loops)
					if($nDEBUG){ print "*** Creating directory(c) '$dest'<BR>"; }
					@mkdir($dest,$options['folderPermission']);
					//chmod($dest,$options['filePermission']); // commented out, was chmod'ing all new folders to filePermission value (e.g. 0644) making them unwritable
				}
			}
		}
		$dirHandle=opendir($source);
		while($file=readdir($dirHandle)){
			if($file!="." && $file!=".."){
				$__dest=$dest."/".$file;
				$__source=$source."/".$file;
				$__source=str_replace('//','/',$__source); $__dest=str_replace('//','/',$__dest);
				//echo "$__source ||| $__dest<br />";
				if ($__source!=$dest) {
					//if($nDEBUG){ print "'$__source' does not equal '$dest', let's call smartCopy again!<BR>"; }
					$result=smartCopy($__source, $__dest, $options);
				}
			}
		}
		closedir($dirHandle);
		
	} else {
		$result=false;
	}
	return $result;
}

// ------------ lixlpixel recursive PHP functions -------------
// recursive_remove_directory( directory to delete, empty )
// expects path to directory and optional TRUE / FALSE to empty
// of course PHP has to have the rights to delete the directory
// you specify and all files and folders inside the directory
// ------------------------------------------------------------

// to use this function to totally remove a directory, write:
// recursive_remove_directory('path/to/directory/to/delete');

// to use this function to empty a directory, write:
// recursive_remove_directory('path/to/full_directory',TRUE);

function recursive_remove_directory($directory, $empty=FALSE){
	// if the path has a slash at the end we remove it here
	if(substr($directory,-1) == '/'){ $directory = substr($directory,0,-1); }
	// if the path is not valid or is not a directory ...
	if(!file_exists($directory) || !is_dir($directory)){ return FALSE; }
	if(!is_readable($directory)){ return FALSE; }
	// open the directory and scan it
	$handle = opendir($directory);
	while (FALSE !== ($item = readdir($handle))){
		// if the filepointer is not the current directory
		// or the parent directory
		if($item != '.' && $item != '..'){
			// we build the new path to delete
			$path = $directory.'/'.$item;
			// if the new path is a directory
			if(is_dir($path)){
				// we call this function with the new path
				recursive_remove_directory($path);
			// if the new path is a file
			} else { unlink($path); }
		}
	}
	// close the directory
	closedir($handle);
	// if the option to empty is not set to true
	if($empty == FALSE){
		// try to delete the now empty directory
		if(!rmdir($directory)){ return FALSE; }
	}
	return TRUE;
}

// Utility functions
function nGetAutoGenPass($length = 8){
	$password = "";
	// define possible characters
	$possible = "23456789abcdfghjkmnpqrstvwxyz23456789ABCDEFGHJKMNPQRSTUVWXYZ23456789"; 
	$i = 0; 
	while ($i < $length) { 
	  $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
	  if (!strstr($password, $char)) { 
	    $password .= $char;
	    $i++;
	  }
	}
	return $password;
}
/**
Validate an email address.
Provide email address (raw input)
Returns true if the email address has the email 
address format and the domain exists.
*/
function validate_email($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex){
      $isValid = false;
   } else {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if($localLen < 1 || $localLen > 64){
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255){
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.'){
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local)){
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)){
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain)){
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))){
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      //if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))){
      //   // domain not found in DNS
      //   $isValid = false;
      //}
   }
   return $isValid;
}
function nImportNewComps(){
	global $nDBHost,$nDBName,$nDBUser,$nDBPass,$nDEBUG;
	global $nCompPath,$nDefaultLang;
	
	// Connect to db
	if($Link = mysql_connect($nDBHost,$nDBUser,$nDBPass)){
		$nTable = "";
		// Get all files in Components directory
		$dir_handle = @opendir($nCompPath) or die("Unable to open Component path:"." $nCompPath");
		while ($file = readdir($dir_handle)) {
			if($file == "." || $file == ".." || $file == "index.php" )
				continue;
			if(!is_dir("$nCompPath$file")){
				// reset imported vars
				$nName = ""; $nDescription = ""; $nPageTypeLimit = ""; $nTemplateFile = "";
				$nFileName="$file";
				$nFilePath="$nCompPath$file";
				if(file_exists("$nFilePath")){
					// Pull in component settings file
					// include($nFilePath);
					$nConnFile = fopen($nFilePath,"r");
					if($nConnFile){
						$nFileCode = fread($nConnFile,filesize($nFilePath));
						fclose($nConnFile);
					} else { return 0; }
					$nFileCode = str_replace("\r\n","\n",$nFileCode);
					$nFileCodeARRAY = explode("\n",$nFileCode);
					if(isset($nFileCodeARRAY[2]) && strpos($nFileCodeARRAY[2],"nName")){ eval($nFileCodeARRAY[2]); }
					if(isset($nFileCodeARRAY[3]) && strpos($nFileCodeARRAY[3],"nDescription")){ eval($nFileCodeARRAY[3]); }
					if(isset($nFileCodeARRAY[4]) && strpos($nFileCodeARRAY[4],"nPageTypeLimit")){ eval($nFileCodeARRAY[4]); }
					if(isset($nFileCodeARRAY[5]) && strpos($nFileCodeARRAY[5],"nTemplateFile")){ eval($nFileCodeARRAY[5]); }
					if($nName){
						$nCompID = nGetCompIDFromTemplateFile($nFileName);
						//print "id exists for $nName: $nCompID<BR>";
						if($nTemplateFile && !$nCompID){ // if comp doesn't already exist in DB (no ID exists), add it
							$nName = nTruncateString(trim($nName),50);
							$nDescription = addslashes(nTruncateString(trim($nDescription),255));
							$nPageTypeLimit = addslashes(nTruncateString(trim($nPageTypeLimit),50));
							$nTemplateFile = nTruncateString(trim($nTemplateFile),255);
							$nTemplateFilePath="$nCompPath$nTemplateFile";
							$nLangPath = "$nDefaultLang/";
							$nTemplateOverridePath = "$nCompPath$nLangPath$nTemplateFile";
							//print "template file ($nTemplateFilePath) exists? ".file_exists("$nTemplateFilePath")."<BR>";
							//print "template override file ($nTemplateOverridePath) exists? ".file_exists("$nTemplateOverridePath")."<BR>";
							// Add plugin to database un-activated if all tests passed
							$nNewCompID = 0; // let MySQL choose the new comp ID
							switch($nFileName){ // just during install, choose specific IDs for certain new default comps (to connect default data)
								case "basicnavbox.php": $nNewCompID = 1; break;
								case "contactform.php": $nNewCompID = 2; break;
								case "disqus_commentbox.php": $nNewCompID = 3; break;
								case "featuretext.php": $nNewCompID = 4; break;
								case "fullcalendar.php": $nNewCompID = 5; break;
								case "headerimage.php": $nNewCompID = 6; break;
								case "loginform.php": $nNewCompID = 7; break;
								case "minicalendar.php": $nNewCompID = 8; break;
								case "pdfnavbox.php": $nNewCompID = 9; break;
								case "search_results.php": $nNewCompID = 10; break;
								case "simpleimage.php": $nNewCompID = 11; break;
								case "simpletext.php": $nNewCompID = 12; break;
								case "textimage.php": $nNewCompID = 13; break;
								case "title.php": $nNewCompID = 14; break;
							}
							if($nName && (file_exists("$nTemplateFilePath") || file_exists("$nTemplateOverridePath"))){
								//print "saving to db<BR>";
								$Query = "INSERT INTO nComponent VALUES ('$nNewCompID','$nName','$nDescription','1','$nPageTypeLimit','$nFileName')";
								mysql_select_db($nDBName);
								mysql_query($Query, $Link);
							}
						} else {
							// If component already exists, just update the description and name (just in case default language is different or component had a recent update)
							$nName = addslashes(stripslashes($nName));
							$nDescription = addslashes(stripslashes($nDescription));
							$Query = "UPDATE nComponent SET nName='$nName', nDesc='$nDescription' WHERE nID='$nCompID'";
							mysql_select_db($nDBName);
							mysql_query($Query, $Link);
						}
					}
				}
			}
		}
	}
	closedir($dir_handle);
	return $nTable;
}
function nGetCompIDFromTemplateFile($nCompTmplFile){
	global $nDBHost,$nDBName,$nDBUser,$nDBPass,$nDEBUG;
	if(!$nCompTmplFile){ return; }
	$nID = "";
	// Connect to db
	if($Link = mysql_connect($nDBHost,$nDBUser,$nDBPass)){
		$Query = "SELECT nID FROM nComponent WHERE nCompFile='$nCompTmplFile'";
		mysql_select_db($nDBName); $Result = mysql_query($Query,$Link);
		while ($Row = mysql_fetch_array($Result)) {
			$nID = $Row["nID"];
		}
	}
	return $nID;
}
function nTruncateString($nStr,$nMax){
  if(strlen($nStr)>$nMax) {
    $leave = $max - strlen($rep);
    return substr($nStr,0,$nMax);
  }
  return $nStr;
}
?>
