<?php
// $Id: install.php,v 1.2 2004/10/13 11:53:46 Farsus Exp $
// -------------------------------------------------------------------------//
//			                 RUNCMS                                         //
//                                                                          //
//	 reliable - Unique - Nocost &  Simplicity & ease off use                //
//                       < http://www.runcms.org >                          //
// -------------------------------------------------------------------------//
// Original Author: Half-Dead
// Author Website : http://www.e-xoops.com
// License Type   : LGPL: See /manual/LICENSES/LGPL.txt
// ------------------------------------------------------------------------- //

ob_start();
include_once('include/functions.php');

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function welcome() {
global $HTTP_COOKIE_VARS;

$lang = $HTTP_COOKIE_VARS['lang'] ? $HTTP_COOKIE_VARS['lang'] : 'english';
?>

<div align="center">
<h4><?php printf(_INSTALL_W_WELCOME, XOOPS_VERSION);?></h4>
<?php readfile(WIZ_PATH.'/language/'.$lang.'/main.html');?>
</div>
<br />

<table align="center" width="70%"><tr>
<td align="center">
<?php echo _INSTALL_W_CHOOSELANG;?><br />
<form action="install.php" method="post"><select class="select" name="lang">

<?php
include_once("../class/xoopslists.php");
$langarr = XoopsLists::getDirListAsArray("./language/");
foreach ($langarr as $lang) {
	echo "<option value='".$lang."'>".$lang."</option>";
	}
?>

</select>
<input type="hidden" name="op" value="setupcheck" />
<input type="submit" class="button" value="<?php echo _NEXT;?>" />
</form></td>
</tr></table>

<?php
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function setup_check() {

$checks = array();
@chmod("../mainfile.php", 0666);

@is_writable("../mainfile.php") ? $checks[] = _INSTALL_ST_MAINFILE_OK : $checks[] = _INSTALL_ST_MAINFILE_BAD;
if ( !function_exists('mysql_get_client_info') ) {
	$checks[] = sprintf(_INSTALL_ST_MYSQL_BAD2);
	} else {
		version_check('3.23.0', mysql_get_client_info()) ? $checks[] = sprintf(_INSTALL_ST_MYSQL_OK, mysql_get_client_info()) : $checks[] = printf(_INSTALL_ST_MYSQL_BAD, mysql_get_client_info());
	}
ini_get('register_globals') ? $checks[] =  _INSTALL_ST_GLOBALS_OK : $checks[] =  _INSTALL_ST_GLOBALS_BAD;
version_check('4.11', phpversion()) ? $checks[] = sprintf(_INSTALL_ST_PHP_OK, phpversion()) : $checks[] = printf(_INSTALL_ST_PHP_BAD, phpversion());

echo "<table width='75%' align='center'><tr><td><h3>"._INSTALL_ST_TESTS."</h3></td>";

foreach ($checks as $value) {
	echo "<tr><td>$value</td></tr>";
}

echo "
<tr>
<td align='right'>
<a href='./include/php_info.php' target='_blank'>"._INSTALL_PHPINFO."</a> :: <img src='images/info.gif' />
</td>
</tr></table>
<form action='./install.php' method='post'>
<input type='hidden' name='op' value='dbform'>
<div align='center'>
"._INSTALL_ST_NEXT."
<input type='submit' class='button' name='submit' value='"._NEXT."'>
</div>
</form>";

}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function dbdata() {
global $HTTP_POST_VARS;

isset($HTTP_POST_VARS['root_path'])   ? $root_path   = $HTTP_POST_VARS['root_path']   : $root_path   = XOOPS_ROOT_PATH;
isset($HTTP_POST_VARS['xoops_url'])   ? $xoops_url   = $HTTP_POST_VARS['xoops_url']   : $xoops_url   = XOOPS_URL;

isset($HTTP_POST_VARS['dbhost'])      ? $dbhost      = $HTTP_POST_VARS['dbhost']      : $dbhost      = "localhost";
isset($HTTP_POST_VARS['dbpass'])      ? $dbpass      = $HTTP_POST_VARS['dbpass']      : $dbpass      = "";
isset($HTTP_POST_VARS['dbname'])      ? $dbname      = $HTTP_POST_VARS['dbname']      : $dbname      = "";
isset($HTTP_POST_VARS['prefix'])      ? $prefix      = $HTTP_POST_VARS['prefix']      : $prefix      = "runcms";
isset($HTTP_POST_VARS['dbuname'])     ? $dbuname     = $HTTP_POST_VARS['dbuname']     : $dbuname     = "root";
isset($HTTP_POST_VARS['database'])    ? $database    = $HTTP_POST_VARS['database']    : $database    = "mysql";
isset($HTTP_POST_VARS['db_pconnect']) ? $db_pconnect = $HTTP_POST_VARS['db_pconnect'] : $db_pconnect = 0;

include_once("../class/module.textsanitizer.php");

$myts = new MyTextSanitizer;

$root_path   = $myts->makeTboxData4PreviewInForm($root_path);
$xoops_url   = $myts->makeTboxData4PreviewInForm($xoops_url);

$dbhost      = $myts->makeTboxData4PreviewInForm($dbhost);
$dbpass      = $myts->makeTboxData4PreviewInForm($dbpass);
$dbname      = $myts->makeTboxData4PreviewInForm($dbname);
$prefix      = $myts->makeTboxData4PreviewInForm($prefix);
$dbuname     = $myts->makeTboxData4PreviewInForm($dbuname);
$database    = $myts->makeTboxData4PreviewInForm($database);
$db_pconnect = intval($db_pconnect);

include_once("../class/xoopsformloader.php");
include_once("./include/dbform.php");
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function dbconfirm() {
global $HTTP_POST_VARS;

include_once("../class/module.textsanitizer.php");

$myts = new MyTextSanitizer;

$error = array();

if ( empty($HTTP_POST_VARS['dbhost']) ) {
	$error[] = sprintf(_INSTALL_DF_PLEASE_ENTER, "<b>"._INSTALL_DF_HOST."</b>");
}

if ( empty($HTTP_POST_VARS['dbname']) ) {
	$error[] = sprintf(_INSTALL_DF_PLEASE_ENTER, "<b>"._INSTALL_DF_DBNAME."</b>");
}

if ( empty($HTTP_POST_VARS['prefix']) ) {
	$error[] = sprintf(_INSTALL_DF_PLEASE_ENTER, "<b>"._INSTALL_DF_PREFIX."</b>");
}

if ( empty($HTTP_POST_VARS['root_path']) || @!is_dir($HTTP_POST_VARS['root_path']) ) {
	$error[] = sprintf(_INSTALL_DF_PLEASE_ENTER, "<b>"._INSTALL_DF_PATH."</b>");
}

if ( !preg_match("/^http[s]?:\/\/+.{6}/i", $HTTP_POST_VARS['xoops_url']) ) {
	$error[] = sprintf(_INSTALL_DF_PLEASE_ENTER, "<b>"._INSTALL_DF_URL."</b>");
}

echo "<form action='./install.php' method='post'><table align='center'>";

if (!empty($error)) {
	echo "<tr><td><h4>"._INSTALL_DF_ERRORS."</h4></td></tr>";
	foreach ($error as $err) {
		echo "<tr><td><span style='color:#ff0000;'>".$err."</span></td></tr>";
	}

	$msg    = "&nbsp;";
	$op     = "dbform";
	$submit = _GOBACK;

	} else {
		if (@!is_dir($HTTP_POST_VARS['root_path'])) {
			$msg    = _INSTALL_DF_BADROOT;
			$op     = "dbform";
			$submit = _GOBACK;

			} elseif(!test_db()) {
				$msg    = _INSTALL_DF_BADDB;
				$op     = "dbform";
				$submit = _GOBACK;

				} else {
					$msg    = _INSTALL_DF_OK;
					$op     = "writemainfile";
					$submit = _NEXT;
				}
		}

echo "
<tr><td><h5>".$msg."</h5></td></tr>
<tr><td>
<input type='hidden' name='op' value='$op'>
<center><input type='submit' class='button' name='submit' value='".$submit."'>
</center><br></td></tr>
</table>
<input type='hidden' name='database' value='".$myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['database'])."' />
<input type='hidden' name='dbhost' value='".$myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['dbhost'])."' />
<input type='hidden' name='dbuname' value='".$myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['dbuname'])."' />
<input type='hidden' name='dbpass' value='".$myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['dbpass'])."' />
<input type='hidden' name='dbname' value='".$myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['dbname'])."' />
<input type='hidden' name='prefix' value='".$myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['prefix'])."' />
<input type='hidden' name='db_pconnect' value='".intval($HTTP_POST_VARS['db_pconnect'])."' />
<input type='hidden' name='root_path' value='".$myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['root_path'])."' />
<input type='hidden' name='xoops_url' value='".$myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['xoops_url'])."' />
</form>";
}


//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function test_db() {
global $HTTP_POST_VARS;

if ( !empty($HTTP_POST_VARS['prefix']) && !empty($HTTP_POST_VARS['dbname']) ) {
	include_once(XOOPS_ROOT_PATH . "/class/database/".$HTTP_POST_VARS['database'].".php");
	$db = new Database();
	$db->setPrefix($HTTP_POST_VARS['prefix']);
	$db->connect($HTTP_POST_VARS['dbhost'], $HTTP_POST_VARS['dbuname'], $HTTP_POST_VARS['dbpass']);
	if (!$db->select_db($HTTP_POST_VARS['dbname'])) {
		return $db->query("CREATE DATABASE ".$HTTP_POST_VARS['dbname']."");
	}
	return true;
	}
}
//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function write_mainfile() {
global $HTTP_POST_VARS, $HTTP_COOKIE_VARS;

include_once("../class/module.textsanitizer.php");

$myts = new MyTextSanitizer();

$base_url = $HTTP_POST_VARS['xoops_url'];
$base_url = str_replace('\\', '/', $base_url);
if ( substr($base_url, -1) == '/') {
	$base_url = substr($base_url, 0, -1);
}

$base_path = $HTTP_POST_VARS['root_path'];
$base_path = str_replace('\\', '/', $base_path);
if ( substr($base_path, -1) == '/') {
	$base_path = substr($base_path, 0, -1);
}

$language = !empty($HTTP_COOKIE_VARS['lang']) ? $HTTP_COOKIE_VARS['lang'] : 'english';

$content = '<?php
// ------------------------------------------------------------------------- //
//               E-Xoops: Content Management for the Masses                  //
//                       < http://www.e-xoops.com >                          //
// ------------------------------------------------------------------------- //

if ( !defined(\'XOOPS_MAINFILE_INCLUDED\') ) {
	define(\'XOOPS_MAINFILE_INCLUDED\', 1);

	// '._INSTALL_DF_PATH.'
	// '._INSTALL_DF_PATH1.'
	define(\'XOOPS_ROOT_PATH\', \''.$myts->oopsHtmlSpecialChars($myts->oopsAddSlashesGPC($base_path)).'\');

	// '._INSTALL_DF_URL.'
	// '._INSTALL_DF_URL1.'
	define(\'XOOPS_URL\', \''.$myts->oopsHtmlSpecialChars($myts->oopsAddSlashesGPC($base_url)).'\');

	// '._INSTALL_DF_DB.'
	// '._INSTALL_DF_DB1.'
	$xoopsConfig[\'database\'] = \''.$myts->oopsHtmlSpecialChars($myts->oopsAddSlashesGPC($HTTP_POST_VARS['database'])).'\';

	// '._INSTALL_DF_PREFIX.'
	// '._INSTALL_DF_PREFIX1.'
	$xoopsConfig[\'prefix\'] = \''.$myts->oopsHtmlSpecialChars($myts->oopsAddSlashesGPC($HTTP_POST_VARS['prefix'])).'\';

	// '._INSTALL_DF_HOST.'
	// '._INSTALL_DF_HOST1.'
	$xoopsConfig[\'dbhost\'] = \''.$myts->oopsHtmlSpecialChars($myts->oopsAddSlashesGPC($HTTP_POST_VARS['dbhost'])).'\';

	// '._INSTALL_DF_UNAME.'
	// '._INSTALL_DF_UNAME1.'
	$xoopsConfig[\'dbuname\'] = \''.$myts->oopsHtmlSpecialChars($myts->oopsAddSlashesGPC($HTTP_POST_VARS['dbuname'])).'\';

	// '._INSTALL_DF_PASS.'
	// '._INSTALL_DF_PASS1.'
	$xoopsConfig[\'dbpass\'] = \''.$myts->oopsHtmlSpecialChars($myts->oopsAddSlashesGPC($HTTP_POST_VARS['dbpass'])).'\';

	// '._INSTALL_DF_DBNAME.'
	// '._INSTALL_DF_DBNAME1.'
	$xoopsConfig[\'dbname\'] = \''.$myts->oopsHtmlSpecialChars($myts->oopsAddSlashesGPC($HTTP_POST_VARS['dbname'])).'\';

	// '._INSTALL_DF_PCONNECT.' ('._YES.'=1 '._NO.'=0)
	// '._INSTALL_DF_PCONNECT1.'
	$xoopsConfig[\'db_pconnect\'] = '.intval($HTTP_POST_VARS['db_pconnect']).';

	// '._INSTALL_LANG.'
	$xoopsConfig[\'default_language\'] = \''.$myts->oopsHtmlSpecialChars($myts->oopsAddSlashesGPC($language)).'\';

	include_once(XOOPS_ROOT_PATH.\'/include/common.php\');
}
?>';

if ( !$file = fopen('../mainfile.php', 'w') ) {
	echo _INSTALL_MF_FAILOPEN;
	install_footer();
	exit();
	}

if ( fwrite($file, $content) == -1 ) {
	echo _INSTALL_MF_FAILWRITE;
	fclose($file);
	install_footer();
	exit();
	}

echo "
<form action='./install.php' method='post'>
<input type='hidden' name='op' value='adminsetup'>
<div align='center'>
"._INSTALL_MF_WRITEOK."<br><br>
<input type='submit' class='button' name='submit' value='"._NEXT."'>
</div>
</form>";

}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function adminsetup() {
global $HTTP_POST_VARS;

include_once("../class/module.textsanitizer.php");

$myts = new MyTextSanitizer();
?>

<div align='center'>
<h4><?php echo _INSTALL_AD_MSG;?></h4>
</div>
<br />
<form action="./install.php" method="post">
<table align="center"><tr>

<td><?php echo _INSTALL_AD_UNAME;?></td>
<td><input type="text" class="text" name="uname" value="<?php echo $myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['uname']);?>"></td>

</tr><tr>

<td><?php echo _INSTALL_AD_EMAIL;?></td>
<td><input type="text" class="text" name="email" value="<?php echo $myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['email']);?>"></td>

</tr><tr>

<td><?php echo _INSTALL_AD_PASS;?></td>
<td><input type="text" class="text" name="password" value="<?php echo $myts->makeTboxData4PreviewInForm($HTTP_POST_VARS['password']);?>"></td>

</tr><tr>

<td colspan="2" align="center">
<input type="submit" class="button" name="submit" value="<?php echo _NEXT;?>">
<input type="hidden" name="op" value="install_tables">
<td>
</tr></table>
</form>

<?php
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function admincheck() {
global $HTTP_POST_VARS, $xoopsConfig;

if (!checkEmail($HTTP_POST_VARS['email'])) {
	$errors[] = _INSTALL_AD_BADEMAIL;
	}

if (strlen($HTTP_POST_VARS['password']) < $xoopsConfig['minpass']) {
	$errors[] = sprintf(_INSTALL_AD_BADPASS, $xoopsConfig['minpass']);
	}

if ( empty($HTTP_POST_VARS['uname']) || preg_match("/[^a-z0-9_-]/i", $HTTP_POST_VARS['uname']) ) {
	$errors[] = _INSTALL_AD_BADUNAME;
	}

if ( is_array($errors) ) {
	foreach ($errors as $val) {
		echo "<br /><b>$val</b>";
		}
	return false;
	}

return true;
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function install_tables() {
global $HTTP_POST_VARS, $db, $myts, $xoopsConfig;

include_once("../include/sql_parse.php");

$sql_file = $xoopsConfig['database'].'.sql';

$sql = join('', file('./sql/'.$sql_file));
$sql = remove_remarks($sql);
$sql = split_sql_file($sql, ';');

foreach ($sql as $value) {
	if ( $result = prefixQuery($value, $db->prefix) ) {
		if (!$db->query($result[0])) {
			uninstall_tables();
			return false;
			}
		}
}

$regdate  = time();
$uname    = $myts->makeTboxData4Save($HTTP_POST_VARS['uname']);
$email    = $myts->makeTboxData4Save($HTTP_POST_VARS['email']);
$password = md5($myts->makeTboxData4Save($HTTP_POST_VARS['password']));
$actkey   = substr(md5(makepass()), 0, 8);

$sql = "
	UPDATE ".$db->prefix("users")." SET
	uname='".$uname."',
	email='".$email."',
	url='".XOOPS_URL."/',
	user_regdate='".$regdate."',
	pass='".$password."',
	actkey='".$actkey."',
	theme='".$xoopsConfig['default_theme']."',
	last_login=".$regdate."
	WHERE uid=1";

if (!$db->query($sql)) {
	echo "Failed to create admin account, please login with the default values: Admin/admin";
}

return true;
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function uninstall_tables() {
global $db;

$tables = file("./cfg/table_list.txt");
$size   = count($tables);

for ($i=0; $i<$size; $i++) {
	$table = trim($tables[$i]);
	if (!empty($table)) {
		$db->query("DROP TABLE IF EXISTS ".$db->prefix($table)."");
		}
	}
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function do_chmod($file, $value, $type='chmod') {

switch ($type) {
	case 'ftp':
		break;

	default:
		@chmod($file, $value);
}

if ($value == 0666 || $value == 0777) {
	if ( !is_writable($file) ) {
		return false;
	}
}

return true;
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function finish() {
?>
<table width="60%" align="center"><tr>

<td colspan="2">
<center><?php echo _INSTALL_F_CONGRAT;?><br /><br />
<?php printf(_INSTALL_F_VISIT, XOOPS_URL);?><br /><br /><c/center>
</td>

</tr>
<?php
include_once("./cfg/chmod_list.php");
include_once(XOOPS_ROOT_PATH."/class/xoopslists.php");
$chmod_files = array();
$size = count($_chmod);
for ($i=0; $i<$size; $i++) {
	if ( !do_chmod(XOOPS_ROOT_PATH.'/'.$_chmod[$i]['base'], $_chmod[$i]['baseval']) ) {
		$result .= '<tr><td><li><span style="color:#ff0000;">'.$_chmod[$i]['base'].'</span></li></td><td>: 0'.decoct($_chmod[$i]['baseval']).'</td></tr>';
		$chmod_files[XOOPS_ROOT_PATH.'/'.$_chmod[$i]['base']] = $_chmod[$i]['baseval'];
	}
	if ($_chmod[$i]['extval']) {
		$images = XoopsLists::getImgListAsArray(XOOPS_ROOT_PATH.'/'.$_chmod[$i]['base'].'/');
		foreach ($images as $image) {
			if ( !do_chmod(XOOPS_ROOT_PATH.'/'.$_chmod[$i]['base'].'/'.$image, $_chmod[$i]['extval']) ) {
				$result .= '<tr><td><li><span style="color:#ff0000;">'.$_chmod[$i]['base'].'/'.$image.'</span></li></td><td>: 0'.decoct($_chmod[$i]['extval']).'</td></tr>';
				$chmod_files[XOOPS_ROOT_PATH.'/'.$_chmod[$i]['base'].'/'.$image] = $_chmod[$i]['extval'];
			}
		}
	}
}

if ( !empty($chmod_files) ) {
	?>
	<tr><td colspan="2"><b><?php echo _INSTALL_F_CHMOD;?></b></td></tr>
	<?php echo $result;?>
	<tr><td colspan="2"><br /><br />
	<form action="include/chmod_save.php" method="post">
	<?php echo _INSTALL_F_CHMODMSG;?>:<br /><br />
	<input type="hidden" name="files" value="<?php echo urlencode(serialize($chmod_files));?>">
	Windows: <input type="radio" class="radio" name="os" value="W">
	Unix:<input type="radio" class="radio" name="os" value="U" checked>
	<input type="submit" class="button" name="submit" value="<?php echo _DOWNLOAD;?>">
	</form>
	</td></tr>
	<?php
}
?>
</table>
<?php
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
switch($HTTP_POST_VARS['op']) {

case "setupcheck":
	setcookie("lang", $HTTP_POST_VARS['lang'], time()+1800, "/");
	wiz_header();
	setup_check();
	wiz_footer();
	break;

case "dbform":
	wiz_header();
	dbdata();
	wiz_footer();
	break;

case "dbconfirm":
	wiz_header();
	dbconfirm();
	wiz_footer();
	break;

case "writemainfile":
	wiz_header();
	write_mainfile();
	wiz_footer();
	break;

case "adminsetup":
	include_once("../mainfile.php");
	wiz_header();
	adminsetup();
	wiz_footer();
	break;

case "install_tables":
	include_once("../mainfile.php");
	wiz_header();
	if ( !admincheck() ) {
		adminsetup();
		} elseif (!install_tables()) {
			echo "<br /><div align='center'><h4>"._INSTALL_DB_DBERROR."</h4>";
			printf(_INSTALL_DB_TRYAGAIN, "install.php");
			echo "</div><br /><br />";
			} else {
				finish();
			}
	wiz_footer();
	break;

default:
	wiz_header();
	welcome();
	wiz_footer();
	break;
}
ob_end_flush();
?>
