<?php
/**
  * BLOG:CMS: PHP/MySQL Personal Content Management System (CMS)
  * http://blogcms.com/
  * ----------------------------------------------------------------
  *
  * Copyright (C) 2003-2005 Radek HULÁN
  * http://hulan.cz/contact/
  *
  * Based on: 
  * ----------------------------------------------------------------
  * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/) 
  * Copyright (C) 2002-2003 The Nucleus Group
  *
  * ----------------------------------------------------------------
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
  * as published by the Free Software Foundation; either version 2
  * of the License, or (at your option) any later version.
**/

	// don't give warnings for uninitialized vars
	error_reporting(E_ERROR | E_PARSE);

	// make sure there's no unnecessary escaping:
	set_magic_quotes_runtime(0);

	/****************************************
	 Fix for IIS, which doesn't set REQUEST_URI
	****************************************/
	if ( !isset( $_SERVER['REQUEST_URI'] ) ) {
		$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
		if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) {
			$_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
		}
	}

	/****************************************
  	Fix for PHP as CGI hosts that set 
  	SCRIPT_FILENAME to something ending in php.cgi 
  	for all requests
	****************************************/
	if ( strpos($_SERVER['SCRIPT_FILENAME'], 'php.cgi') == strlen($_SERVER['SCRIPT_FILENAME']) - 7 )
		$_SERVER['SCRIPT_FILENAME'] = $_SERVER['PATH_TRANSLATED'];

	/****************************************
	 Fix for Dreamhost and other PHP as CGI hosts
	****************************************/
	if ( strstr( $_SERVER['SCRIPT_NAME'], 'php.cgi' ) )
		unset($_SERVER['PATH_INFO']);

	// postvars
	if (phpversion() >= '4.1.0')
		  include_once('admin/libs/vars4.1.0.php');
	else
		  include_once('admin/libs/vars4.0.6.php');

    // include DB layer
	include_once('admin/libs/db.php');

	if (postVar('action') == 'go')
		doInstall();
	else
		showInstallForm();
	exit;

	function showInstallForm() {
	doCheckFiles();
	?>
	<!DOCTYPE html
	PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	    <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
		<title>BLOG:CMS Install</title>
		<style type="text/css"><!--
			@import url('admin/documentation/styles/manual.css');
		--></style>
		<script type="text/javascript"><!--
			// function to make sure the submit button only gets pressed once
			var submitcount=0;
			function checkSubmit() {
				if (submitcount == 0) {
					submitcount++;
					return true;
				} else {
					return false;
				}
			}
		--></script>
	</head>
	<body>

  <div style='text-align:center;margin-top:20px'><img src='./admin/styles/blogcms.gif' /></div>

	<form method="post" action="install.php">

	<h1>Install BLOG:CMS v4.2.1</h1>
	<p>This script will help you to install BLOG:CMS. It will set up your database tables and provide you with the information you need to enter in <i>cfg.php</i>. In order to do all this, you need to enter some information.</p>
	<p>All fields are mandatory. Optional information can be set from the BLOG:CMS admin-area when installation is completed.</p>

	<h1>Prerequisites to successful installation</h1>
	<p>If you want BLOG:CMS to automatically update and create all configuration files, you'll <strong>need to make following files and directories writable first</strong>. You can do this by changing the file permissions to <strong>777</strong> (<a href="admin/documentation/tips.html#filepermissions">Quick guide on how to change file permissions</a>). </p>
	<pre>/ <em>(root directory in which this install.php is located)</em>
/media/1
/media/.cache
/forum
/forum/cache
/photo/data
/photo/data/users.csv.php
/photo/data/cache
/photo/data/logs
/photo/data/logs/views..log
/photo/data/logs/views.-Corvette.log
/photo/galleries
/wiki/conf/users.auth.php
/wiki/data
/wiki/data/changes.log
/wiki/data/attic
/wiki/data/cache
/wiki/data/locks
/wiki/data/media
/wiki/data/pages</pre>
<?php
	// tell people how they can have their config file filled out automatically
	if (@file_exists('cfg.php') && @!is_writable('cfg.php')) {
?>
	<h1>Automatic <i>cfg.php</i> Update</h1>
	<p>If you want BLOG:CMS to automatically update the <em>cfg.php</em> file, you'll need to make it writable. You can do this by changing the file permissions to <strong>666</strong>. After BLOG:CMS is successfully installed, you can change the permissions back to <strong>444</strong> (<a href="admin/documentation/tips.html#filepermissions">Quick guide on how to change file permissions</a>).</p>
	<p>If you choose not to make your file writable (or are unable to do so): don't worry. The installation process will provide you with the contents of the <em>cfg.php</em> file so you can upload it yourself.</p>

<?php } ?>

	<h1>Database type</h1>
	<fieldset>
	  <legend>General Database Settings</legend>
	  <table><tr>
	    <td>Database type used:</td>
		<td>
		  <select name="dbtype">
		  <option value="0" <?php if (!function_exists('mysqli_connect') && !function_exists('sqlite_query')) echo 'selected="selected"'; ?>>MySQL 4.0 (mysql)</option>
		  <option value="1" <?php if (function_exists('mysqli_connect')) echo 'selected="selected"'; ?>>MySQL 4.1/5.x (mysqli)</option>
		  <option value="2" <?php if (!function_exists('mysqli_connect') && function_exists('sqlite_query')) echo 'selected="selected"'; ?>>SQLite (bundled with PHP 5.0)</option>
		  </select>
		</tr></table>
	</fieldset>

	<h1>MySQL login data</h1>
	<p>Enter your MySQL data below. If you don't know this information, contact your system administrator for more info.</p>
	<fieldset>
		<legend>MySQL database settings</legend>
		<table><tr>
			<td>Hostname:</td>
			<td><input name="mySQL_host" value="localhost" /></td>
		</tr><tr>
			<td>Username:</td>
			<td><input name="mySQL_user" /></td>
		</tr><tr>
			<td>Password:</td>
			<td><input name="mySQL_password" type="password" /></td>
		</tr><tr>
			<td>Database:</td>
			<td><input name="mySQL_database" /> <input name="mySQL_create" value="1" type="checkbox" id="mySQL_create"> <label for="mySQL_create" />needs to be created</label></td>
		</tr></table>
	</fieldset>

	<h1>SQLite login data</h1>
	<fieldset>
		<legend>SQLite database settings</legend>
		<table><tr>
			<td>Database filename and <b>PATH</b>:</td>
			<td><input name="SQLite_db_name" size="60" value="<?php
			        $path = str_replace("install.php",'',serverVar('SCRIPT_FILENAME'));
					$path = str_replace("\\","/",$path);
					// add slash at end if necessary
					if (!endsWithSlash($path)) $path .= '/';
					if ($path) echo  $path;
					echo "sqlite.db";
				?>" /></td>
		</tr></table>
	</fieldset>

	<h1>Advanced settings</h1>
	<fieldset>
		<legend>Advanced Database Settings</legend>
		<table><tr>
			<td><input name="mySQL_usePrefix" value="1" type="checkbox" id="mySQL_usePrefix"> <label for="mySQL_usePrefix" />Use table prefix:</label></td>
			<td><input name="mySQL_tablePrefix" value="" /></td>
		</tr></table>
		<p>Unless you're installing multiple BLOG:CMS installations in one single database and know what you're doing, <strong>you really shouldn't change this</strong>. All database tables generated by BLOG:CMS will start with this prefix.</p>
	</fieldset>

	<h1>Directories and URLs</h1>
	<p>This install script has attempted to find out the directories and URLs in which BLOG:CMS is installed. Please check the values below and correct if necessary. The URLs and file paths should end with a slash.</p>

	<fieldset>
		<legend>URLs and directories</legend>
		<table><tr>
			<td>Site <strong>URL</strong>:</td>
			<td>
					<input name="IndexURL" size="60" value="<?php
					$url = "http://" . serverVar('HTTP_HOST') . serverVar('REQUEST_URI');
					$url = str_replace("install.php",'',$url);
					$url = str_replace("\\","/",$url);
					// add slash at end if necessary
					if (!endsWithSlash($url)) $url .= '/';
					echo $url;
				?>" />
			</td>
		</tr><tr>
			<td>Admin-area <strong>URL</strong>:</td>
			<td><input name="AdminURL" size="60" value="<?php
			        if ($url) echo $url . 'admin/';
				?>" />
			</td>
		</tr><tr>
			<td>Admin-area <strong>path</strong>:</td>
			<td><input name="AdminPath" size="60" value="<?php
			        $path = str_replace("install.php",'',serverVar('SCRIPT_FILENAME'));
					$path = str_replace("\\","/",$path);
					// add slash at end if necessary
					if (!endsWithSlash($path)) $path .= '/';
					if($path) echo  $path . 'admin/';
				?>" />
			</td>
		</tr><tr>
			<td>Media files <strong>URL</strong>:</td>
			<td><input name="MediaURL" size="60" value="<?php					if ($url) echo $url . 'media/';
				?>" />
			</td>
		</tr><tr>
			<td>Media directory <strong>path</strong>:</td>
			<td><input name="MediaPath" size="60" value="<?php					$path = str_replace("install.php",'',serverVar('SCRIPT_FILENAME'));
					$path = str_replace("\\","/",$path);
					// add slash at end if necessary
					if (!endsWithSlash($path)) $path .= '/';
					if ($path) echo $path . 'media/';
				?>" />
			</td>
		</tr><tr>
			<td>Extra skin files <strong>URL</strong>:</td>
			<td><input name="SkinsURL" size="60" value="<?php					if ($url) echo $url . 'skins/';
				?>" />
				<br />(used by imported skins)
			</td>
		</tr><tr>
			<td>Extra skin files directory <strong>path</strong>:</td>
			<td><input name="SkinsPath" size="60" value="<?php				$path = str_replace("install.php",'',serverVar('SCRIPT_FILENAME'));
				$path = str_replace("\\","/",$path);
				// add slash at end if necessary
				if (!endsWithSlash($path)) $path .= '/';
				if ($path) echo $path . 'skins/';
				?>" />
				<br />(this is where imported skins can place their extra files)
			</td>
		</tr><tr>
			<td>Plugin files <strong>URL</strong>:</td>
			<td><input name="PluginURL" size="60" value="<?php					if ($url) echo $url . 'admin/plugins/';
				?>" />
			</td>
		</tr><tr>
			<td>Action <strong>URL</strong>:</td>
			<td><input name="ActionURL" size="60" value="<?php					if ($url) echo $url . 'action.php';
				?>" />
				<br />(absolute location of the <tt>action.php</tt> file)
			</td>
		</tr></table>
	</fieldset>

	<p class="note">
	<strong>Note:</strong> <strong>Use absolute paths</strong> instead of relative paths. Usually, an absolute path will start with something like <tt>/home/username/public_html/</tt>. On Unix systems (most servers), paths should start with a slash. If you have trouble filling out this information, you should ask your administrator what to fill out.
	</p>

	<h1>Administrator User</h1>

	<p>Below, you need to enter some information to create the first user of your site.</p>

	<fieldset>
		<legend>Administrator User</legend>
		<table><tr>
			<td>Display Name:</td>
			<td>
				<input name="User_name" value="" />
				<small>(allowed characters: a-z and 0-9, spaces allowed inside)</small>
			</td>
		</tr><tr>
			<td>Real Name:</td>
			<td><input name="User_realname" value="" /></td>
		</tr><tr>
			<td>Password:</td>
			<td><input name="User_password" type="password" value="" /></td>
		</tr><tr>
			<td>Password Again:</td>
			<td><input name="User_password2" type="password" value="" /></td>
		</tr><tr>
			<td>E-mail Address:</td>
			<td>
				<input name="User_email" value="" />
				<small>(needs to be a valid e-mail address)</small>
			</td>
		</tr></table>
	</fieldset>

	<h1>Weblog data</h1>

	<p>Below, you need to enter some information to create a default weblog. The name of this weblog will also be used as name for your site</p>

	<fieldset>
		<legend>Weblog Data</legend>
		<table><tr>
			<td>Blog Name:</td>
			<td><input name="Blog_name" size="60" value="BLOG:CMS Weblog" /></td>
		</tr><tr>
			<td>Blog Short Name:</td>
			<td>
				<input name="Blog_shortname" value="myweblog" />
				<small>(allowed characters: a-z and 0-9, no spaces allowed)</small>
			</td>
		</tr></table>
	</fieldset>

	<h1>Submit</h1>

	<p>Verify the data above, and click the button below to set up your database tables and initial data. This can take a while, so have patience. <b>ONLY CLICK THE BUTTON ONCE !</b></p>

	<p>
		<input name="action" value="go" type="hidden" />
		<input type="submit" value="Install BLOG:CMS" onclick="return checkSubmit();" />
	</p>

	</form>

	</body>
	</html>


	<?php	}

	function tableName($unPrefixed)
	{
		global $mysql_usePrefix, $mysql_prefix;
		if ($mysql_usePrefix == 1)
			return $mysql_prefix . $unPrefixed;
		else
			return $unPrefixed;
	}

	function doInstall() {
		global $mysql_usePrefix, $mysql_prefix;

		// 0. put all POST-vars into vars
		$mysql_host 		= postVar('mySQL_host');
		$mysql_user 		= postVar('mySQL_user');
		$mysql_password 	= postVar('mySQL_password');
		$mysql_database 	= postVar('mySQL_database');
		$mysql_create 		= postVar('mySQL_create');
		$mysql_usePrefix	= postVar('mySQL_usePrefix');
		$mysql_prefix		= postVar('mySQL_tablePrefix');
		$mysql_dbtype       = postVar('dbtype');
		if (intval($mysql_dbtype)==2)
		  $mysql_database   = postVar('SQLite_db_name');
		$config_indexurl 	= postVar('IndexURL');
		$config_adminurl 	= postVar('AdminURL');
		$config_adminpath 	= postVar('AdminPath');
		$config_mediaurl 	= postVar('MediaURL');
		$config_skinsurl 	= postVar('SkinsURL');
		$config_pluginurl 	= postVar('PluginURL');
		$config_actionurl 	= postVar('ActionURL');
		$config_mediapath 	= postVar('MediaPath');
		$config_skinspath 	= postVar('SkinsPath');
		$user_name 			= postVar('User_name');
		$user_realname 		= postVar('User_realname');
		$user_password 		= postVar('User_password');
		$user_password2 	= postVar('User_password2');
		$user_email 		= postVar('User_email');
		$blog_name 			= postVar('Blog_name');
		$blog_shortname 	= postVar('Blog_shortname');
		$config_adminemail 	= $user_email;
		$config_sitename 	= $blog_name;


		$config_indexurl 	= str_replace("\\","/",$config_indexurl);
		$config_adminurl 	= str_replace("\\","/",$config_adminurl);
		$config_mediaurl 	= str_replace("\\","/",$config_mediaurl);
		$config_skinsurl 	= str_replace("\\","/",$config_skinsurl);
		$config_pluginurl 	= str_replace("\\","/",$config_pluginurl);
		$config_actionurl 	= str_replace("\\","/",$config_actionurl);
		$config_adminpath	= str_replace("\\","/",$config_adminpath);
		$config_skinspath	= str_replace("\\","/",$config_skinspath);

		// 1. check all the data
		$errors = array();

		if (!$mysql_database)
			array_push($errors,"mySQL database name missing");
		if (($mysql_usePrefix == 1) && (strlen($mysql_prefix) == 0))
			array_push($errors,"mySQL prefix was selected, but prefix is empty");
		if (($mysql_usePrefix == 1) && (!eregi('^[a-zA-Z0-9_]+$', $mysql_prefix)))
			array_push($errors,"mySQL prefix should only contain characters from the ranges A-Z, a-z, 0-9 or underscores");
		if (!endsWithSlash($config_indexurl) || !endsWithSlash($config_adminurl)
		     				     || !endsWithSlash($config_mediaurl)
		     				     || !endsWithSlash($config_pluginurl)
		     				     || !endsWithSlash($config_skinsurl)
								// TODO: add action.php check
		    )
			array_push($errors,"One of the URLs does not end with a slash, or action url does not end with 'action.php'");
		if (!endsWithSlash($config_adminpath))
			array_push($errors,"The path of the administration area does not end with a slash");
		if (!endsWithSlash($config_mediapath))
			array_push($errors,"The media path does not end with a slash");
		if (!endsWithSlash($config_skinspath))
			array_push($errors,"The skins path does not end with a slash");
		if (!is_dir($config_adminpath))
			array_push($errors,"The path of the administration area does not exist on your server");
		if (!_isValidMailAddress($user_email))
			array_push($errors,"Invalid e-mail address given for user");
		if (!_isValidDisplayName($user_name))
			array_push($errors,"User name is not a valid display name (allowed chars: a-zA-Z0-9 and spaces)");
		if (!$user_password || !$user_password2)
			array_push($errors, "User password is empty");
		if ($user_password != $user_password2)
			array_push($errors, "User password do not match");
		if (!_isValidShortName($blog_shortname))
			array_push($errors, "Invalid short name given for blog (allowed chars: a-z0-9, no spaces)");
		if (sizeof($errors) > 0)
			showErrorMessages($errors);

		// 2. try to log in to mySQL
		global $SQL_HOST, $SQL_USER, $SQL_PASSWORD, $SQL_DATABASE, $SQL_TYPE;
		$SQL_HOST = $mysql_host;
		$SQL_USER = $mysql_user;
		$SQL_PASSWORD = $mysql_password;
		$SQL_DATABASE = $mysql_database;
		$SQL_TYPE = $mysql_dbtype;
		// connect to MySQL, not SQLite
		if ($SQL_TYPE!=2) sql_connect(false);

		// 3. try to create database (if needed)
		if ($mysql_create == 1)  sql_create_db($mysql_database);

		// 4. try to select database
		sql_select_db($mysql_database);

		// 5. execute queries
		if ($SQL_TYPE!=2)
		  $filename = "install_mysql.sql";
		else
		  $filename = "install_sqlite.sql";
		$fd = fopen ($filename, "r");
		$queries = fread ($fd, filesize ($filename));
		fclose ($fd);
		@set_time_limit(1200);
		if ($SQL_TYPE==2)
		  $queries = preg_split("/\);\s*[\r|\n]/",$queries);
		else
		  $queries = preg_split("/\;\s*[\r|\n]/",$queries);
		for ($idx = 0;$idx<sizeof($queries);$idx++) {
			$query = trim($queries[$idx]);
			if (!empty($query)) {
				if ($SQL_TYPE==2) $query.=')';
				// echo "<p><small>".htmlspecialchars($query)."</small></p>";
				if ($mysql_usePrefix == 1) $query = str_replace('`nucleus_','`'.$mysql_prefix.'nucleus_', $query);
				sql_query($query) or _doError("Error while executing query (<small>" . htmlspecialchars($query) . "</small>): " . sql_error());
			}
		}

		// 6. update global settings
		updateConfig('IndexURL',	$config_indexurl);
		updateConfig('AdminURL',	$config_adminurl);
		updateConfig('MediaURL',	$config_mediaurl);
		updateConfig('SkinsURL',	$config_skinsurl);
		updateConfig('PluginURL',	$config_pluginurl);
		updateConfig('ActionURL',	$config_actionurl);
		updateConfig('AdminEmail',	$config_adminemail);
		updateConfig('SiteName',	htmlspecialchars($config_sitename));


		// 7. update GOD member
		$query =  'UPDATE ' . tableName('nucleus_member')
		       . " SET mname='" . addslashes($user_name) . "',"
		       . "     mrealname='". addslashes($user_realname) . "',"
		       . "     mpassword='". md5(addslashes($user_password)) . "',"
		       . "     murl='" . addslashes($config_indexurl) . "',"
		       . "     memail='" . addslashes($user_email) . "',"
		       . "     madmin=1,"
		       . "     mcanlogin=1"
		       . " WHERE mnumber=1";
		sql_query($query) or _doError("Error while setting member settings: " . sql_error());

		// 8. update weblog settings
		$query =  'UPDATE ' . tableName('nucleus_blog')
		       . " SET bname='" . addslashes(str_replace("'",'&#039;',htmlspecialchars($blog_name))) . "',"
		       . "     bshortname='". addslashes(htmlspecialchars($blog_shortname)) . "',"
		       . "     burl='" . addslashes($config_indexurl) . "',"
		       . "	   bnotify='". addslashes($user_email) . "'"
		       . " WHERE bnumber=1";
		sql_query($query) or _doError("Error while setting weblog settings: " . sql_error());

		// 9. update item and comments date
		$query =  'UPDATE ' . tableName('nucleus_item')
			. " SET itime='". date("Y-m-d H:i:s",time()) ."'"
			. " WHERE inumber=1";
		sql_query($query) or _doError("Error with query: " . sql_error());
		$query =  'UPDATE ' . tableName('nucleus_comment')
			. " SET ctime='". date("Y-m-d H:i:s",time()) ."'"
			. " WHERE citem=1";
		sql_query($query) or _doError("Error with query: " . sql_error());

		// 10. install custom plugins 
		global $aPlugErrors;
		$aPlugErrors = array();
		
		global $SQL_HOST, $SQL_USER, $SQL_PASSWORD, $SQL_DATABASE, $SQL_PREFIX, $SQL_TYPE;
		$SQL_HOST = $mysql_host;
		$SQL_USER = $mysql_user;
		$SQL_PASSWORD = $mysql_password;
		$SQL_DATABASE = $mysql_database;
		$SQL_TYPE = $mysql_dbtype;
		$SQL_PREFIX = ($mysql_usePrefix == 1)?$mysql_prefix:'';
		
		global $DIR_ADMIN, $DIR_MEDIA, $DIR_SKINS, $DIR_PLUGINS, $DIR_LANG, $DIR_LIBS;
		$DIR_ADMIN = $config_adminpath;
		$DIR_MEDIA = $config_mediapath;
		$DIR_SKINS = $config_skinspath;
		$DIR_PLUGINS = $DIR_ADMIN . 'plugins/';
		$DIR_LANG = $DIR_ADMIN . 'language/';
		$DIR_LIBS = $DIR_ADMIN . 'libs/';

		// close database connection (needs to be closed if we want to include globalfunctions.php)
		sql_close();

		include_once($DIR_LIBS . 'globalfunctions.php');

		// 11. install plugins
		// array with names of plugins to install. Plugin files must be present in the admin/plugin/ directory.
		global $aConfPlugsToInstall;
		$aConfPlugsToInstall = array(
				'NP_Captcha',
				'NP_CommentPreview',
				'NP_CommentControl',
				'NP_FancyText',
				'NP_BlogWithOffset',
				'NP_Calendar',
				'NP_Contact',
				'NP_CSS',
				'NP_CSSAdmin',
				'NP_ExtraSkin',
				'NP_FancierURL',
				'NP_HeaderNavigation',
				'NP_LatestComments',
				'NP_LatestDisc',
				'NP_LatestItems',
				'NP_MailToAFriend',
				'NP_MostKarma',
				'NP_MostPopular',
				'NP_MostViewed',
				'NP_OffsetArticles',
				'NP_OffsetEntriesLink',
				'NP_PageLinkList',
				'NP_PDF',
				'NP_Poll',
				'NP_Print',
				'NP_Random',
				'NP_Referrer',
				'NP_Related',
				'NP_XMLSupport',
				'NP_RSSAtom',
				'NP_RSSAtomAggregator',
				'NP_RSSBlog',
				'NP_RSSItem',
				'NP_Signature',
				'NP_SkinFiles',
				'NP_SubCategories',
				'NP_Table',
				'NP_TrackBack',
				'NP_Viewed',
				'NP_WYSIWYG',
				'NP_XMLTools');
		$aPlugErrors = installCustomPlugs($manager);
		
		// 12. Write config file ourselves (if possible)
		$bConfigWritten = 0;
		if ($fp = @fopen('cfg.php', 'w')) {
			$config_data = "<" . "?php \n";
			$config_data .= "\n";
			$config_data .= '	global $SQL_HOST,$SQL_USER,$SQL_PASSWORD,$SQL_DATABASE,$SQL_TYPE,$SQL_PREFIX;'."\n";
			$config_data .= '	global $DIR_ADMIN,$DIR_MEDIA,$DIR_SKINS,$DIR_PLUGINS,$DIR_LANG,$DIR_LIBS;'."\n";
			$config_data .= "\n";
			$config_data .= "	// MySQL/SQLite connection information\n";
			if (intval($SQL_TYPE)!=2) {
				$config_data .= "	\$SQL_HOST = '" . $mysql_host . "';\n";
				$config_data .= "	\$SQL_USER = '" . $mysql_user . "';\n";
				$config_data .= "	\$SQL_PASSWORD = '" . $mysql_password . "';\n";
			}
			$config_data .= "	\$SQL_DATABASE = '" . $mysql_database . "';\n";
			$config_data .= "	/**\n";
			$config_data .= "	* \$SQL_TYPE=0: MySQL 4.0 (mysql)\n";
			$config_data .= "	* \$SQL_TYPE=1: MySQL 4.1 (mysqli)\n";
			$config_data .= "	* \$SQL_TYPE=2: SQLite 2.8\n";
			$config_data .= "	*/\n";
			$config_data .= "	\$SQL_TYPE = $SQL_TYPE;\n";
			$config_data .= "	\$SQL_PREFIX = '" . (($mysql_usePrefix == 1)?$mysql_prefix:'') . "';\n";
			$config_data .= "\n";
			$config_data .= "	// main BLOG:CMS directory\n";
			$config_data .= "	\$DIR_ADMIN = '" . $config_adminpath . "';\n";
			$config_data .= "\n";
			$config_data .= "	// path to media dir\n";
			$config_data .= "	\$DIR_MEDIA = '" . $config_mediapath . "';\n";
			$config_data .= "\n";
			$config_data .= "	// extra skin files for imported skins\n";
			$config_data .= "	\$DIR_SKINS = '" . $config_skinspath . "';\n";
			$config_data .= "\n";
			$config_data .= "	// these dirs are normally sub dirs of the BLOG:CMS dir, but \n";
			$config_data .= "	// you can redefine them if you wish\n";
			$config_data .= "	\$DIR_PLUGINS = \$DIR_ADMIN . 'plugins/';\n";
			$config_data .= "	\$DIR_LANG = \$DIR_ADMIN . 'language/';\n";
			$config_data .= "	\$DIR_LIBS = \$DIR_ADMIN . 'libs/';\n";
			$config_data .= "\n";
			$config_data .= "	// include libs\n";
			$config_data .= "	include(\$DIR_LIBS.'globalfunctions.php');\n";
			$config_data .= "?" . ">";

			$result = @fputs($fp, $config_data, strlen($config_data));
			fclose($fp);

			if ($result) {
				// try to set permissions
				$path_array = explode('/',$config_adminpath);
				array_pop($path_array);
				array_pop($path_array);
				$path = implode('/',$path_array);
				$arr = array(
					'/media/1',
					'/media/.cache',
					'/forum',
					'/forum/cache',
					'/photo/data',
					'/photo/data/users.csv.php',
					'/photo/data/cache',
					'/photo/data/logs',
					'/photo/data/logs/views..log',
					'/photo/data/logs/views.-Corvette.log',
					'/photo/galleries',
					'/wiki/data/changes.log',
					'/wiki/conf/users.auth.php',
					'/wiki/data',
					'/wiki/data/attic',
					'/wiki/data/cache',
					'/wiki/data/locks',
					'/wiki/data/meta',
					'/wiki/data/pages',
					'/wiki/data/media'
					);
				foreach ($arr as $file) 
					if (@file_exists($path.$file)) @chmod($path.$file,0777); 
				
				// try to write photo gallery admin user
				$file=$path.'/photo/data/users.csv.php';
				if ( @file_exists($file) && ($fp = @fopen($file, 'w')) ) {
					@chmod($file,0777);
					if ($fp = @fopen($file, 'w')) {
						$data = '<'.'?'.'php die("Hacking attempt detected"); '.'?'.'>username,md5(pass),permissions,group(s),email,name,description,stats,'."\n";
						$data.= $user_name.','.md5(addslashes($user_password)).',1024,"","","'.addslashes($user_realname).'","Default administrator account",""'."\n";
						$data.= 'guest,5f4dcc3b5aa765d61d8327deb882cf99,0,"","","Guest","Restricted use account for guests who do not have a user account",""'."\n";
						@fputs($fp, $data, strlen($data));
						fclose($fp);
					}
				}
				
				// try to write wiki admin user
				$file=$path.'/wiki/conf/users.auth.php';
				if ( @file_exists($file) && ($fp = @fopen($file, 'w')) ) {
					@chmod($file,0777);
					if ($fp = @fopen($file, 'w')) {
						$data = '#user:MD5password:Real Name:email:groups,comma,seperated'."\n";
						$data.= $user_name.":".md5($user_password).":".$user_realname.":".$user_email.":admin\n";
						@fputs($fp, $data, strlen($data));
						fclose($fp);
					}
				}

				// and redirect to forum installation
				$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
				$url = str_replace('install.php','',$url);
				header('Location: '.$url.'forum/install.php');
			}
		}

		?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
		    <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
			<title>BLOG:CMS Install</title>
			<style>
				@import url('admin/styles/manual.css');
			</style>
		</head>
		<body>
<?php
	$aAllErrors = $aPlugErrors;
	if (count($aAllErrors) > 0) {
		echo '<h1>Skin/Plugin Install errors</h1>';
		echo '<ul><li>'.implode('</li><li>', $aAllErrors).'</li></ul>';
	}

	if (!$bConfigWritten) { ?>
	<h1 style='text-align:center'>BLOG:CMS - Installation Almost Complete!</h1>
	<p>The database tables have been initialized successfully. What still needs to be done is to change the contents of <i>cfg.php</i>. Below is how it should look like:</p>

<pre>&lt;?php
	global $SQL_HOST,$SQL_USER,$SQL_PASSWORD,$SQL_DATABASE,$SQL_TYPE,$SQL_PREFIX;
	global $DIR_ADMIN,$DIR_MEDIA,$DIR_SKINS,$DIR_PLUGINS,$DIR_LANG,$DIR_LIBS;

	// database connection information
<?php if (intval($SQL_TYPE)!=2) { ?>	$SQL_HOST = '<b><?php echo $mysql_host?></b>';
	$SQL_USER = '<b><?php echo $mysql_user?></b>';
	$SQL_PASSWORD = '<i><b><?php echo $mysql_password?></b></i>';
<?php } ?>	$SQL_DATABASE = '<b><?php echo $mysql_database?></b>';
	$SQL_PREFIX = '<b><?php echo ($mysql_usePrefix == 1)?$mysql_prefix:''?></b>';
	$SQL_TYPE = <b><?php echo $SQL_TYPE?></b>;

	// main BLOG:CMS directory
	$DIR_ADMIN = '<b><?php echo $config_adminpath?></b>';

	// path to media dir
	$DIR_MEDIA = '<b><?php echo $config_mediapath?></b>';

	// extra skin files for imported skins
	$DIR_SKINS = '<b><?php echo $config_skinspath?></b>';

	// these dirs are normally sub dirs of the BLOG:CMS dir, but
	// you can redefine them if you wish
	$DIR_PLUGINS = $DIR_ADMIN . 'plugins/';
	$DIR_LANG = $DIR_ADMIN . 'language/';
	$DIR_LIBS = $DIR_ADMIN . 'libs/';

	// include libs
	include($DIR_LIBS.'globalfunctions.php');
?&gt;</pre>

			<p>After you changed the file on your computer, upload it to your web server using FTP. Make sure you use ASCII mode to send over the files.
			</p>

			<div class="note">
			<b>Note:</b> Make sure that you have no spaces at the beginning or end of the <i>cfg.php</i> file. These would cause errors to happen when performing certain actions.
			<br />
			Thus, the first character of cfg.php should be "&lt;", and the last character should be "&gt;".
			</div>

<?php } else { ?>


	<h1 style='text-align:center'>BLOG:CMS - Installation complete!</h1>

			<p>BLOG:CMS has been installed, and your <code>cfg.php</code> has been updated for you.</p>

			<p>Don't forget to change the permissions on <code>cfg.php</code> back to 444 for security (<a href="admin/documentation/tips.html#filepermissions">Quick guide on how to change file permissions</a>).</p>
<?php } ?>
			<h1>Delete your install files</h1>

			<p>Files you should delete from your web server:</p>

			<ul>
				<li><b>install_mysql.sql</b>: file containing MySQL table structures</li>
				<li><b>install_sqlite.sql</b>: file containing SQLite table structures</li>
				<li><b>install.php</b>: this file</li>
				<li><b>upgrade.php</b>: upgrade file</li>
				<li><b>upgrade.sql</b>: helper upgrade file</li>
			</ul>

			<p>If you don't delete these files, you won't be able to open the admin area</p>

			<h1>Visit your web site</h1>
			<p>
			Your web site is now almost ready to use!
			</p>

      <p style='border:2px solid #666666;background-color:#E8E8E8;padding:10px'>
				<a href="<?php echo $config_adminurl?>">Login to the admin area to configure your site</a>
      </p>
		</body>
		</html>
		<?php
	}

	// install all plugins
	function installCustomPlugs(&$manager) {
		global $aConfPlugsToInstall, $DIR_LIBS;

		$aErrors = array();
		if (count($aConfPlugsToInstall) == 0) return $aErrors;

		$query = sql_query('SELECT * FROM '.sql_table('plugin'));
		$numCurrent = sql_num_rows($query);
		foreach ($aConfPlugsToInstall as $plugName) {
			// do this before calling getPlugin (in case the plugin id is used there)
			sql_query('INSERT INTO '.sql_table('plugin').' (porder, pfile) VALUES ('.(++$numCurrent).',"'.sql_escape($plugName).'")');
			$_id = sql_insert_id();
			// get and install the plugin
			$plugin =& $manager->getPlugin($plugName);
			if (!$plugin) {
				sql_query('DELETE FROM ' . sql_table('plugin') . ' WHERE pfile=\''. sql_escape($plugName).'\'');
				$numCurrent--;
				array_push($aErrors, 'Unable to install plugin ' . $plugName);
				continue;
			}
			$plugin->plugid = $_id;
			$plugin->install();
		}

		// SYNC PLUGIN EVENT LIST
		sql_query('DELETE FROM '.sql_table('plugin_event'));
		$res = sql_query('SELECT pid, pfile FROM '.sql_table('plugin'));
		// loop over all installed plugins
		while($o = sql_fetch_object($res)) {
			$pid = $o->pid;
			$plug =& $manager->getPlugin($o->pfile);
			if ($plug) {
				$eventList = $plug->getEventList();
				foreach ($eventList as $eventName) sql_query('INSERT INTO '.sql_table('plugin_event').' (pid, event) VALUES ('.$pid.', \''.$eventName.'\')');
			}
		}

		return $aErrors;
	}

	// give an error if one or more BLOG:CMS are not accessible
	function doCheckFiles() {
		$missingfiles = array();

		if (!is_readable('install_mysql.sql'))
			array_push($missingfiles, "File <b>install_mysql.sql</b> is missing or not readable");
		if (!is_readable('install_sqlite.sql'))
			array_push($missingfiles, "File <b>install_sqlite.sql</b> is missing or not readable");
		if (!is_readable('index.php'))
			array_push($missingfiles, "File <b>index.php</b> is missing or not readable");
		if (!is_readable('action.php'))
			array_push($missingfiles, "File <b>action.php</b> is missing or not readable");
		if (!is_readable('admin/index.php'))
			array_push($missingfiles, "File <b>admin/index.php</b> is missing or not readable");
		if (!is_readable('admin/libs/globalfunctions.php'))
			array_push($missingfiles, "File <b>admin/libs/globalfunctions.php</b> is missing or not readable");
		if (!is_readable('admin/libs/ADMIN.php'))
			array_push($missingfiles, "File <b>admin/libs/ADMIN.php</b> is missing or not readable");
		if (!is_readable('admin/libs/BLOG.php'))
			array_push($missingfiles, "File <b>admin/libs/BLOG.php</b> is missing or not readable");
		if (!is_readable('admin/libs/COMMENT.php'))
			array_push($missingfiles, "File <b>admin/libs/COMMENT.php</b> is missing or not readable");
		if (!is_readable('admin/libs/COMMENTS.php'))
			array_push($missingfiles, "File <b>admin/libs/COMMENTS.php</b> is missing or not readable");
		if (!is_readable('admin/libs/ITEM.php'))
			array_push($missingfiles, "File <b>admin/libs/ITEM.php</b> is missing or not readable");
		if (!is_readable('admin/libs/MEMBER.php'))
			array_push($missingfiles, "File <b>admin/libs/MEMBER.php</b> is missing or not readable");
		if (!is_readable('admin/libs/SKIN.php'))
			array_push($missingfiles, "File <b>admin/libs/SKIN.php</b> is missing or not readable");
		if (!is_readable('admin/libs/TEMPLATE.php'))
			array_push($missingfiles, "File <b>admin/libs/TEMPLATE.php</b> is missing or not readable");
		if (!is_readable('admin/libs/MEDIA.php'))
			array_push($missingfiles, "File <b>admin/libs/MEDIA.php</b> is missing or not readable");
		if (!is_readable('admin/libs/ACTIONLOG.php'))
			array_push($missingfiles, "File <b>admin/libs/ACTIONLOG.php</b> is missing or not readable");
		if (!is_readable('admin/media.php'))
			array_push($missingfiles, "File <b>admin/media.php</b> is missing or not readable");
		if (sizeof($missingfiles) > 0)
			showErrorMessages($missingfiles);
	}

	function updateConfig($name, $val) {
		$name = addslashes($name);
		$val = trim(addslashes($val));
		$query = 'UPDATE ' . tableName('nucleus_config')
		       . " SET value='$val'"
		       . " WHERE name='$name'";
		sql_query($query);
		return sql_insert_id();
	}

	function endsWithSlash($s) {
		return (strrpos($s,'/') == strlen($s) - 1);
	}

	/**
	  * Checks if email address is valid
	  */
	function _isValidMailAddress($address) {
		if (preg_match("/^[a-zA-Z0-9\._-]+@+[A-Za-z0-9\._-]+\.+[A-Za-z]{2,4}$/", $address))
			return 1;
		else
			return 0;
	}

	// returns true if the given string is a valid shortname
	// (to check short blog names and nicknames)
	// logic: starts and ends with a non space, can contain spaces in between
	//        min 2 chars
	function _isValidShortName($name) {
		if (eregi("^[a-z0-9]+$", $name))
			return 1;
		else
			return 0;
	}

	// returns true if the given string is a valid display name
	// (to check nicknames)
	function _isValidDisplayName($name) {
		if (eregi("^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$", $name))
			return 1;
		else
			return 0;
	}

	function _doError($msg) {
		?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
		   <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
			<title>BLOG:CMS Install</title>
			<style>
				@import url('admin/styles/manual.css');
			</style>
		</head>
		<body>
		  <div style='text-align:center;margin-top:20px'><img src='./admin/styles/blogcms.gif' /></div>
			<h1>Error!</h1>
			<p>
			Error message was: "<?php echo $msg?>";
			</p>

			<p>
			<a href="install.php" onclick="history.back();return false;">Go Back</a>
			</p>
		</body>
		</html>
		<?php		exit;
	}

	function showErrorMessages($errors) {
		?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
			<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
			<title>BLOG:CMS Install</title>
			<style>
				@import url('admin/styles/manual.css');
			</style>
		</head>
		<body>
      <div style='text-align:center;margin-top:20px'><img src='./admin/styles/blogcms.gif' /></div>
			<h1>Errors!</h1>
			<p>
			Errors were found:
			</p>

			<ul>
			<?php	while($msg = array_shift($errors))
					echo "<li>$msg</li>";
			?>
			</ul>

			<p>
			<a href="install.php" onclick="history.back();return false;">Go Back</a>
			</p>
		</body>
		</html>
		<?php	exit;
	}
?>