<?php

/***************************************************************************

 install.php
 ------------
 copyright : (C) 2002-2003 The ezContents Development Team

 ***************************************************************************/

/***************************************************************************
 The ezContents Development Team offers no warranties on this script.
 The owner/licensee of the script is solely responsible for any problems
 caused by installation of the script or use of the script.

 All copyright notices regarding ezContents must remain intact on the
 scripts and in the HTML for the scripts.

 For more info on ezContents,
 visit http://www.ezcontents.org/

/***************************************************************************

/***************************************************************************
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the License which can be found within the
 *	zipped package.
 *
 ***************************************************************************/


$requesturi = $HTTP_SERVER_VARS["REQUEST_URI"];
$uri = explode('?',$requesturi);
$uri = explode('/',$uri[0]);
$urilen = count($uri) - 1;
$uri = $uri[$urilen];
if ($uri == 'install.php.complete') {
	Header("Location: index.php");
}

error_reporting( E_ERROR | E_PARSE );	//	Disable error reporting for anything but critical errors
set_time_limit(300);					//	Allow up to five minutes for the time-consuming upgrade to run....
										//		this should be more than enough for almost any site.

$GLOBALS["DebugMode"] = False;

if (strpos(php_uname(), 'Win') !== FALSE) { $GLOBALS["OS"] = "Windows"; }

$GLOBALS["rootdp"] = './';		//	Database access routines
include ('./include/debuglib.php');
include ('./include/db.php');



//	Define the page headings
$GLOBALS["Titles"]["Main"]			= 'ezContents CMS Version 2.0.3';
$GLOBALS["Titles"]["Installation"]	= 'ezContents Version 2.0.3 Installation';
$GLOBALS["Titles"]["License"]		= 'ezContents Version 2.0.3 Licence Agreement';
$GLOBALS["Titles"]["Modules"]		= 'ezContents CMS Version 2.0.3 Modules';
$GLOBALS["Titles"]["Languages"]		= 'ezContents CMS Version 2.0.3 Languages';
$GLOBALS["Titles"]["Database"]		= 'ezContents CMS Version 2.0.3 Database Configuration';
$GLOBALS["Titles"]["Upgrade"]		= 'ezContents CMS Version 2.0.3 Upgrade';
$GLOBALS["Titles"]["NewInstall"]	= 'ezContents CMS Version 2.0.3 New Installation';
$GLOBALS["Titles"]["InstallLog"]	= 'ezContents Version 2.0.3 Installation Log';

//	Help Texts
$GLOBALS["Help"]["Test"]			= 'This form displays the basic system requirements that ezContents needs to run, and determines if your system meets those minimum requirements.';
$GLOBALS["Help"]["PHPVersion"]		= 'The minimum version of PHP that is required for this version of ezContents.';
$GLOBALS["Help"]["RegisterGlobals"]	= 'If PHP is configured with \'Register Globals\' set to \'On\' this is a serious security flaw on your server.'.chr(10).chr(10).'ezContents will still work with this setting either \'On\' or \'Off\'; but we strongly advise you to reconfigure your PHP installation.';
$GLOBALS["Help"]["GDGraphics"]		= 'If PHP has been built with the GD Graphics module, then ezContents will use this, otherwise certain graphic features can only be simulated.'.chr(10).chr(10).'GD is not a prerequisite for ezContents, nor is .GIF support within GD; but it is useful.';
$GLOBALS["Help"]["mbstring"]		= 'If you plan to use the multi-lingual features of ezContents for languages that use different character sets, then the PHP Multi-byte (mbstring) extension should be available.'.chr(10).chr(10).'The mbstring extension is not a prerequisite for ezContents, unless you plan to provide translations in several languages that use different character sets.';
$GLOBALS["Help"]["SafeMode"]		= 'For security reasons, some ISPs run PHP in \'Safe Mode\' and this can restrict the functionality available in ezContents.'.chr(10).chr(10).'It does not mean that ezContents cannot run, although this depends exactly how \'Safe Mode\' has been configured.';
$GLOBALS["Help"]["OpenBasedir"]		= 'For security reasons, some ISPs restrict filesystem access within PHP using an \'Open_Basedir\' setting, and this can restrict the functionality available in ezContents if it is mis-set.'.chr(10).chr(10).'It does not mean that ezContents cannot run - a properly set \'open_basedir\' will not restrict functionality; but it is frequently set incorrectly by ISPs.';
$GLOBALS["Help"]["FileUploads"]		= 'For security reasons, some ISPs prevent http from uploading files to the server.'.chr(10).chr(10).'If this restriction is enforced, then you will not be able to upload files using ezContents, but will need to do so using ftp.';
$GLOBALS["Help"]["MySQLVersion"]	= 'The minimum version of the MySQL database that is required for this version of ezContents.';
$GLOBALS["Help"]["Apache"]			= 'Although ezContents will run on most web servers, but we would recommend using Apache version 1.3.26 or above.';
$GLOBALS["Help"]["WriteableFiles"]	= 'A number of directories need to have read/write privilege to use all the facilities of ezContents. Additionally, the ezContents configuration file must be writeable while this install script is running.'.chr(10).chr(10).'These include the /contentimage, /downloads and /scripts directories used for uploads, the /backup directory used for database backups, admin/styles/icache used for dynamic image cacheing, and the /sites and /themes directories used for the multi-site and multi-theme options.';

$GLOBALS["Help"]["Modules"]			= 'Use this form to select which modules you wish to install.'.chr(10).chr(10).'If you decide not to install any modules now, you can always install them later through the admin functions.';
$GLOBALS["Help"]["calendar"]		= 'This is a simple calendar display, showing the current month and allowing viewers to page backward and forward from month to month and year to year.';
$GLOBALS["Help"]["diary"]			= 'The \'diary\' module is a version of calendar that allows you to record events. It is available either as a calendar display, listing events against dates, or as a simple list of events. The event list is also available as an \'inline\' version that can be included within the content of a page.'.chr(10).chr(10).'Optionally, users can also be allowed to submit events to the diary.';
$GLOBALS["Help"]["gallery"]			= 'This module provides a basic image gallery, displaying thumbnails of selected images and allowing viewers to click on any image to display it full size.'.chr(10).chr(10).'It does not yet allow viewers to submit images to the gallery.';
$GLOBALS["Help"]["guestbook"]		= 'The guestbook module allows visitors to enter comments about your site, or even just general comments.';
$GLOBALS["Help"]["links"]			= 'The \'links\' module provides a list of links to other sites that you can maintain.'.chr(10).chr(10).'Optionally, users can also be allowed to submit their own links to the list.';
$GLOBALS["Help"]["news"]			= 'Use this module for maintaining news items on your site.'.chr(10).'News is available as a module, or as an \'inline\' version that can be included within the content of a page.'.chr(10).chr(10).'Optionally, users can also be allowed to submit their own news items.';
$GLOBALS["Help"]["poll"]			= 'Set multiple-choice questions for your visitors to answer either as a module or an inline version.'.chr(10).'The style of poll is determines by one of two modes: a single answer from a series, or multiple answers (check all that apply).'.chr(10).chr(10).'User submission of polls is not supported at this point, and only registered members of the site can vote.';
$GLOBALS["Help"]["reviews"]			= 'The \'review\' module allows you to have a list of reviews for films, books, games, etc. and to give these a \'star rating\'.'.chr(10).chr(10).'Optionally, users can also be allowed to submit their own reviews.';
$GLOBALS["Help"]["search"]			= 'The \'search\' module allows users to search for specific content articles on your site.';
$GLOBALS["Help"]["sitemap"]			= 'Displays a hierarchical \'map\' of the menus on your site.';
$GLOBALS["Help"]["sitestats"]		= 'This module hasn\'t yet been written, but if you have site visitor statistics enabled it will allow users to view those statistics.'.chr(10).'Basically it will eventually be a \'front-end\' version of the admin \'View Statistics\' function';
$GLOBALS["Help"]["toprated"]		= 'Can be used to display a list of the \'top ten\' rated articles.';
$GLOBALS["Help"]["whatsnew"]		= 'Allows the viewers to see what content on your site has been added, updated (or even expired) since their last visit.';
$GLOBALS["Help"]["ModuleSelectAll"]		= 'Select all modules';
$GLOBALS["Help"]["ModuleSelectNone"]	= 'Select none of the modules';

$GLOBALS["Help"]["Languages"]	= 'Use this form to select which languages you wish to install, and select your default language.'.chr(10).'You must install at least one language.'.chr(10).chr(10).'If you decide not to install any additional languages now, you can always install them later through the admin functions.';
$GLOBALS["Help"]["da"]			= 'Danish'.chr(10).chr(10).'Partial fileset.';
$GLOBALS["Help"]["de"]			= 'German.';
$GLOBALS["Help"]["en"]			= 'English.';
$GLOBALS["Help"]["es"]			= 'Spanish.'.chr(10).chr(10).'Not yet available: only included in this list for testing the installation procedure.';
$GLOBALS["Help"]["fr"]			= 'French.';
$GLOBALS["Help"]["hu"]			= 'Hungarian.'.chr(10).chr(10).'Not yet available: only included in this list for testing the installation procedure.';
$GLOBALS["Help"]["it"]			= 'Italian.'.chr(10).chr(10).'Not yet available: only included in this list for testing the installation procedure.';
$GLOBALS["Help"]["nl"]			= 'Dutch.';
$GLOBALS["Help"]["pl"]			= 'Polish.';
$GLOBALS["Help"]["pt"]			= 'Portuguese.'.chr(10).chr(10).'Not yet available: only included in this list for testing the installation procedure.';
$GLOBALS["Help"]["ru"]			= 'Russian.';
$GLOBALS["Help"]["zh"]			= 'Chinese (Big5).';
$GLOBALS["Help"]["LanguageSelectAll"]	= 'Select all languages';
$GLOBALS["Help"]["LanguageSelectNone"]	= 'Deselect all languages';

$GLOBALS["Available"]["da"]		= 'Yes';
$GLOBALS["Available"]["de"]		= 'Yes';
$GLOBALS["Available"]["en"]		= 'Yes';
$GLOBALS["Available"]["es"]		= 'No';
$GLOBALS["Available"]["fr"]		= 'Yes';
$GLOBALS["Available"]["hu"]		= 'No';
$GLOBALS["Available"]["it"]		= 'No';
$GLOBALS["Available"]["nl"]		= 'Yes';
$GLOBALS["Available"]["pl"]		= 'Yes';
$GLOBALS["Available"]["pt"]		= 'No';
$GLOBALS["Available"]["ru"]		= 'Yes';
$GLOBALS["Available"]["zh"]		= 'Yes';

$GLOBALS["Help"]["Database"]		= 'To install ezContents, the installation procedure needs some information about your database. This form is for you to provide the script with that information.'.chr(10).chr(10).'Once you have entered all the necessary information, click on the \'Submit Database Details\' button to start the installation or upgrade.';
$GLOBALS["Help"]["InstallType"]		= 'First, you need to select whether this is a new installation, or whether you are upgrading from version 1.4x of ezContents.';
$GLOBALS["Help"]["InstallNew"]		= 'Select this option for a new installation.';
$GLOBALS["Help"]["InstallUpgrade"]	= 'Select this option to upgrade an existing ezContents 1.4x database to version 2.0.3.';
$GLOBALS["Help"]["CreateDatabase"]	= 'This is only appropriate for a new installation, not for an upgrade.'.chr(10).'Should the installation script create a new database for you, or use an existing database that you have created manually?'.chr(10).chr(10).'IMPORTANT NOTE - If the installation process \'hangs\' after you click on \'Submit Database Details\', you may need to manually create an empty database, then rerun this script to build and populate the data tables.';
$GLOBALS["Help"]["NewDatabase"]		= 'The ezContents installer should create the database as part of the installation process.';
$GLOBALS["Help"]["OldDatabase"]		= 'The database has been created manually.';
$GLOBALS["Help"]["DBDriver"]		= 'Select the appropriate database driver for MySQL.'.chr(10).chr(10).'If you don\'t know, then simply use \'MySQL\' rather than \'MySQL Transactional\'.';
$GLOBALS["Help"]["DBAddress"]		= 'You need to point ezContents to the address of the database server box.'.chr(10).'The database may be on the same box as your webserver, in which case use the default value of \'localhost\; otherwise enter the appropriate IP address.';
$GLOBALS["Help"]["DBName"]			= 'If you are upgrading from a previous installation of ezContents 1.4x, enter the name of your database here.'.chr(10).chr(10).'If this is a new installation, you will need to enter a name for your database. This should be kept reasonably short (for simplicity) and should not contain any unusual characters such as spaces or punctuation marks.';
$GLOBALS["Help"]["DBLogin"]			= 'ezContents needs to know the login name for MySQL. Enter that information here.';
$GLOBALS["Help"]["DBPassword"]		= 'ezContents needs to know the password for connecting to MySQL. Enter that information here.';
$GLOBALS["Help"]["DBPrefix"]		= 'You can prefix the ezContents table names to ensure that they are unique if you are likely to be sharing a database with other users or systems.'.chr(10).'If you wish to use a prefix, enter it here. This prefix should be kept reasonably short (for simplicity) and should not contain any unusual characters such as spaces or punctuation marks (although underscores are permitted).';
$GLOBALS["Help"]["DBPersistent"]	= 'Persistent connections can improve the performance of ezContents; but your database needs to be configured to use them, and they limit the number of concurrent users that can connect to the database.'.chr(10).chr(10).'If in doubt, do NOT use Persistent Connections.';
$GLOBALS["Help"]["InstallLog"]		= 'You can log all database commands executed during the install or upgrade. If the script fails, this log can help identify the cause of the problem'.chr(10).'This log will be displayed in the pop-up debug window.';
$GLOBALS["Help"]["LogNo"]			= 'Don\'t enable logging.';
$GLOBALS["Help"]["LogYes"]			= 'Enable logging.';

$GLOBALS["Help"]["NewInstall"]			= 'Installation is now complete, and you can log in to ezContents with a username of \'admin\' and a password of \'ezcontents\'. Note that usernames and passwords are case sensitive.';
$GLOBALS["Help"]["UpgradeInstall"]		= 'The upgrade is now complete, and you can log in to ezContents with your normal username and password. Remember that usernames and passwords are case sensitive.';
$GLOBALS["Help"]["SecurityComments"]	= chr(10).chr(10).'For security reasons, we would now recommend that you delete install.php and the /sql subdirectory, together with the install.sql files in the language and modules subdirectories.'.chr(10).'Check that the /include/config.php file that has been updated by this script is set to read only.';


//	Define the traffic light icons
$GLOBALS["Checks"]["green"]		= '<img src="./images/green_dot.gif">&nbsp;';
$GLOBALS["Checks"]["orange"]	= '<img src="./images/orange_dot.gif">&nbsp;';
$GLOBALS["Checks"]["red"]		= '<img src="./images/red_dot.gif">&nbsp;';


$GLOBALS["MaxFileSize"] = 262144;	//	256k


//	Execute the appropriate page script
if ($HTTP_POST_VARS["mode"] <> "") { $HTTP_GET_VARS["mode"] = $HTTP_POST_VARS["mode"]; }

if ($HTTP_GET_VARS["mode"] == 'modules') {
	$languagecount = test_languages_1();
	if ($languagecount == 0) {
		$languageerror = 'You must install at least one language';
		$HTTP_GET_VARS["mode"] = 'languages';
	} else {
		$languagecount = test_languages_2($HTTP_POST_VARS["defaultlanguage"]);
		if ($languagecount == 0) {
			$languageerror = 'The default language must be one of those you have selected for installation';
			$HTTP_GET_VARS["mode"] = 'languages';
		}
	}
}

switch ($HTTP_GET_VARS["mode"]) {
	case 'install'	 : install_header("Installation",360,120);
					   install_ezContents();
					   if ($HTTP_POST_VARS["InstallType"] == 'newinstall') { help_screen(360,72,$GLOBALS["Help"]["NewInstall"].$GLOBALS["Help"]["SecurityComments"]);
					   } else { help_screen(360,72,$GLOBALS["Help"]["UpgradeInstall"].$GLOBALS["Help"]["SecurityComments"]); }
					   break;
	case 'database'	 : install_header("Installation",460,370);
					   database_screen();
					   help_screen(360,72,$GLOBALS["Help"]["Database"]);
					   break;
	case 'modules'	 : install_header("Installation",420,120);
					   module_screen();
					   help_screen(400,62,$GLOBALS["Help"]["Modules"]);
					   break;
	case 'languages' : install_header("Installation",420,120);
					   if ($languageerror != '') {
							blocktext($languageerror,'red');
							echo '</td></tr>';
							echo '<tr><td align="center" valign="top">';
					   }
					   language_screen();
					   help_screen(400,62,$GLOBALS["Help"]["Languages"]);
					   break;
	case 'test'		 : install_header("Installation",780,500);
					   test_screen();
					   help_screen(780,92,$GLOBALS["Help"]["Test"]);
					   break;
	case 'agreement' : install_header("License",600,330);
					   agreement_screen();
					   break;
	default			 : install_header("Installation",420,200);
					   opening_screen();
}
install_footer($title);




function opening_screen()
{
	?>
	<table border="0" height="100%" width="100%" cellpadding="4" cellspacing="2">
		<tr><td colspan="2" align="center" valign="middle">
				<?php blocktitle("Main"); ?>
			</td>
		</tr>
		<tr><td align="center" valign="bottom">
				<img src="./images/vs_logo.jpg">
			</td>
			<td valign="top">
				<?php blocktext('Thank you for choosing to install the ezContents Content Management System.'); ?>
				<?php blocktext('This script will only take a few moment to run, and will configure a new installation, or upgrade an existing 1.4.x site to the new version.'); ?>
			</td>
		</tr>
		<tr><td align="center" valign="top">
				<img src="./images/logo_small.gif">
			</td>
			<td align="center" valign="middle">
				<input type="button" class="ip_text" value="Install ezContents" onClick="location.href='install.php?mode=agreement'">
			</td>
		</tr>
	</table>
	<?php
} // function opening_screen()


function agreement_screen()
{
	?>
	<table border="0" height="100%" width="100%" cellpadding="4" cellspacing="2">
		<tr><td align="center" valign="middle">
				<?php blocktitle("License"); ?>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php blocktext('Please read the agreement below, and if you agree to it select the button at the very bottom.<br />By selecting the button, you agree to the terms below.'); ?>
				<p>
				<textarea cols="70" rows="15" name="agreement" wrap='soft' style="font-family: Courier; font-size: 10pt" readonly>
<?php include("./ezContents_License_1-0.txt"); ?>
				</textarea>
				</p>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<input type="button" class="ip_text" value="I Agree To These Terms" onClick="location.href='install.php?mode=test'">
			</td>
		</tr>
	</table>
	<?php
} // function agreement_screen()


function readPerms($in_Perms)
{
	$sP;

	if ($in_Perms & 0x1000) { $sP = 'p'; }	// FIFO pipe
	elseif ($in_Perms & 0x2000) { $sP = 'c'; }	// Character special
	elseif ($in_Perms & 0x4000) { $sP = 'd'; }	// Directory
	elseif ($in_Perms & 0x6000) { $sP = 'b'; }	// Block special
	elseif ($in_Perms & 0x8000) { $sP = '-'; }	// Regular
	elseif ($in_Perms & 0xA000) { $sP = 'l'; }	// Symbolic Link
	elseif ($in_Perms & 0xC000) { $sP = 's'; }	// Socket
	else { $sP = 'u'; }				// UNKNOWN

	// owner
	$sP .= (($in_Perms & 0x0100) ? 'r' : '-').(($in_Perms & 0x0080) ? 'w' : '-').(($in_Perms & 0x0040) ? (($in_Perms & 0x0800) ? 's' : 'x' ) : (($in_Perms & 0x0800) ? 'S' : '-'));
	// group
	$sP .= (($in_Perms & 0x0020) ? 'r' : '-').(($in_Perms & 0x0010) ? 'w' : '-').(($in_Perms & 0x0008) ? (($in_Perms & 0x0400) ? 's' : 'x' ) : (($in_Perms & 0x0400) ? 'S' : '-'));
	// world
	$sP .= (($in_Perms & 0x0004) ? 'r' : '-').(($in_Perms & 0x0002) ? 'w' : '-').(($in_Perms & 0x0001) ? (($in_Perms & 0x0200) ? 't' : 'x' ) : (($in_Perms & 0x0200) ? 'T' : '-'));
	return $sP;
} // function readPerms()


function fileReadWrite($myuserid,$mygroupid,$fileref)
{
	$rval = false;

	$userid = fileowner($fileref);
	$groupid = filegroup($fileref);
	$perms = readPerms(fileperms($fileref));

	if ($GLOBALS["DebugMode"]) {
		debug_msg('<font color="LIGHTGREEN" SIZE="-1">File Name = ['.$fileref.']<br />',$GLOBALS["Titles"]["InstallLog"]);
		debug_msg('File Owner ID = ['.$userid.'] ',$GLOBALS["Titles"]["InstallLog"]);
		debug_msg('File Group ID = ['.$groupid.']<br />',$GLOBALS["Titles"]["InstallLog"]);
		debug_msg('File Permissions = ['.$perms.']<br />',$GLOBALS["Titles"]["InstallLog"]);
	}

	if ($myuserid == $userid) {
		if (substr($perms,2,1) == 'w') {
			$rval = true;
			if ($GLOBALS["DebugMode"]) { debug_msg('*** Owner match ***<br />',$GLOBALS["Titles"]["InstallLog"]); }
		}
		elseif ($mygroupid == $groupid) {
			if (substr($perms,5,1) == 'w') {
				$rval = true;
				if ($GLOBALS["DebugMode"]) { debug_msg('*** Group match ***<br />',$GLOBALS["Titles"]["InstallLog"]); }
			} elseif (substr($perms,8,1) == 'w') {
				$rval = true;
				if ($GLOBALS["DebugMode"]) { debug_msg('*** World match ***<br />',$GLOBALS["Titles"]["InstallLog"]); }
			}
		}
	} elseif ($mygroupid == $groupid) {
		if (substr($perms,5,1) == 'w') {
			$rval = true;
			if ($GLOBALS["DebugMode"]) { debug_msg('*** Group match ***<br />',$GLOBALS["Titles"]["InstallLog"]); }
		}
	} elseif (substr($perms,8,1) == 'w') {
		$rval = true;
		if ($GLOBALS["DebugMode"]) { debug_msg('*** World match ***<br />',$GLOBALS["Titles"]["InstallLog"]); }
	}

	if ($GLOBALS["DebugMode"]) { 
		if (!($rval)) {
			debug_msg('*** NO MATCH ***<br />',$GLOBALS["Titles"]["InstallLog"]);
		}
		debug_msg('<br /></font>',$GLOBALS["Titles"]["InstallLog"]);
	}

	return $rval;
} // function fileReadWrite()


function test_screen()
{
	global $HTTP_SERVER_VARS;

	$safe_mode = (bool) ini_get("safe_mode");
	$open_basedir = ini_get("open_basedir");
	$file_uploads = (bool) ini_get("file_uploads");
	$register_globals = (bool) ini_get("register_globals");

	$Status = True;
	?>
	<table border="0" height="100%" width="100%" cellpadding="1" cellspacing="1">
		<tr><td align="center" valign="middle">
				<?php blocktitle("Main"); ?>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php blocktext('This screen tests your configuration against the requirements to run ezContents.'); ?>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<table border="1" height="100%" width="95%" cellpadding="1" cellspacing="1">
					<tr><td align="center" valign="middle">
							<table border="0" height="100%" width="100%" cellpadding="1" cellspacing="2">
								<tr><td align="right" width="45%" valign="top">
										<?php basetext(mouseover('PHP Version 4.0.4 or greater :','PHPVersion','Test')); ?>
									</td>
									<td valign="top" width="55%">
										<?php
										if (phpversion() >= '4.0.4') { $text = $GLOBALS["Checks"]["green"];
										} else {
											$text = $GLOBALS["Checks"]["red"];
											$Status = False;
										}
										$text .= 'You are running version '.phpversion(). ' of PHP';
										basetext($text);
										if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
										?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Register Globals :<br />(strongly advised \'Off\')','RegisterGlobals','Test')); ?>
									</td>
									<td valign="top">
										<?php
										if (!$safe_mode) { $text = $GLOBALS["Checks"]["green"].'Register Globals is \'Off\'';
										} else {
											$text = $GLOBALS["Checks"]["red"].'Register Globals is \'On\'<br />This is a serious security flaw in your PHP configuration';
										}
										basetext($text);
										if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
										?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('GD graphics extension for PHP :<br />(recommended)','GDGraphics','Test')); ?>
									</td>
									<td valign="top">
										<?php
										if (extension_loaded('gd')) {
											if (ImageTypes() & IMG_GIF) { $text = $GLOBALS["Checks"]["green"].'GD is available';
											} else { $text = $GLOBALS["Checks"]["green"].'GD is available<br />but does not support .gif images'; }
										} else { $text = $GLOBALS["Checks"]["orange"].'GD is NOT available'; }
										basetext($text);
										if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
										?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Multi-byte (mbstring) extension for PHP :','mbstring','Test')); ?>
									</td>
									<td valign="top">
										<?php
										if (extension_loaded('mbstring')) {
											if (substr(phpversion(),0,5) >= '4.2.3') { $text = $GLOBALS["Checks"]["orange"].'mbstring is available, but there may be problems with using multi-byte strings under version 4.2.3 of PHP.<br />We don\'t recommend that you use the multi-language features of ezContents with languages using different charsets.';
											} else { $text = $GLOBALS["Checks"]["green"].'mbstring is available'; }
										}
										else { $text = $GLOBALS["Checks"]["orange"].'mbstring is NOT available.<br />We don\'t recommend that you use the multi-language features of ezContents with languages using different charsets.'; }
										basetext($text);
										if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
										?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Safe Mode should be \'Off\' :','SafeMode','Test')); ?>
									</td>
									<td valign="top">
										<?php
										if (!$safe_mode) { $text = $GLOBALS["Checks"]["green"].'Safe mode is \'Off\'';
										} else {
											$text = $GLOBALS["Checks"]["orange"].'Safe mode is \'On\'<br />This can restrict much of the functionality of ezContents';
										}
										basetext($text);
										if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
										?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Open Basedir should allow access to the ezContents home directory :','OpenBasedir','Test')); ?>
									</td>
									<td valign="top">
										<?php
										if ($open_basedir <> '') { $text = $GLOBALS["Checks"]["orange"].'Open Basedir restriction is in effect';
										} else { $text = $GLOBALS["Checks"]["green"].'Open Basedir restriction is not set'; }
										basetext($text);
										if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
										?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('File Uploads should be permitted :','FileUploads','Test')); ?>
									</td>
									<td valign="top">
										<?php
										if ($file_uploads) { $text = $GLOBALS["Checks"]["green"].'File uploads are permitted';
										} else { $text = $GLOBALS["Checks"]["orange"].'File uploads are NOT permitted. You will need to use ftp for all your image, scripts and downloads maintenance.'; }
										basetext($text);
										if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
										?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('MySQL version 3.23 or above :<br />(recommended)','MySQLVersion','Test')); ?>
									</td>
									<td valign="top">
										<?php
										if (mysql_get_client_info() >= '3.23') { $text = $GLOBALS["Checks"]["green"];
										} else {
											if (mysql_get_client_info() >= '3.20.32') { $text = $GLOBALS["Checks"]["orange"];
											} else {
												$text = $GLOBALS["Checks"]["red"];
												$Status = False;
											}
										}
										$text .= 'You are running the MySQL client version '.mysql_get_client_info();
										basetext($text);
										if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
										?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Apache webserver :','Apache','Test')); ?>
									</td>
									<td valign="top">
										<?php
										if (strpos($HTTP_SERVER_VARS["SERVER_SOFTWARE"], 'Apache') !== FALSE) { $text = $GLOBALS["Checks"]["green"];
										} else { $text = $GLOBALS["Checks"]["orange"]; }
										$text .= 'You are running '.$HTTP_SERVER_VARS["SERVER_SOFTWARE"];
										basetext($text);
										if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
										?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Read/Write privileges :','WriteableFiles','Test')); ?>
									</td>
									<td valign="top">
										<?php
										$myuserid = getmyuid();
										if (phpversion() >= '4.1.0') { $mygroupid = getmygid(); } else { $mygroupid = getmyuid(); }

										if (function_exists('posix_getuid')) {
											$posixmyuserid = posix_getuid();
											$posixuserinfo = posix_getpwuid ($posixmyuserid);
											$posixname = $posixuserinfo["name"];
											$posixmygroupid = $posixuserinfo["gid"];
											$posixgroupinfo = posix_getgrgid ($posixmygroupid);
											$posixgroup = $posixgroupinfo["name"];

											if ($myuserid != $posixmyuserid) {
												$text = $GLOBALS["Checks"]["orange"]."Script running as user '".$posixname."', but PHP reports it as user ".$myuserid.".<br />You may not have the necessary level of file access to run ezContents without problems if you use both ftp and the ezContents maintenance functions to manage files.<br />";
												basetext($text);
												if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
											}
										} else {
											$posixmyuserid = $myuserid;
											$posixname = get_current_user();
											$posixmygroupid = $mygroupid;
											$posixgroup = '';
										}

										if ($GLOBALS["DebugMode"]) {
											debug_msg('<font color="LIGHTGREEN" SIZE="-1">',$GLOBALS["Titles"]["InstallLog"]);
											debug_msg('Script User ID = ['.$myuserid.'] ('.get_current_user().') ',$GLOBALS["Titles"]["InstallLog"]);
											debug_msg('Script Group ID = ['.$mygroupid.']<br />',$GLOBALS["Titles"]["InstallLog"]);
											debug_msg('Posix Script User ID = ['.$posixmyuserid.'] ('.$posixname.')<br />',$GLOBALS["Titles"]["InstallLog"]);
											debug_msg('Posix Script Group ID = ['.$posixmygroupid.'] ('.$posixgroup.')<br /><br /></font>',$GLOBALS["Titles"]["InstallLog"]);
										}

										if ($myuserid != $posixmyuserid) { $myuserid = $posixmyuserid; }
										if ($mygroupid != $posixmygroupid) { $mygroupid = $posixmygroupid; }

										$text  = '';
										$ftext = '';
										if (!(fileReadWrite($myuserid,$mygroupid,'./include/config.php'))) { $text = $GLOBALS["Checks"]["orange"].'Configuration file is read only'; }
										if (!(fileReadWrite($myuserid,$mygroupid,'./'))) { $ftext = '<br />'.$GLOBALS["Checks"]["orange"].'ezContents root directory file is read only'; }
										if (!(fileReadWrite($myuserid,$mygroupid,'./contentimage'))) { $ftext .= '<br />'.$GLOBALS["Checks"]["orange"].'/contentimage directory is read only'; }
										if (!(fileReadWrite($myuserid,$mygroupid,'./downloads'))) { $ftext .= '<br />'.$GLOBALS["Checks"]["orange"].'/downloads directory is read only'; }
										if (!(fileReadWrite($myuserid,$mygroupid,'./scripts'))) { $ftext .= '<br />'.$GLOBALS["Checks"]["orange"].'/scripts directory is read only'; }
										if (!(fileReadWrite($myuserid,$mygroupid,'./backup'))) { $ftext .= '<br />'.$GLOBALS["Checks"]["orange"].'/backup directory is read only'; }
										if (!(fileReadWrite($myuserid,$mygroupid,'./sites'))) { $ftext .= '<br />'.$GLOBALS["Checks"]["orange"].'/sites directory is read only'; }
										if (!(fileReadWrite($myuserid,$mygroupid,'./themes'))) { $ftext .= '<br />'.$GLOBALS["Checks"]["orange"].'/themes directory is read only'; }
										if (!(fileReadWrite($myuserid,$mygroupid,'./admin/styles/icache'))) { $ftext .= '<br />'.$GLOBALS["Checks"]["orange"].'/admin/styles/icache directory is read only'; }
										if ($text == '') { $text = $GLOBALS["Checks"]["green"].'Configuration file is read/write'; }
										basetext($text);
										if ($GLOBALS["DebugMode"]) { debug_msg($text,$GLOBALS["Titles"]["InstallLog"]); }
										if ($ftext == '') {
											$ftext = '<br />'.$GLOBALS["Checks"]["green"].'Directories are all read/write';
											basetext($ftext);
											if ($GLOBALS["DebugMode"]) { debug_msg($ftext,$GLOBALS["Titles"]["InstallLog"]); }
										 }
										?>
									</td>
								</tr>
							</table>
						</td>
					</tr>
				</table>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<table border="0" cellpadding="1" cellspacing="1">
					<tr><td align="left" valign="middle">
							<?php
							$text  = $GLOBALS["Checks"]["green"].'A green dot indicates that this is acceptable.<br />';
							$text .= $GLOBALS["Checks"]["orange"].'An orange dot indicates that some functionality may be restricted, or that you may encounter some errors during the installation or while running ezContents.<br />';
							$text .= $GLOBALS["Checks"]["red"].'A red dot indicates that ezContents should not be run without changes to your PHP/Server configuration.<br />Don\'t continue with the installation if you see a red dot.';
							basetext($text);
							?>
						</td>
					</tr>
				</table>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php blocktext($HTTP_SERVER_VARS["HTTP_USER_AGENT"]); ?>
			</td>
		</tr>
		<?php
		if ($Status) {
			?>
			<tr><td align="center" valign="middle">
					<input type="button" class="ip_text" value="Continue with Installation" onClick="location.href='install.php?mode=languages'">
				</td>
			</tr>
			<?php
		}
		?>
	</table>
	<?php
} // function test_screen()


function read_languages()
{
	$languagecount = 0;
	$savedir = getcwd();
	chdir('./languages');
	if ($handle = @opendir('.')) {
		while ($filename = readdir($handle)) {
			if ((is_dir($filename)) && (!($filename == '..') && !($filename == '.') && !($filename == 'CVS'))) {
				$GLOBALS["languages"][] = $filename;
				$languagecount++;
			}
		}
		closedir($handle);
	}
	chdir($savedir);
	return $languagecount;
} // function read_languages()


function language_screen()
{
	$languagecount = read_languages();

	?>
	<form name="language_data" action="install.php" method="post" enctype="multipart/form-data">
	<table border=0>
		<tr><td align="center" valign="middle">
				<?php blocktitle("Languages"); ?>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php blocktext('Please select the languages that you wish to install.'); ?>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<table border="1" height="100%" width="60%" cellpadding="1" cellspacing="1">
					<tr><td align="center" valign="middle">
							<table border="0" height="100%" width="100%" cellpadding="0" cellspacing="2">
								<tr><td align="right"><b><u><?php basetext("Language"); ?><u></b></td>
									<td align="center"><b><u><?php basetext("Install"); ?><u></b></td>
									<td align="left"><b><u><?php basetext("Default"); ?><u></b></td>
								</tr>
								<?php
								for ($i=0; $i < $languagecount; $i++) {
									$language = strtolower($GLOBALS["languages"][$i]);
									echo '<tr><td align="right">';
									basetext(mouseover($language,$language,"Languages"));
									echo '</td><td align="center">';
									if (strtolower($GLOBALS["Available"][$language]) == 'yes') {
										echo '<input type="checkbox" name="'.$language.'" value="Y" checked>';
									}
									echo '</td><td align="left">';
									if (strtolower($GLOBALS["Available"][$language]) == 'yes') {
										echo '<input type="radio" name="defaultlanguage" value="'.$language.'"';
										if ($language == 'en') { echo " checked"; }
										echo '>';
									}
									echo '</td><td align="left">';
									if (strtolower($GLOBALS["Available"][$language]) != 'yes') { basetext(mouseover("not yet available",$language,"Languages")); }
									echo '</td></tr>';
								}
								?>
							</table>
						</td>
					</tr>
				</table>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php
				$checkref = '<a href="#" class="help_text" onClick="';
				for ($i=0; $i < $languagecount; $i++) {
					$j = $GLOBALS["languages"][$i];
					if (strtolower($GLOBALS["Available"][$j]) == 'yes') { $checkref .= 'window.document.language_data.'.$GLOBALS["languages"][$i].'.checked=true;'; }
				}
				$checkref .= '" ';
				$checkref .= 'onMouseOver="window.document.helpform.helptext.value=\''.str_replace('\'','\\\'',str_replace(chr(10),'\n\r',$GLOBALS["Help"]["LanguageSelectAll"])).'\';"';
				$checkref .= 'onMouseOut="window.document.helpform.helptext.value=\''.str_replace('\'','\\\'',str_replace(chr(10),'\n\r',$GLOBALS["Help"]["Languages"])).'\'">';
				$checkref .= 'Check All</a>';
				$uncheckref = '<a href="#" class="help_text" onClick="';
				for ($i=0; $i < $languagecount; $i++) {
					$j = $GLOBALS["languages"][$i];
					if (strtolower($GLOBALS["Available"][$j]) == 'yes') { $uncheckref .= 'window.document.language_data.'.$GLOBALS["languages"][$i].'.checked=false;'; }
				}
				$uncheckref .= '" ';
				$uncheckref .= 'onMouseOver="window.document.helpform.helptext.value=\''.str_replace('\'','\\\'',str_replace(chr(10),'\n\r',$GLOBALS["Help"]["LanguageSelectNone"])).'\';"';
				$uncheckref .= 'onMouseOut="window.document.helpform.helptext.value=\''.str_replace('\'','\\\'',str_replace(chr(10),'\n\r',$GLOBALS["Help"]["Languages"])).'\'">';
				$uncheckref .= 'Uncheck All</a>';
				basetext($checkref.'&nbsp;&nbsp;/&nbsp;&nbsp;'.$uncheckref);
				?>
		</tr>
		<tr><td align="center" valign="middle">
				<input type="hidden" name="mode" value="modules">
				<input type="submit" class="ip_text" name="submit" value="Submit Language List">
			</td>
		</tr>
	</table>
	</form>
	<?php
} // function language_screen()


function read_modules()
{
	$modulecount = 0;
	$savedir = getcwd();
	chdir('./modules');
	if ($handle = @opendir('.')) {
		while ($filename = readdir($handle)) {
			if ((is_dir($filename)) && (!($filename == '..') && !($filename == '.') && !($filename == 'CVS'))) {
				$GLOBALS["modules"][] = $filename;
				$modulecount++;
			}
		}
		closedir($handle);
	}
	chdir($savedir);
	return $modulecount;
} // function read_modules()


function module_screen()
{
	global $HTTP_POST_VARS;

	$modulecount = read_modules();

	?>
	<form name="module_data" action="install.php" method="post" enctype="multipart/form-data">
	<table border=0>
		<tr><td align="center" valign="middle">
				<?php blocktitle("Modules"); ?>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php blocktext('Please select the modules that you wish to install.'); ?>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<table border="1" height="100%" width="45%" cellpadding="1" cellspacing="1">
					<tr><td align="center" valign="middle">
							<table border="0" height="100%" width="100%" cellpadding="0" cellspacing="2">
								<tr><td align="left"><b><u><?php basetext("Module"); ?><u></b></td>
									<td align="center"><b><u><?php basetext("Install"); ?><u></b></td>
								</tr>
								<?php
								for ($i=0; $i < $modulecount; $i++) {
									echo '<tr><td>';
									basetext(mouseover($GLOBALS["modules"][$i],$GLOBALS["modules"][$i],"Modules"));
									echo '</td><td align="center">';
									echo '<input type="checkbox" name="'.$GLOBALS["modules"][$i].'" value="Y" checked>';
									echo '</td></tr>';
								}
								?>
							</table>
						</td>
					</tr>
				</table>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php
				$checkref = '<a href="#" class="help_text" onClick="';
				for ($i=0; $i < $modulecount; $i++) {
					$checkref .= 'window.document.module_data.'.$GLOBALS["modules"][$i].'.checked=true;';
				}
				$checkref .= '" ';
				$checkref .= 'onMouseOver="window.document.helpform.helptext.value=\''.str_replace('\'','\\\'',str_replace(chr(10),'\n\r',$GLOBALS["Help"]["ModuleSelectAll"])).'\';"';
				$checkref .= 'onMouseOut="window.document.helpform.helptext.value=\''.str_replace('\'','\\\'',str_replace(chr(10),'\n\r',$GLOBALS["Help"]["Modules"])).'\'">';
				$checkref .= 'Check All</a>';
				$uncheckref = '<a href="#" class="help_text" onClick="';
				for ($i=0; $i < $modulecount; $i++) {
					$uncheckref .= 'window.document.module_data.'.$GLOBALS["modules"][$i].'.checked=false;';
				}
				$uncheckref .= '" ';
				$uncheckref .= 'onMouseOver="window.document.helpform.helptext.value=\''.str_replace('\'','\\\'',str_replace(chr(10),'\n\r',$GLOBALS["Help"]["ModuleSelectNone"])).'\';"';
				$uncheckref .= 'onMouseOut="window.document.helpform.helptext.value=\''.str_replace('\'','\\\'',str_replace(chr(10),'\n\r',$GLOBALS["Help"]["Modules"])).'\'">';
				$uncheckref .= 'Uncheck All</a>';
				basetext($checkref.'&nbsp;&nbsp;/&nbsp;&nbsp;'.$uncheckref);
				?>
		</tr>
		<tr><td align="center" valign="middle">
				<?php
				if ($GLOBALS["DebugMode"]) { debug_msg('Installing:<ul>',$GLOBALS["Titles"]["Languages"]); }
				$savedir = getcwd();
				chdir('./languages');
				if ($handle = @opendir('.')) {
					while ($filename = readdir($handle)) {
						if ((is_dir($filename)) && (!($filename == '..') && !($filename == '.'))) {
							if ($HTTP_POST_VARS[$filename] == 'Y') {
								echo '<input type="hidden" name="'.$filename.'" value="'.$HTTP_POST_VARS[$filename].'">';
								$debugmsg = '<li>'.$filename;
								if ($filename == $HTTP_POST_VARS["defaultlanguage"]) { $debugmsg .= ' as default'; }
								if ($GLOBALS["DebugMode"]) { debug_msg($debugmsg,$GLOBALS["Titles"]["Languages"]); }
							}
						}
					}
					closedir($handle);
				}
				chdir($savedir);
				if ($GLOBALS["DebugMode"]) { debug_msg('</ul>',$GLOBALS["Titles"]["Languages"]); }
				?>
				<input type="hidden" name="defaultlanguage" value="<?php echo $HTTP_POST_VARS["defaultlanguage"]; ?>">
				<input type="hidden" name="mode" value="database">
				<input type="submit" class="ip_text" name="submit" value="Submit Module List">
			</td>
		</tr>
	</table>
	</form>
	<?php
} // function module_screen()


function database_screen()
{
	global $HTTP_POST_VARS;

	?>
	<form name="db_data" action="install.php" method="post" enctype="multipart/form-data">
	<table border=0>
		<tr><td align="center" valign="middle">
				<?php blocktitle("Database"); ?>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php blocktext('Please enter the following details about your mySQL server<br />and any existing ezcontents database that you wish to upgrade.'); ?>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<table border="1" height="100%" width="95%" cellpadding="1" cellspacing="1">
					<tr><td align="center" valign="middle">
							<table border="0" height="100%" width="100%" cellpadding="4" cellspacing="4">
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Type of Install :','InstallType','Database')); ?>
									</td>
									<td valign="top">
										<input type="radio" name="InstallType" value='newinstall' checked><?php basetext(mouseover('New Installation','InstallNew','Database')); ?><br />
										<input type="radio" name="InstallType" value='upgrade'><?php basetext(mouseover('Upgrade','InstallUpgrade','Database')); ?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Create Database :','CreateDatabase','Database')); ?>
									</td>
									<td valign="top">
										<input type="radio" name="CreateDatabase" value='no' checked><?php basetext(mouseover('No','OldDatabase','Database')); ?><br />
										<input type="radio" name="CreateDatabase" value='yes'><?php basetext(mouseover('Yes','NewDatabase','Database')); ?>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Database driver :','DBDriver','Database')); ?>
									</td>
									<td valign="top">
										<select class="ip_text" size="1" name="DBType">
											<option value="mysql">MySQL
											<option value="mysqlt">MySQL Transactional
										</select>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('IP Address of the database server :','DBAddress','Database')); ?>
									</td>
									<td valign="top">
										<input class="ip_text" type="text" size="15" name="DBServer" value="localhost">
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Database name :','DBName','Database')); ?>
									</td>
									<td valign="top">
										<input class="ip_text" type="text" size="20" name="DBName" value="ezcontents">
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Database login ID :','DBLogin','Database')); ?>
									</td>
									<td valign="top">
										<input class="ip_text" type="text" size="20" name="DBLogin">
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Database password :','DBPassword','Database')); ?>
									</td>
									<td valign="top">
										<input class="ip_text" type="password" size="20" name="DBPassword">
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Table prefix :','DBPrefix','Database')); ?>
									</td>
									<td valign="top">
										<input class="ip_text" type="text" size="8" name="DBPrefix">
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Use persistent connections :','DBPersistent','Database')); ?>
									</td>
									<td valign="top">
										<select class="ip_text" size="1" name="DBPersistent">
											<option value="N">No
											<option value="Y">Yes
										</select>
									</td>
								</tr>
								<tr><td align="right" valign="top">
										<?php basetext(mouseover('Log database updates during install/upgrade :','InstallLog','Database')); ?>
									</td>
									<td valign="top">
										<input type="radio" name="DBLogUpdates" value='N' checked><?php basetext(mouseover('No','LogNo','Database')); ?>
										<input type="radio" name="DBLogUpdates" value='Y'><?php basetext(mouseover('Yes','LogYes','Database')); ?>
									</td>
								</tr>
							</table>
						</td>
					</tr>
				</table>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php
				$savedir = getcwd();
				chdir('./languages');
				if ($handle = @opendir('.')) {
					while ($filename = readdir($handle)) {
						if ((is_dir($filename)) && (!($filename == '..') && !($filename == '.'))) {
							if ($HTTP_POST_VARS[$filename] == 'Y') {
								echo '<input type="hidden" name="'.$filename.'" value="'.$HTTP_POST_VARS[$filename].'">';
							}
						}
					}
					closedir($handle);
				}
				chdir($savedir);
				if ($GLOBALS["DebugMode"]) { debug_msg('Installing:<ul>',$GLOBALS["Titles"]["Modules"]); }
				chdir('./modules');
				if ($handle = @opendir('.')) {
					while ($filename = readdir($handle)) {
						if ((is_dir($filename)) && (!($filename == '..') && !($filename == '.'))) {
							if ($HTTP_POST_VARS[$filename] == 'Y') {
								echo '<input type="hidden" name="'.$filename.'" value="'.$HTTP_POST_VARS[$filename].'">';
								$debugmsg = '<li>'.$filename;
								if ($GLOBALS["DebugMode"]) { debug_msg($debugmsg,$GLOBALS["Titles"]["Modules"]); }
							}
						}
					}
					closedir($handle);
				}
				chdir($savedir);
				if ($GLOBALS["DebugMode"]) { debug_msg('</ul>',$GLOBALS["Titles"]["Modules"]); }
				?>
				<input type="hidden" name="defaultlanguage" value="<?php echo $HTTP_POST_VARS["defaultlanguage"]; ?>">
				<input type="hidden" name="mode" value="install">
				<input type="submit" class="ip_text" name="submit" value="Submit Database Details">
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php blocktext('This may take a few minutes.'); ?>
			</td>
		</tr>
	</table>
	</form>
	<?php
} // function database_screen()


function install_message($colour,$message)
{
	$image = $GLOBALS["Checks"][$colour];
	?>
			</td>
		</tr>
		<tr>
			<td align="center" valign="middle">
				<?php
				blocktext($image.$message);
} // function install_message()


function install_ezContents()
{
	global $HTTP_POST_VARS;

	if (get_magic_quotes_runtime() == 1) { set_magic_quotes_runtime(0); }


	$GLOBALS["dbConn"] = &ADONewConnection(strtolower($HTTP_POST_VARS["DBType"]));
	if ($HTTP_POST_VARS["CreateDatabase"] == 'yes') {
		$GLOBALS["dbConn"]->Connect($HTTP_POST_VARS["DBServer"],$HTTP_POST_VARS["DBLogin"],$HTTP_POST_VARS["DBPassword"])
			or die('<table border=0 cellpadding=8 cellspacing=8 width="100%"><tr><td align="center"><font color="yellow">Unable to connect to MySQL server.</font></td></tr></table>');
	} else {
		$GLOBALS["dbConn"]->Connect($HTTP_POST_VARS["DBServer"],$HTTP_POST_VARS["DBLogin"],$HTTP_POST_VARS["DBPassword"],$HTTP_POST_VARS["DBName"])
			or die('<table border=0 cellpadding=8 cellspacing=8 width="100%"><tr><td align="center"><font color="yellow">Unable to connect to database '.$HTTP_POST_VARS["DBName"].'.</font></td></tr></table>');
	}


	$GLOBALS["Log"] = $HTTP_POST_VARS["DBLogUpdates"]
	?>
	<table BORDER="0" height="100%" width="100%" cellpadding="4" cellspacing="2">
		<tr><td align="center" valign="middle">
				<?php
				$Status = True;
				$installtype = $HTTP_POST_VARS["InstallType"];
				if ($installtype == 'upgrade') {
					blocktitle("Upgrade");
					if ($HTTP_POST_VARS["CreateDatabase"] == 'yes') {
						if (!$GLOBALS["dbConn"]->SelectDB($HTTP_POST_VARS["DBName"])) {
							install_message('red','Cannot connect to database '.$HTTP_POST_VARS["DBName"]);
							$Status = False;
						}
					}
					if ($Status) { test_database($HTTP_POST_VARS["DBName"],$HTTP_POST_VARS["DBPrefix"],$Status); }
					if ($Status) { populate_database('ezcupg_','core_tables',$Status); }
					if ($Status) {
						install_message('green','Initial phase of database upgrade completed.');
						create_languages('ezcupg_',$Status);
						if ($Status) { install_message('green','Selected Languages installed to the database.'); }
					}
					if ($Status) {
						create_modules('ezcupg_',$Status);
						if ($Status) { install_message('green','Selected Modules installed to the database.'); }
					}
					if ($Status) { transfer_database($HTTP_POST_VARS["DBPrefix"],$Status); }
					if ($Status) {
						install_message('green','Second phase of database upgrade completed.');
						upgrade_database($HTTP_POST_VARS["DBPrefix"],$Status);
					}
					if ($Status) {
						install_message('green','Third phase of database upgrade completed.');
						drop_old_tables($HTTP_POST_VARS["DBPrefix"],$Status);
					}
					if ($Status) {
						install_message('green','Fourth phase of database upgrade completed.');
						rename_new_tables($HTTP_POST_VARS["DBPrefix"],$Status);
						if ($Status) { install_message('green','Final phase of database upgrade completed.'); }
					}
				} else {
					blocktitle("NewInstall");
					if ($HTTP_POST_VARS["CreateDatabase"] == 'yes') {
						if (!$GLOBALS["dbConn"]->SelectDB($HTTP_POST_VARS["DBName"])) {
							create_database($HTTP_POST_VARS["DBName"],$Status);
						}
					}
					if ($Status) { populate_database($HTTP_POST_VARS["DBPrefix"],'core_tables',$Status); }
					if ($Status) {
						install_message('green','Initial phase of database upgrade completed.');
						create_languages($HTTP_POST_VARS["DBPrefix"],$Status);
						if ($Status) { install_message('green','Selected Languages installed to the database.'); }
						if ($Status) {
							create_modules($HTTP_POST_VARS["DBPrefix"],$Status);
							if ($Status) { install_message('green','Selected Modules installed to the database.'); }
						}
					}
					if ($Status) { populate_database($HTTP_POST_VARS["DBPrefix"],'new_install',$Status); }
					if ($Status) { specialcontents($HTTP_POST_VARS["DBPrefix"],$HTTP_POST_VARS["DBPrefix"],$Status); }
					if ($Status) { install_message('green','Final phase of database population completed.'); }
				}
				if ($Status) { write_config_file($Status); }
				if ($Status) {
					install_message('green','Configuration file written.');
					write_htaccess_files($Status);
				}
				if ($Status) { install_message('green','ezContents configuration completed.'); }
				?>
			</td>
		</tr>
		<tr><td align="center" valign="middle">
				<?php
				if ($Status) {
					if ($installtype == "upgrade") { blocktext('Upgrade has completed successfully.'); }
					else { blocktext('Installation has completed successfully.'); }
				} else {
					if ($installtype == "upgrade") { blocktext('Upgrade has failed.','red'); }
					else { blocktext('Installation has failed.','red'); }
				}
				?>
			</td>
		</tr>

		<?php
		//	If the install/upgrade ran successfully, then we rename the installation script so that it can't be run again by accident
		if ($Status) { $Status = rename("install.php","install.php.complete"); }
		?>

		<tr><td align="center" valign="middle">
				<input type="button" class="ip_text" value="Run ezContents" onClick="location.href = './admin/index.php'">
			</td>
		</tr>
	</table>
	<?php

	$GLOBALS["dbConn"]->Close();
} // function install_ezContents()




function sqlLog(&$sqlString)
{
	if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlString,$GLOBALS["Titles"]["InstallLog"]); }
} // function sqlLog()


function create_database($DBName,&$Status)
{
	if ($GLOBALS["Log"] == 'Y') { debug_msg('****	Creating Database '.$DBName,$GLOBALS["Titles"]["InstallLog"]); }

	$Status = True;
	$sqlQuery = "CREATE DATABASE ".$DBName.";";
	sqlLog($sqlQuery);
	$result = dbExecute($sqlQuery,true);

	if ($result) {
		install_message('green','Database '.$DBName.' created.');
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Database '.$DBName.' created',$GLOBALS["Titles"]["InstallLog"]); }
		$GLOBALS["dbConn"]->SelectDB($DBName);
	} else {
		install_message('red','Failed to create database '.$DBName);
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Failed to create database '.$DBName,$GLOBALS["Titles"]["InstallLog"]); }
		$Status = False;
	}
} // function create_database()


function test_database($DBName,$DBPrefix,&$Status)
{
	if ($GLOBALS["Log"] == 'Y') { debug_msg('****	Testing Database '.$DBName,$GLOBALS["Titles"]["InstallLog"]); }

	$Status = True;
	$tables = $GLOBALS["dbConn"]->MetaTables();
	if (in_array($DBPrefix.'authors',$tables) === False) {
		install_message('red','Database '.$DBName.' is not an ezContents 1.4x database;<br />or table prefix '.$DBPrefix.'is invalid');
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Database '.$DBName.' is not an ezContents 1.4x database; or prefix '.$DBPrefix.' is invalid',$GLOBALS["Titles"]["InstallLog"]); }
		$Status = False;
	}
} // function test_database()


function populate_database($DBPrefix,$ScriptFile,&$Status)
{
	if ($GLOBALS["Log"] == 'Y') { debug_msg('****	Populating Database using MySQL_ezcontents203_'.$ScriptFile.'.sql',$GLOBALS["Titles"]["InstallLog"]); }

	$Status = True;
	$fp = fopen('./sql/MySQL_ezcontents203_'.$ScriptFile.'.sql', "r");
	if (!$fp) {
		install_message('red','Unable to open MySQL_ezcontents203_'.$ScriptFile.'.sql file');
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Unable to open MySQL_ezcontents203_'.$ScriptFile.'.sql',$GLOBALS["Titles"]["InstallLog"]); }
		$Status = False;
	} else {
		$file = fread($fp, $GLOBALS["MaxFileSize"]);
		$file = str_replace("\r", "", $file);
		$query = explode(";\n",$file);
		for ($i=0; $i < count($query) - 1; $i++) {
			if ($Status) {
				$sqlQuery = trim($query[$i]);
				$workquery = explode("\n",$sqlQuery);
				for ($j=0; $j < count($workquery) - 1; $j++) {
					$test_workquery = trim($workquery[$j]);
					if (substr($test_workquery,0,1) == '#') { $workquery[$j] = ''; }
				}
				$sqlQuery = implode("",$workquery);
				if ((substr($sqlQuery,0,4) == 'DROP') || (substr($sqlQuery,0,6) == 'CREATE') || (substr($sqlQuery,0,6) == 'UPDATE') || (substr($sqlQuery,0,6) == 'INSERT')) {
					if (substr($sqlQuery,0,4) == 'DROP') {
						$sqlQuery = str_replace('DROP TABLE IF EXISTS ','DROP TABLE IF EXISTS '.$DBPrefix, $sqlQuery);
					}
					if (substr($sqlQuery,0,6) == 'CREATE') {
						$sqlQuery = str_replace('CREATE TABLE ','CREATE TABLE '.$DBPrefix, $sqlQuery);
					}
					if (substr($sqlQuery,0,6) == 'UPDATE') {
						$sqlQuery = str_replace('UPDATE ','UPDATE '.$DBPrefix, $sqlQuery);
					}
					if (substr($sqlQuery,0,6) == 'INSERT') {
						$sqlQuery = str_replace('INSERT INTO ','INSERT INTO '.$DBPrefix, $sqlQuery);
					}
					sqlLog($sqlQuery);
					$result = dbExecute($sqlQuery,true);
					if (!$result) { $Status = False; }
				}
			}
		}
		$fp = fclose($fp);
	}
} // function populate_database()


function setusergroup_languages($Language,$DBPrefix,$text,$keyref,&$Status)
{
	$sqlQuery = "INSERT INTO ".$DBPrefix."usergroups (usergroupdesc, usergroupname, language, authorid) VALUES ('".$text."', '".$keyref."', '".$Language."', 1)";
	sqlLog($sqlQuery);
	$result = dbExecute($sqlQuery,true);
	if (!$result) { $Status = False; }
} // function setusergroup_languages()


function settagcategory_languages($Language,$DBPrefix,$text,$keyref,&$Status)
{
	$sqlQuery = "INSERT INTO ".$DBPrefix."tagcategories (catdesc, catname, language, authorid) VALUES ('".$text."', '".$keyref."', '".$Language."', 1)";
	sqlLog($sqlQuery);
	$result = dbExecute($sqlQuery,true);
	if (!$result) { $Status = False; }
} // function settagcategory_languages()


function create_language($Language,$DBPrefix,&$Status)
{
	if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Creating language'.$Language,$GLOBALS["Titles"]["InstallLog"]); }

	$Status = True;
	$fp = fopen('./'.$Language.'/install.sql', "r");
	if (!$fp) {
		install_message('orange','Unable to open '.$Language.' install.sql file');
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Unable to create language',$GLOBALS["Titles"]["InstallLog"]); }
	} else {
		$file = fread($fp, $GLOBALS["MaxFileSize"]);
		$file = str_replace("\r", "", $file);
		$query = explode(";\n",$file);
		for ($i=0; $i < count($query) - 1; $i++) {
			if ($Status) {
				$sqlQuery = trim($query[$i]);
				$workquery = explode("\n",$sqlQuery);
				for ($j=0; $j < count($workquery) - 1; $j++) {
					$test_workquery = trim($workquery[$j]);
					if (substr($test_workquery,0,1) == '#') { $workquery[$j] = ''; }
				}
				$sqlQuery = implode("",$workquery);
				if ((substr($sqlQuery,0,4) == 'DROP') || (substr($sqlQuery,0,6) == 'CREATE') || (substr($sqlQuery,0,6) == 'UPDATE') || (substr($sqlQuery,0,6) == 'INSERT')) {
					if (substr($sqlQuery,0,4) == 'DROP') {
						$sqlQuery = str_replace('DROP TABLE IF EXISTS ','DROP TABLE IF EXISTS '.$DBPrefix, $sqlQuery);
					}
					if (substr($sqlQuery,0,6) == 'CREATE') {
						$sqlQuery = str_replace('CREATE TABLE ','CREATE TABLE '.$DBPrefix, $sqlQuery);
					}
					if (substr($sqlQuery,0,6) == 'UPDATE') {
						$sqlQuery = str_replace('UPDATE ','UPDATE '.$DBPrefix, $sqlQuery);
					}
					if (substr($sqlQuery,0,6) == 'INSERT') {
						$sqlQuery = str_replace('INSERT INTO ','INSERT INTO '.$DBPrefix, $sqlQuery);
					}
					sqlLog($sqlQuery);
					$result = dbExecute($sqlQuery,true);
					if (!$result) { $Status = False; }
				}
			}
		}
		$fp = fclose($fp);
	}
	if ($Status) { setusergroup_languages($Language,$DBPrefix,'Administrators','administrator',$Status); }
	if ($Status) { setusergroup_languages($Language,$DBPrefix,'Contributors','contributor',$Status); }
	if ($Status) { setusergroup_languages($Language,$DBPrefix,'Translators','translator',$Status); }
	if ($Status) { setusergroup_languages($Language,$DBPrefix,'Members','member',$Status); }
	if ($Status) { setusergroup_languages($Language,$DBPrefix,'Probationary Members','probationer',$Status); }

	if ($Status) { settagcategory_languages($Language,$DBPrefix,'Table','table',$Status); }
	if ($Status) { settagcategory_languages($Language,$DBPrefix,'Titles','title',$Status); }
	if ($Status) { settagcategory_languages($Language,$DBPrefix,'List','list',$Status); }
	if ($Status) { settagcategory_languages($Language,$DBPrefix,'Text Formatting','text',$Status); }
	if ($Status) { settagcategory_languages($Language,$DBPrefix,'Miscellaneous','other',$Status); }

	if (!($Status)) { install_message('red','Error installing language '.$Language); }
} // function create_language()


function create_languages($DBPrefix,&$Status)
{
	global $HTTP_POST_VARS;

	if ($GLOBALS["Log"] == 'Y') { debug_msg('****	Creating Languages',$GLOBALS["Titles"]["InstallLog"]); }

	$Status = True;
	$LanguageCount = 0;
	$savedir = getcwd();
	chdir('./languages');
	if ($handle = @opendir('.')) {
		while (($Status) && ($filename = readdir($handle))) {
			if ((is_dir($filename)) && (!($filename == '..') && !($filename == '.'))) {
				if ($HTTP_POST_VARS[$filename] == 'Y') {
					create_language($filename,$DBPrefix,$Status);
					$LanguageCount++;
				}
			}
		}
		closedir($handle);
	}
	chdir($savedir);

	$sqlQuery = "UPDATE ".$DBPrefix."settings SET settingvalue='".$HTTP_POST_VARS["defaultlanguage"]."' WHERE settingname='default_language'";
	sqlLog($sqlQuery);
	$result = dbExecute($sqlQuery,true);
	if (!$result) { $Status = False;
	} else {
		if ($LanguageCount > 1) {
			$sqlQuery = "UPDATE ".$DBPrefix."settings SET settingvalue='Y' WHERE settingname='multilanguage'";
			sqlLog($sqlQuery);
			$result = dbExecute($sqlQuery,true);
			if (!$result) { $Status = False; }
		}
	}
} // function create_languages()


function create_module($Module,$DBPrefix,&$Status)
{
	if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Creating module'.$Module,$GLOBALS["Titles"]["InstallLog"]); }

	$Status = True;
	$fp = fopen('./'.$Module.'/install.sql', "r");
	if (!$fp) {
		install_message('orange','Unable to open '.$Module.' install.sql file');
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Unable to create module',$GLOBALS["Titles"]["InstallLog"]); }
	} else {
		$file = fread($fp, $GLOBALS["MaxFileSize"]);
		$file = str_replace("\r", "", $file);
		$query = explode(";\n",$file);
		for ($i=0; $i < count($query) - 1; $i++) {
			if ($Status) {
				$sqlQuery = trim($query[$i]);
				$workquery = explode("\n",$sqlQuery);
				for ($j=0; $j < count($workquery) - 1; $j++) {
					$test_workquery = trim($workquery[$j]);
					if (substr($test_workquery,0,1) == '#') { $workquery[$j] = ''; }
				}
				$sqlQuery = implode("",$workquery);
				if ((substr($sqlQuery,0,4) == 'DROP') || (substr($sqlQuery,0,6) == 'CREATE') || (substr($sqlQuery,0,6) == 'UPDATE') || (substr($sqlQuery,0,6) == 'INSERT')) {
					if (substr($sqlQuery,0,4) == 'DROP') {
						$sqlQuery = str_replace('DROP TABLE IF EXISTS ','DROP TABLE IF EXISTS '.$DBPrefix, $sqlQuery);
					}
					if (substr($sqlQuery,0,6) == 'CREATE') {
						$sqlQuery = str_replace('CREATE TABLE ','CREATE TABLE '.$DBPrefix, $sqlQuery);
					}
					if (substr($sqlQuery,0,6) == 'UPDATE') {
						$sqlQuery = str_replace('UPDATE ','UPDATE '.$DBPrefix, $sqlQuery);
					}
					if (substr($sqlQuery,0,6) == 'INSERT') {
						$sqlQuery = str_replace('INSERT INTO ','INSERT INTO '.$DBPrefix, $sqlQuery);
					}
					sqlLog($sqlQuery);
					$result = dbExecute($sqlQuery,true);
					if (!$result) { $Status = False; }
				}
			}
		}
		$fp = fclose($fp);
	}
	if (!($Status)) { install_message('red','Error installing module '.$Module); }
} // function create_module()


function create_modules($DBPrefix,&$Status)
{
	global $HTTP_POST_VARS;

	if ($GLOBALS["Log"] == 'Y') { debug_msg('****	Creating Modules',$GLOBALS["Titles"]["InstallLog"]); }

	$Status = True;
	$savedir = getcwd();
	chdir('./modules');
	if ($handle = @opendir('.')) {
		while (($Status) && ($filename = readdir($handle))) {
			if ((is_dir($filename)) && (!($filename == '..') && !($filename == '.'))) {
				if ($HTTP_POST_VARS[$filename] == 'Y') {
					create_module($filename,$DBPrefix,$Status);
				}
			}
		}
		closedir($handle);
	}
	chdir($savedir);
} // function create_modules()


function transfer_database($DBPrefix,&$Status)
{
	if ($GLOBALS["Log"] == 'Y') { debug_msg('****	Transferring data to new data structures',$GLOBALS["Titles"]["InstallLog"]); }

	$Status = True;
	$tables = $GLOBALS["dbConn"]->MetaTables();
	$num_tables = count($tables);
	$i = 0;
	while ($i < $num_tables) {
		if ($Status) {
			$tablename = $tables[$i];
			if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Testing table '.$tablename.' for upgrade',$GLOBALS["Titles"]["InstallLog"]); }
			if ((substr($tablename,0,strlen($DBPrefix)) == $DBPrefix) && (substr($tablename,0,7) != 'ezcupg_')) {
				if ($GLOBALS["Log"] == 'Y') { debug_msg('****			Table requires upgrade',$GLOBALS["Titles"]["InstallLog"]); }
				$FieldList = $GLOBALS["dbConn"]->MetaColumnNames($tablename);
				$newtablename = 'ezcupg_'.substr($tablename,strlen($DBPrefix));
				$NewFieldList = $GLOBALS["dbConn"]->MetaColumnNames($newtablename);
				if ($GLOBALS["Log"] == 'Y') {
					debug_msg('****			Field List in table '.$tablename,$GLOBALS["Titles"]["InstallLog"]);
					reset($FieldList);
					while (list ($key, $val) = each ($FieldList)) {
						debug_msg('****				'.$val,$GLOBALS["Titles"]["InstallLog"]);
					}
					reset($FieldList);
					debug_msg('****			Field List in new table '.$newtablename,$GLOBALS["Titles"]["InstallLog"]);
					reset($NewFieldList);
					while (list ($key, $val) = each ($NewFieldList)) {
						debug_msg('****				'.$val,$GLOBALS["Titles"]["InstallLog"]);
					}
					reset($FieldList);
				}

				$sqlQuery = 'SELECT * FROM '.$tablename;
				if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
				$result = dbRetrieve($sqlQuery,false,0,0);
				while ($rs = dbFetch($result)) {
					if ($Status) {
						$isql1 = 'INSERT INTO '.$newtablename.' ( ';
						$isql2 = ' ) VALUES ( ';
						$usql  = 'UPDATE '.$newtablename.' SET ';
						$k = 0;
						for ($j=0; $j < count($FieldList); $j++) {
							$ColumnName = $FieldList[$j];
							reset($NewFieldList);
							if (in_array($ColumnName,$NewFieldList) === True) {
								if ($k > 0) {
									$isql1 .= ', ';
									$isql2 .= ', ';
									$usql  .= ', ';
								} else {
									$keycol = $ColumnName;
									$keyval = dbStr($rs[$ColumnName]);
								}
								$isql1 .= $ColumnName;
								$isql2 .= "'".dbStr($rs[$ColumnName])."'";
								if (($newtablename == 'ezcupg_specialcontents') && ($ColumnName == 'scid')) {
									$k--;
								} else {
									$usql  .= $ColumnName."='".dbStr($rs[$ColumnName])."'";
								}
								$k++;
							}
						}
						if ($newtablename == 'ezcupg_specialcontents') {
							$keycol = 'scname';
							$keyval = $rs["scname"];
						}
						$isql = $isql1.$isql2.' );';
						$usql .= " WHERE ".$keycol."='".$keyval."';";
						if ($k > 0) {
							sqlLog($isql);
							$iresult = dbExecute($isql,false);
							if ($iresult === False) {
								sqlLog($usql);
								$uresult = dbExecute($usql,true);
								if (!$uresult) { $Status = False; }
							}
						}
					}
				}
				dbFreeResult($result);
			}
		}
		$i++;
	}
} // function transfer_database()


function specialcontents($DBPrefix,$SPrefix,&$Status)
{
	if ($DBPrefix != '') {
		//  Upgrade the specialcontents table (use prefix if appropriate)
		$sqlString = "UPDATE ".$SPrefix."specialcontents SET scuseprefix='Y';";
		sqlLog($sqlString);
		$uresult = dbExecute($sqlString,true);
		if (!$uresult) { $Status = False; }
	}
} // function specialcontents()


function upgrade_database($DBPrefix,&$Status)
{
	global $HTTP_POST_VARS;

	$Status = True;

	if ($GLOBALS["Log"] == 'Y') { debug_msg('****	Upgrading Database',$GLOBALS["Titles"]["InstallLog"]); }

	$baselanguage = 'en';
	//  Retrieve the default site language
	$sqlQuery = "SELECT settingvalue FROM ".$DBPrefix."settings WHERE settingname='default_language';";
	if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
	$result = dbRetrieve($sqlQuery,true,0,0);
	if ($rs = dbFetch($result)) { $baselanguage = $rs["settingvalue"]; }
	dbFreeResult($result);


	$masteruser = '';
	if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the authors table',$GLOBALS["Titles"]["InstallLog"]); }
	//  Upgrade the authors table
	$sqlQuery = 'SELECT * FROM '.$DBPrefix.'authors;';
	if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
	$result = dbRetrieve($sqlQuery,true,0,0);
	while ($rs = dbFetch($result)) {
		if ($Status) {
			//  Encrypt the user's password
			$md5password = md5($rs["password"]);
			//  Retrieve the 'master' user (site administrator) so that we have an account for granting ownership to all other 'owned' records.
			if (($masteruser == '') && ($rs["usergroup"] == 1)) { $masteruser = $rs["authorid"]; }
			//  Retrieve the usergroup code rather than the number used in previous versions
			$usergroup = $rs["usergroup"];
			$sqlString = "SELECT usergroupname FROM ezcupg_usergroups WHERE usergroupid='".$usergroup."';";
			$tresult = dbRetrieve($sqlString,true,0,0);
			$trs = dbFetch($tresult);
			$usergroupname = $trs["usergroupname"];
			dbFreeResult($tresult);
			//  Perform the update
			$sqlString = "UPDATE ezcupg_authors SET userpassword='".$md5password."',usergroup='".$usergroupname."' WHERE authorid='".$rs["authorid"]."';";
			sqlLog($sqlString);
			$uresult = dbExecute($sqlString,true);
			if (!$uresult) { $Status = False; }
		}
	}
	dbFreeResult($result);

	if ($Status) {
		//  Upgrade the banners table with the tag creator (master author) and fieldname change: (active => banneractive)
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the banners table',$GLOBALS["Titles"]["InstallLog"]); }
		$sqlQuery = 'SELECT * FROM '.$DBPrefix.'banners;';
		if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
		$result = dbRetrieve($sqlQuery,true,0,0);
		while ($rs = dbFetch($result)) {
			if ($Status) {
				$sqlString = "UPDATE ezcupg_banners SET banneractive='".$rs["active"]."', authorid='".$masteruser."';";
				sqlLog($sqlString);
				$uresult = dbExecute($sqlString,true);
				if (!$uresult) { $Status = False; }
			}
		}
	}

	if ($Status) {
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the tags table',$GLOBALS["Titles"]["InstallLog"]); }
		//  Remove any '[' or ']' from the tags table as these are now handled internally
		$sqlString = "DELETE FROM ezcupg_tags WHERE translation='".$GLOBALS["tqBlock1"]."' OR translation='".$GLOBALS["tqBlock2"]."';";
		sqlLog($sqlString);
		$uresult = dbExecute($sqlString,true);
		if (!$uresult) { $Status = False;
		} else {
			//  Upgrade the tags table with the tag creator (master author) and appropriate categories
			$sqlString = "UPDATE ezcupg_tags SET authorid='".$masteruser."', cat='text' WHERE tag IN ('b','/b','i','/i','u','/u');";
			sqlLog($sqlString);
			$uresult = dbExecute($sqlString,true);
			if (!$uresult) { $Status = False;
			} else {
				$sqlString = "UPDATE ezcupg_tags SET authorid='".$masteruser."', cat='list' WHERE tag IN ('ul','/ul','ol','/ol','li','/li');";
				sqlLog($sqlString);
				$uresult = dbExecute($sqlString,true);
				if (!$uresult) { $Status = False;
				} else {
					$sqlString = "UPDATE ezcupg_tags SET authorid='".$masteruser."', cat='title' WHERE tag IN ('h2','/h2','h3','/h3','h4','/h4');";
					sqlLog($sqlString);
					$uresult = dbExecute($sqlString,true);
					if (!$uresult) { $Status = False;
					} else {
						$sqlString = "UPDATE ezcupg_tags SET authorid='".$masteruser."', cat='table' WHERE tag IN ('table','/table','row','/row','cell_lt','cell_ct','cell_rt','cell_lc','cell_cc','cell_rc','cell_lb','cell_cb','cell_rb','/cell');";
						sqlLog($sqlString);
						$uresult = dbExecute($sqlString,true);
						if (!$uresult) { $Status = False;
						} else {
							$sqlString = "UPDATE ezcupg_tags SET authorid='".$masteruser."', cat='other' WHERE cat='';";
							sqlLog($sqlString);
							$uresult = dbExecute($sqlString,true);
							if (!$uresult) { $Status = False; }
						}
					}
				}
			}
		}
	}

	if ($Status) {
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the imageformattemplates table',$GLOBALS["Titles"]["InstallLog"]); }
		//  Upgrade the imageformattemplates table with the tag creator (master author)
		$sqlString = "UPDATE ezcupg_imageformattemplates SET authorid='".$masteruser."';";
		sqlLog($sqlString);
		$uresult = dbExecute($sqlString,true);
		if (!$uresult) { $Status = False; }
	}

	if ($Status) {
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the sidebartemplates table',$GLOBALS["Titles"]["InstallLog"]); }
		//  Upgrade the sidebartemplates table with the tag creator (master author)
		$sqlString = "UPDATE ezcupg_sidebartemplates SET authorid='".$masteruser."';";
		sqlLog($sqlString);
		$uresult = dbExecute($sqlString,true);
		if (!$uresult) { $Status = False; }
	}


	if ($Status) { specialcontents($DBPrefix,'ezcupg_',$Status); }

	if ($Status) {
		if ($HTTP_POST_VARS["diary"] == 'Y') {
			if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the diary table',$GLOBALS["Titles"]["InstallLog"]); }
			//  Upgrade the diary table (fieldname change: active => activeentry)
			$sqlQuery = 'SELECT * FROM '.$DBPrefix.'diary;';
			if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
			$result = dbRetrieve($sqlQuery,true,0,0);
			while ($rs = dbFetch($result)) {
				if ($Status) {
					$active = $rs["active"];
					//  Perform the update
					$sqlString = "UPDATE ezcupg_diary SET activeentry='".$active."' WHERE diaryid='".$rs["diaryid"]."';";
					sqlLog($sqlString);
					$uresult = dbExecute($sqlString,true);
					if (!$uresult) { $Status = False; }
				}
			}
			dbFreeResult($result);
		}
	}

	if ($Status) {
		if ($HTTP_POST_VARS["guestbook"] == 'Y') {
			if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the guestbook table',$GLOBALS["Titles"]["InstallLog"]); }
			//  Upgrade the guestbook table (fieldname change: active => activeentry)
			$sqlQuery = 'SELECT * FROM '.$DBPrefix.'guestbook;';
			if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
			$result = dbRetrieve($sqlQuery,true,0,0);
			while ($rs = dbFetch($result)) {
				if ($Status) {
					$active = $rs["active"];
					//  Perform the update
					$sqlString = "UPDATE ezcupg_guestbook SET activeentry='".$active."' WHERE guestbookid='".$rs["guestbookid"]."';";
					sqlLog($sqlString);
					$uresult = dbExecute($sqlString,true);
					if (!$uresult) { $Status = False; }
				}
			}
			dbFreeResult($result);
		}
	}

	if ($Status) {
		if ($HTTP_POST_VARS["news"] == 'Y') {
			if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the news table',$GLOBALS["Titles"]["InstallLog"]); }
			//  Upgrade the news table (fieldname change: active => activeentry)
			$sqlQuery = 'SELECT * FROM '.$DBPrefix.'news;';
			if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
			$result = dbRetrieve($sqlQuery,true,0,0);
			while ($rs = dbFetch($result)) {
				if ($Status) {
					$active = $rs["active"];
					//  Perform the update
					$sqlString = "UPDATE ezcupg_news SET activeentry='".$active."' WHERE newsid='".$rs["newsid"]."';";
					sqlLog($sqlString);
					$uresult = dbExecute($sqlString,true);
					if (!$uresult) { $Status = False; }
				}
			}
			dbFreeResult($result);
		}
	}

	if ($Status) {
		if ($HTTP_POST_VARS["links"] == 'Y') {
			//	Test to see if links module was installed in previous version
			$sqlQuery = "SELECT scname FROM ".$DBPrefix."specialcontents WHERE scname='links'";
			sqlLog($sqlQuery);
			$lresult = dbRetrieve($sqlQuery,true,0,0);
			$lRecCount = dbRowsReturned($lresult);
			dbFreeResult($lresult);
			if ($lRecCount > 0) {
				if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the links table',$GLOBALS["Titles"]["InstallLog"]); }
				//  Upgrade the links table (fieldname change: active => activeentry)
				$sqlQuery = 'SELECT * FROM '.$DBPrefix.'links;';
				if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
				$result = dbRetrieve($sqlQuery,true,0,0);
				while ($rs = dbFetch($result)) {
					if ($Status) {
						$active = $rs["active"];
						//  Perform the update
						$sqlString = "UPDATE ezcupg_links SET activeentry='".$active."' WHERE linksid='".$rs["linksid"]."';";
						sqlLog($sqlString);
						$uresult = dbExecute($sqlString,true);
						if (!$uresult) { $Status = False; }
					}
				}
				dbFreeResult($result);
			}
		}
	}

	if ($Status) {
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the topgroups table',$GLOBALS["Titles"]["InstallLog"]); }
		//  Upgrade the topgroups table
		$sqlQuery = 'SELECT * FROM '.$DBPrefix.'topgroups;';
		if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
		$result = dbRetrieve($sqlQuery,true,0,0);
		while ($rs = dbFetch($result)) {
			if ($Status) {
				//  Retrieve the usergroup codes rather than the number used in previous versions
				$usergroup = $rs["usergroup"];
				$usergroupnames = '';
				if (($usergroup != '') && ($usergroup != '99')) {
					$sqlString = "SELECT usergroupname FROM ezcupg_usergroups WHERE usergroupid<='".$usergroup."';";
					$tresult = dbRetrieve($sqlString,true,0,0);
					while ($trs = dbFetch($tresult)) {
						$usergroupnames .= ','.$trs["usergroupname"];
					}
					dbFreeResult($tresult);
				}
				//  Perform the update
				$sqlString = "UPDATE ezcupg_topgroups SET topgroupname=topgroupid, language='".$baselanguage."', usergroups='".$usergroupnames."', authorid='".$masteruser."' WHERE topgroupid='".$rs["topgroupid"]."';";
				sqlLog($sqlString);
				$uresult = dbExecute($sqlString,true);
				if (!$uresult) { $Status = False; }
			}
		}
		dbFreeResult($result);
	}

	if ($Status) {
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the groups table',$GLOBALS["Titles"]["InstallLog"]); }
		//  Upgrade the groups table
		$sqlQuery = 'SELECT * FROM '.$DBPrefix.'groups;';
		if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
		$result = dbRetrieve($sqlQuery,true,0,0);
		while ($rs = dbFetch($result)) {
			if ($Status) {
				//  Retrieve the subgroup count
				$sqlString = "SELECT COUNT(subgroupid) AS count FROM ".$DBPrefix."subgroups WHERE groupid='".$rs["groupid"]."';";
				$tresult = dbRetrieve($sqlString,true,0,0);
				$trs = dbFetch($tresult);
				$subgroupcount = $trs["count"];
				dbFreeResult($tresult);
				//  Retrieve the usergroup codes rather than the number used in previous versions
				$usergroup = $rs["usergroup"];
				$usergroupnames = '';
				if (($usergroup != '') && ($usergroup != '99')) {
					$sqlString = "SELECT usergroupname FROM ezcupg_usergroups WHERE usergroupid<='".$usergroup."';";
					$tresult = dbRetrieve($sqlString,true,0,0);
					while ($trs = dbFetch($tresult)) {
						$usergroupnames .= ','.$trs["usergroupname"];
					}
					dbFreeResult($tresult);
				}
				//  Perform the update
				$sqlString = "UPDATE ezcupg_groups SET groupname=groupid, topgroupname='".$rs["topgroupid"]."', language='".$baselanguage."', usergroups='".$usergroupnames."', subgroupcount='".$subgroupcount."', authorid='".$masteruser."' WHERE groupid='".$rs["groupid"]."';";
				sqlLog($sqlString);
				$uresult = dbExecute($sqlString,true);
				if (!$uresult) { $Status = False; }
			}
		}
		dbFreeResult($result);
	}

	if ($Status) {
		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the subgroups table',$GLOBALS["Titles"]["InstallLog"]); }
		//  Upgrade the subgroups table
		$sqlQuery = 'SELECT * FROM '.$DBPrefix.'subgroups;';
		if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
		$result = dbRetrieve($sqlQuery,true,0,0);
		while ($rs = dbFetch($result)) {
			if ($Status) {
				//  Retrieve the usergroup codes rather than the number used in previous versions
				$usergroup = $rs["usergroup"];
				$usergroupnames = '';
				if (($usergroup != '') && ($usergroup != '99')) {
					$sqlString = "SELECT usergroupname FROM ezcupg_usergroups WHERE usergroupid<='".$usergroup."';";
					$tresult = dbRetrieve($sqlString,true,0,0);
					while ($trs = dbFetch($tresult)) {
						$usergroupnames .= ','.$trs["usergroupname"];
					}
					dbFreeResult($tresult);
				}
				//  Perform the update
				$sqlString = "UPDATE ezcupg_subgroups SET subgroupname=subgroupid, groupname='".$rs["groupid"]."', language='".$baselanguage."', usergroups='".$usergroupnames."', authorid='".$masteruser."' WHERE subgroupid='".$rs["subgroupid"]."';";
				sqlLog($sqlString);
				$uresult = dbExecute($sqlString,true);
				if (!$uresult) { $Status = False; }
			}
		}
		dbFreeResult($result);
	}

	if ($Status) {
		$GLOBALS["tqBlock1"] = '[';
		$GLOBALS["tqBlock2"] = ']';
		$GLOBALS["tqCloseBlock"] = '/';
		$GLOBALS["tqSeparator"] = ',';
		$GLOBALS["eztbTags"] = 'ezcupg_tags';
		include_once('./admin/compile.php');

		if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the contents table',$GLOBALS["Titles"]["InstallLog"]); }
		//  Upgrade the contents table
		$sqlQuery = 'SELECT * FROM '.$DBPrefix.'contents;';
		if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
		$result = dbRetrieve($sqlQuery,true,0,0);
		while ($rs = dbFetch($result)) {
			if ($Status) {
				$sbody = $rs["body"];
				$steaser = $rs["teaser"];
				//	Strip obsolete [html] tags
				$sbody = str_replace('[html]','', $sbody);
				$sbody = str_replace('[/html]','', $sbody);
				$steaser = str_replace('[html]','', $steaser);
				$steaser = str_replace('[/html]','', $steaser);

				debug_msg('Article '.$rs["contentid"].':<BR>BODY=['.$sbody.']<BR>TEASER=['.$steaser.']',$GLOBALS["Titles"]["InstallLog"]);

				//	Generate pre-compile body and teaser content
				$cbody = dbStr(compile(trim('[html]'.$sbody.'[/html]'),'N','Y',$rs["leftright"],'Y'));
				$cteaser = dbStr(compile(trim('[html]'.$steaser.'[/html]'),'N','Y',$rs["leftright"],'Y'));
				$sbody = dbStr($sbody);
				$steaser = dbStr($steaser);
				//  Perform the update
				$sqlString = "UPDATE ezcupg_contents SET contentname=contentid, subgroupname='".$rs["subgroupid"]."', groupname='".$rs["groupid"]."', contentactive='".$rs["active"]."', language='".$baselanguage."', body='".$sbody."', teaser='".$steaser."', cbody='".$cbody."', cteaser='".$cteaser."', authorid='".$masteruser."' WHERE contentid='".$rs["contentid"]."';";
				sqlLog($sqlString);
				$uresult = dbExecute($sqlString,true);
				if (!$uresult) { $Status = False; }
			}
		}
		dbFreeResult($result);
	}

	if ($Status) {
		//  Update language settings if site isn't using the default 'en' language
		if ($baselanguage != 'en') {
			if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Upgrading the languages table',$GLOBALS["Titles"]["InstallLog"]); }
			$sqlString = "UPDATE ezcupg_languages SET enabled='Y' WHERE languagecode='".$baselanguage."';";
			sqlLog($sqlString);
			$uresult = dbExecute($sqlString,true);
			if (!$uresult) { $Status = False;
			} else {
				$sqlQuery = "SELECT * FROM ezcupg_tagcategories;";
				if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlQuery,$GLOBALS["Titles"]["InstallLog"]); }
				$tresult = dbRetrieve($sqlQuery,true,0,0);
				while ($trs = dbFetch($tresult)) {
					if ($Status) {
						$sqlString = "INSERT INTO ezcupg_tagcategories(catdesc, catname, language, authorid) VALUES('".dbStr($trs["catdesc"])."','".$trs["catname"]."','".$baselanguage."','".$masteruser."');";
						sqlLog($sqlString);
						$uresult = dbExecute($sqlString,true);
						if (!$uresult) { $Status = False; }
					}
				}
				dbFreeResult($tresult);
				if ($Status) {
					$sqlString = "SELECT * FROM ezcupg_usergroups;";
					if ($GLOBALS["Log"] == 'Y') { debug_msg($sqlString,$GLOBALS["Titles"]["InstallLog"]); }
					$tresult = dbRetrieve($sqlString,true,0,0);
					while ($trs = dbFetch($tresult)) {
						if ($Status) {
							$sqlString = "INSERT INTO ezcupg_usergroups(usergroupdesc, usergroupname, language, authorid) VALUES('".dbStr($trs["usergroupdesc"])."','".$trs["usergroupname"]."','".$baselanguage."','".$masteruser."');";
							sqlLog($sqlString);
							$uresult = dbExecute($sqlString,true);
							if (!$uresult) { $Status = False; }
						}
					}
					dbFreeResult($tresult);
				}
			}
		}
	}

	if ($Status) {
		//  Clear all sessions
		$sqlString = "DELETE FROM ezcupg_sessions;";
		sqlLog($sqlString);
		$uresult = dbExecute($sqlString,true);
		if (!$uresult) { $Status = False; }
	}
} // function upgrade_database()


function drop_old_tables($DBPrefix,&$Status)
{
	if ($GLOBALS["Log"] == 'Y') { debug_msg('****	Dropping old database tables',$GLOBALS["Titles"]["InstallLog"]); }

	$Status = True;
	$tables = $GLOBALS["dbConn"]->MetaTables();
	$num_tables = count($tables);
	$i = 0;
	while ($i < $num_tables) {
		if ($Status) {
			$tablename = $tables[$i];
			if ((substr($tablename,0,strlen($DBPrefix)) == $DBPrefix) && (substr($tablename,0,7) != 'ezcupg_')) {
				if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Dropping table '.$tablename,$GLOBALS["Titles"]["InstallLog"]); }
				$dsql = "DROP TABLE ".$tablename;
				sqlLog($dsql);
				$dresult = dbExecute($dsql,true);
				if (!$dresult) { $Status = False; }
			}
		}
		$i++;
	}
} // function drop_old_tables()


function rename_new_tables($DBPrefix,&$Status)
{
	if ($GLOBALS["Log"] == 'Y') { debug_msg('****	Renaming new database tables',$GLOBALS["Titles"]["InstallLog"]); }

	$Status = True;
	$tables = $GLOBALS["dbConn"]->MetaTables();
	$num_tables = count($tables);
	$i = 0;
	while ($i < $num_tables) {
		if ($Status) {
			$tablename = $tables[$i];
			if (substr($tablename,0,7) == 'ezcupg_') {
				$tableref = $DBPrefix.substr($tablename,7);
				if ($GLOBALS["Log"] == 'Y') { debug_msg('****		Renaming table '.$tablename.' to '.$tableref,$GLOBALS["Titles"]["InstallLog"]); }
				$rsql = "ALTER TABLE ".$tablename.' RENAME '.$tableref;
				sqlLog($rsql);
				$rresult = dbExecute($rsql,true);
				if (!$rresult) { $Status = False; }
			}
		}
		$i++;
	}
} // function rename_new_tables()


function write_config_file(&$Status)
{
	$Status = True;
	global $HTTP_POST_VARS;

	//  Write the config file
	$fp = fopen("./include/config.php", "wb");
	if ($fp) {
		fwrite($fp,'<?php'.chr(10).chr(10));
		fwrite($fp,'/***************************************************************************'.chr(10).chr(10));
		fwrite($fp,' config.php'.chr(10));
		fwrite($fp,' -----------'.chr(10));
		fwrite($fp,' copyright : (C) 2002-2003 The ezContents Development Team'.chr(10).chr(10));
		fwrite($fp,' ***************************************************************************/'.chr(10).chr(10));
		fwrite($fp,'/***************************************************************************'.chr(10));
		fwrite($fp,' The ezContents Development Team offers no warranties on this script.'.chr(10));
		fwrite($fp,' The owner/licensee of the script is solely responsible for any problems'.chr(10));
		fwrite($fp,' caused by installation of the script or use of the script.'.chr(10).chr(10));
		fwrite($fp,' All copyright notices regarding ezContents must remain intact on the'.chr(10));
		fwrite($fp,' scripts and in the HTML for the scripts.'.chr(10).chr(10));
		fwrite($fp,' For more info on ezContents,'.chr(10));
		fwrite($fp,' visit http://www.ezcontents.org/'.chr(10).chr(10));
		fwrite($fp,' ***************************************************************************/'.chr(10).chr(10));
		fwrite($fp,'/***************************************************************************'.chr(10));
		fwrite($fp,' *'.chr(10));
		fwrite($fp,' *	This program is free software; you can redistribute it and/or modify'.chr(10));
		fwrite($fp,' *	it under the terms of the License which can be found within the'.chr(10));
		fwrite($fp,' *	zipped package.'.chr(10));
		fwrite($fp,' *'.chr(10));
		fwrite($fp,' ***************************************************************************/'.chr(10).chr(10));
		fwrite($fp,'$GLOBALS["Version"]			= "Version 2.0.3";'.chr(10));
		fwrite($fp,'$GLOBALS["gsAdminStyle"]		= "white";'.chr(10).chr(10));
		fwrite($fp,'// Database Configuration'.chr(10));
		fwrite($fp,'$GLOBALS["dbPersistent"]		= "'.$HTTP_POST_VARS["DBPersistent"].'";			//	Persistent database connections'.chr(10));
		fwrite($fp,'								//		\'Y\'es or \'N\'o'.chr(10));
		fwrite($fp,'$GLOBALS["ezContentsDB"]		= "'.$HTTP_POST_VARS["DBType"].'";		//	Database server type'.chr(10));
		fwrite($fp,'$GLOBALS["ezContentsDBServer"]		= "'.$HTTP_POST_VARS["DBServer"].'";		//	IP Address of the database server'.chr(10));
		fwrite($fp,'$GLOBALS["ezContentsDBName"]		= "'.$HTTP_POST_VARS["DBName"].'";		//	Database name'.chr(10));
		fwrite($fp,'$GLOBALS["ezContentsDBLogin"]		= "'.$HTTP_POST_VARS["DBLogin"].'";		//	Database system login'.chr(10));
		fwrite($fp,'$GLOBALS["ezContentsDBPassword"]	= "'.$HTTP_POST_VARS["DBPassword"].'";			//	Database system password'.chr(10).chr(10).chr(10));
		fwrite($fp,'$GLOBALS["admin_home"]			= "admin/";		// admin directory'.chr(10));
		fwrite($fp,'$GLOBALS["language_home"]		= "languages/";		// language base directory'.chr(10));
		fwrite($fp,'$GLOBALS["image_home"]			= "contentimage/";	// user images'.chr(10));
		fwrite($fp,'$GLOBALS["downloads_home"]		= "downloads/";		// user downloads'.chr(10));
		fwrite($fp,'$GLOBALS["style_home"]			= "admin/styles/";	// Extra external style sheet'.chr(10));
		fwrite($fp,'$GLOBALS["font_home"]			= "admin/styles/fonts/";	// Extra fonts'.chr(10));
		fwrite($fp,'$GLOBALS["script_home"]			= "scripts/";		// external php script files'.chr(10));
		fwrite($fp,'$GLOBALS["icon_home"]			= "images/";		// ezContents internal icons'.chr(10));
		fwrite($fp,'$GLOBALS["modules_home"]		= "modules/";		// add-in modules base directory'.chr(10));
		fwrite($fp,'$GLOBALS["backup_home"]			= "backup/";		// ezContents database backup directory'.chr(10));
		fwrite($fp,'$GLOBALS["include_home"]		= "include/";		// include file base directory'.chr(10));
		fwrite($fp,'$GLOBALS["sites_home"]			= "sites/";		// multi-site base directory'.chr(10));
		fwrite($fp,'$GLOBALS["themes_home"]			= "themes/";		// multi-theme base directory'.chr(10).chr(10).chr(10));
		fwrite($fp,'// ezContents Table Names'.chr(10));
		fwrite($fp,'$GLOBALS["eztbPrefix"]			= \''.$HTTP_POST_VARS["DBPrefix"].'\';'.chr(10));
		fwrite($fp,'$GLOBALS["eztbMasterPrefix"]		= $GLOBALS["eztbPrefix"];'.chr(10));
		fwrite($fp,'$GLOBALS["eztbSessions"]		= $GLOBALS["eztbMasterPrefix"]."sessions";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbSites"]			= $GLOBALS["eztbMasterPrefix"]."sites";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbVisitorstats"]		= $GLOBALS["eztbMasterPrefix"]."visitorstats";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbFunctiongroups"]		= $GLOBALS["eztbMasterPrefix"]."functiongroups";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbFunctions"]		= $GLOBALS["eztbMasterPrefix"]."functions";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbUsergroups"]		= $GLOBALS["eztbMasterPrefix"]."usergroups";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbPrivileges"]		= $GLOBALS["eztbMasterPrefix"]."userprivileges";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbCountries"]		= $GLOBALS["eztbMasterPrefix"]."countries";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbContinents"]		= $GLOBALS["eztbMasterPrefix"]."continents";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbLanguages"]		= $GLOBALS["eztbMasterPrefix"]."languages";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbModules"]			= $GLOBALS["eztbMasterPrefix"]."modules";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbAuthors"]			= $GLOBALS["eztbMasterPrefix"]."authors";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbThemes"]			= $GLOBALS["eztbMasterPrefix"]."themes";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbSettings"]		= $GLOBALS["eztbMasterPrefix"]."settings";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbUserdata"]		= $GLOBALS["eztbMasterPrefix"]."userdata";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbBanners"]			= $GLOBALS["eztbMasterPrefix"]."banners";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbTopgroups"]		= $GLOBALS["eztbMasterPrefix"]."topgroups";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbGroups"]			= $GLOBALS["eztbMasterPrefix"]."groups";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbSubgroups"]		= $GLOBALS["eztbMasterPrefix"]."subgroups";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbTagCategories"]		= $GLOBALS["eztbMasterPrefix"]."tagcategories";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbTags"]			= $GLOBALS["eztbMasterPrefix"]."tags";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbSidebartemplates"]	= $GLOBALS["eztbMasterPrefix"]."sidebartemplates";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbImageformattemplates"]	= $GLOBALS["eztbMasterPrefix"]."imageformattemplates";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbContents"]		= $GLOBALS["eztbMasterPrefix"]."contents";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbRatings"]			= $GLOBALS["eztbMasterPrefix"]."ratings";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbSpecialcontents"]		= $GLOBALS["eztbMasterPrefix"]."specialcontents";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbModuleSettings"]		= $GLOBALS["eztbMasterPrefix"]."modulesettings";'.chr(10));
		fwrite($fp,'$GLOBALS["eztbFiletypes"]		= $GLOBALS["eztbMasterPrefix"]."filetypes";'.chr(10).chr(10).chr(10));
		fwrite($fp,'// Other Configuration Variables'.chr(10));
		fwrite($fp,'$GLOBALS["RECORDS_PER_PAGE"]		= 8;			// number of lines of content on admin list pages'.chr(10));
		fwrite($fp,'// Tag block controls'.chr(10));
		fwrite($fp,'$GLOBALS["tqBlock"]			= \'[]\';'.chr(10));
		fwrite($fp,'$GLOBALS["tqBlock1"]			= substr($GLOBALS["tqBlock"], 0, 1);'.chr(10));
		fwrite($fp,'$GLOBALS["tqBlock2"]			= substr($GLOBALS["tqBlock"], -1, 1);'.chr(10));
		fwrite($fp,'$GLOBALS["tqCloseBlock"]		= \'/\';'.chr(10));
		fwrite($fp,'$GLOBALS["tqSeparator"]			= \',\';'.chr(10).chr(10));
		fwrite($fp,'$GLOBALS["locale"]			= \'\';			// Unix locale code if not using the machine default'.chr(10));
		fwrite($fp,'											// value'.chr(10).chr(10));
		fwrite($fp,'$GLOBALS["ShowFilePermissions"]		= \'N\';'.chr(10));
		fwrite($fp,'$GLOBALS["uploadmethod"]			= \'http:\';				// Valid values are \'http:\' and \'ftp:\''.chr(10));
		fwrite($fp,'$GLOBALS["ftp"]["server"]	= \'localhost\';'.chr(10));
		fwrite($fp,'$GLOBALS["ftp"]["port"]		= 21;'.chr(10));
		fwrite($fp,'$GLOBALS["ftp"]["username"]	= \'anonymous\';'.chr(10));
		fwrite($fp,'$GLOBALS["ftp"]["password"]	= \'secret password\';'.chr(10));
		fwrite($fp,'$GLOBALS["ftp"]["ezContents_root"]	= \'/ezc203\';'.chr(10).chr(10).chr(10));
		fwrite($fp,'$imagedir = "/".$GLOBALS["image_home"];'.chr(10));
		fwrite($fp,'$imageurl = "/".$GLOBALS["image_home"];'.chr(10));
		fwrite($fp,'$scriptdir = "/include/htmlarea2Modified/popups/";'.chr(10));
		fwrite($fp,'$scripturl = "/include/htmlarea2Modified/popups/";'.chr(10).chr(10).chr(10));
		fwrite($fp,'$GLOBALS["bDebug"] = False;'.chr(10).chr(10));
		fwrite($fp,'if ($GLOBALS["bDebug"]) { error_reporting( E_ALL & ~ E_NOTICE ); }'.chr(10));
		fwrite($fp,'else { error_reporting( E_ERROR | E_PARSE ); }'.chr(10).chr(10));
		fwrite($fp,'?>'.chr(10));
		fclose($fp);
		if ($GLOBALS["OS"] == "Windows") { chmod("./include/config.php", 666); } else { chmod("./include/config.php", 0666); }
	} else { $Status = False; }

	if (!$Status) { install_message('red','Failed writing the configuration file.'); }
} // function write_config_file()


function write_htaccess_files(&$Status)
{
	global $HTTP_SERVER_VARS;

	$Status = True;
	// .htaccess files are only written for Apache
	if (strpos($HTTP_SERVER_VARS["SERVER_SOFTWARE"], 'Apache') !== FALSE) {
		$dir_array = explode('/',$HTTP_SERVER_VARS["REQUEST_URI"]);
		$discard = array_pop($dir_array);
		$rewritebase = implode('/',$dir_array).'/';
		//  Write the single site .htaccess file
		$fp = fopen("./singlesite.htaccess", "wb");
		if ($fp) {
			fwrite($fp,'#  Options +FollowSymlinks'.chr(10));
			fwrite($fp,'RewriteEngine on'.chr(10));
			fwrite($fp,'RewriteBase '.$rewritebase.chr(10));
			fwrite($fp,'RewriteCond %{REQUEST_URI} /ezc/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)$'.chr(10));
			fwrite($fp,'RewriteRule ^(.*) vscms.php?p1=%1&p2=%2&p3=%3&p4=%4 [L]'.chr(10));
			fwrite($fp,'RewriteCond %{REQUEST_URI} /ezc/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)$'.chr(10));
			fwrite($fp,'RewriteRule ^(.*) vscms.php?p1=%1&p2=%2&p3=%3 [L]'.chr(10));
			fwrite($fp,'RewriteCond %{REQUEST_URI} /ezc/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)$'.chr(10));
			fwrite($fp,'RewriteRule ^(.*) vscms.php?p1=%1&p2=%2 [L]'.chr(10));
			fwrite($fp,'RewriteCond %{REQUEST_URI} /ezc/([A-Za-z0-9_]*)$'.chr(10));
			fwrite($fp,'RewriteRule ^(.*) vscms.php?p1=%1 [L]'.chr(10));
			fwrite($fp,'RewriteCond %{REQUEST_URI} /ezc$'.chr(10));
			fwrite($fp,'RewriteRule ^(.*) index.php'.chr(10));
			fclose($fp);
			if ($GLOBALS["OS"] == "Windows") { chmod("./singlesite.htaccess", 666); } else { chmod("./singlesite.htaccess", 0666); }
		} else { $Status = False; }

		if ($Status) {
			//  Write the multi-site .htaccess file
			$fp = fopen("./multisite.htaccess", "wb");
			if ($fp) {
				fwrite($fp,'#  Options +FollowSymlinks'.chr(10));
				fwrite($fp,'RewriteEngine on'.chr(10));
				fwrite($fp,'RewriteBase '.$rewritebase.chr(10));
				fwrite($fp,'RewriteCond %{REQUEST_URI} /ezc/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)$'.chr(10));
				fwrite($fp,'RewriteRule ^(.*) vscms.php?Site=%1&p1=%2&p2=%3&p3=%4 [L]'.chr(10));
				fwrite($fp,'RewriteCond %{REQUEST_URI} /ezc/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)$'.chr(10));
				fwrite($fp,'RewriteRule ^(.*) vscms.php?Site=%1&p1=%2&p2=%3 [L]'.chr(10));
				fwrite($fp,'RewriteCond %{REQUEST_URI} /ezc/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)$'.chr(10));
				fwrite($fp,'RewriteRule ^(.*) vscms.php?Site=%1&p1=%2 [L]'.chr(10));
				fwrite($fp,'RewriteCond %{REQUEST_URI} /ezc/([A-Za-z0-9_]*)$'.chr(10));
				fwrite($fp,'RewriteRule ^(.*) vscms.php?Site=%1 [L]'.chr(10));
				fwrite($fp,'RewriteCond %{REQUEST_URI} /ezc$'.chr(10));
				fwrite($fp,'RewriteRule ^(.*) index.php'.chr(10));
				fclose($fp);
				if ($GLOBALS["OS"] == "Windows") { chmod("./multisite.htaccess", 666); } else { chmod("./multisite.htaccess", 0666); }
			} else { $Status = False; }
		}
	}

	if (!$Status) { install_message('red','Failed writing the .htaccess files.'); }
} // function write_htaccess_files()




function install_header($title,$width,$height)
{
	?>
	<html>
	<head>
		<title><?php echo $GLOBALS["Titles"][$title]; ?></title>
		<style>
			.ip_text
			{
				border:solid 1px;
				font-family:verdana;
				font-size:8pt;
				letter-spacing:-0.5pt
			}
			.help_text
			{
				border:none;
				border-color:white;
				font-family:verdana;
				font-size:8pt;
				letter-spacing:-0.5pt;
				background-color:darkslateblue;
				color:yellow;
				overflow:hidden;
				text-decoration:None
			}
		</style>
	</head>
	<body text="black" bgcolor="slategray" link="white" vlink="white" alink="white">
	<br />

	<center>
	<table border="1" bgcolor="darkslateblue" cellspacing="0" cellpadding="0" height="<?php echo $height; ?>" width="<?php echo $width; ?>">
		<tr><td align="center" valign="top">
	<?php
} // function install_header(


function mouseover($text,$helptext,$returntext)
{
	$ref = '<a href="#" style="text-decoration:none" onMouseOver="window.document.helpform.helptext.value=\''.str_replace('\'','\\\'',str_replace(chr(10),'\n\r',$GLOBALS["Help"][$helptext])).'\';" onMouseOut="window.document.helpform.helptext.value=\''.str_replace('\'','\\\'',str_replace(chr(10),'\n\r',$GLOBALS["Help"][$returntext])).'\';">';
	return $ref.$text.'</a>';
} // function mouseover()


function help_screen($width,$colwidth,$text)
{
	?>
			</td>
		</tr>
		<tr><td valign="center" align="center">
	<form name="helpform" enctype="multipart/form-data">
	<table border="0" bgcolor="darkslateblue" cellspacing="0" cellpadding="0" height="50" width="<?php echo $width; ?>">
		<tr><td align="center" valign="top">
				<textarea cols="<?php echo $colwidth; ?>" rows="7" id="helptext" name="helptext" wrap='soft' class="help_text" readonly>
<?php echo $text; ?>
				</textarea>
			</td>
		</tr>
	</table>
	</form>
	<?php
} // function help_screen()


function install_footer()
{
	?>
			</td>
		</tr>
	</table>
	</center>

	</body>
	</html>
	<?php
} // function install_footer()


function blocktitle($title)
{
	?>
	<p><font face="Times New Roman" color="paleturquoise" size="+2"><b><?php echo $GLOBALS["Titles"][$title] ?></b></font></p>
	<?php
} // function blocktitle(


function blocktext($text,$colour='white')
{
	?>
	<p><font face="Times New Roman" color="<?php echo $colour; ?>" size="-1"><?php echo $text; ?></font></p>
	<?php
} // function blocktext()

function basetext($text,$colour='white')
{
	?>
	<font face="Times New Roman" color="<?php echo $colour; ?>" size="-1"><?php echo $text; ?></font>
	<?php
} // function blocktext()


function test_languages_1()
{
	global $HTTP_POST_VARS;

	$languagecount = 0;
	$savedir = getcwd();
	chdir('./languages');
	if ($handle = @opendir('.')) {
		while ($filename = readdir($handle)) {
			if ((is_dir($filename)) && (!($filename == '..') && !($filename == '.') && !($filename == 'CVS'))) {
				if ($HTTP_POST_VARS[$filename] == 'Y') { $languagecount++; }
			}
		}
		closedir($handle);
	}
	chdir($savedir);
	return $languagecount;
} // function test_languages_1()


function test_languages_2($language)
{
	global $HTTP_POST_VARS;

	$languagecount = 0;
	$savedir = getcwd();
	chdir('./languages');
	if ($handle = @opendir('.')) {
		while ($filename = readdir($handle)) {
			if ((is_dir($filename)) && (!($filename == '..') && !($filename == '.') && !($filename == 'CVS'))) {
				if ($HTTP_POST_VARS[$filename] == 'Y') {
					if ($filename == $language) { $languagecount++; }
				}
			}
		}
		closedir($handle);
	}
	chdir($savedir);
	return $languagecount;
} // function test_languages_2()


function testOpenCloseTag($tag,&$nCurrent,&$nStartgroup,&$nEndgroup,$teststring)
{
	$nStartgroup = strpos($teststring, $GLOBALS["tqBlock1"].$tag.$GLOBALS["tqBlock2"], $nCurrent);
	if ($nStartgroup === False) { $nCurrent = -1;
	} else {
		$nEndgroup = strpos($teststring, $GLOBALS["tqBlock1"].$GLOBALS["tqCloseBlock"].$tag.$GLOBALS["tqBlock2"], $nStartgroup);
		if (($nEndgroup === False) || ($nEndgroup < $nStartgroup)) { $nEndgroup = strlen($teststring) - 1; }
		$nCurrent = $nEndgroup + 1;
	}
}  // function testOpenCloseTag()

?>
