<?php

	/*
	*	Gekko - Open Source Web Development Framework
	*	------------------------------------------------------------------------
	*	Copyright (C) 2004-2005, J. Carlos Nieto <xiam@users.sourceforge.net>
	*	This program is Free Software.
	*
	*	@package	Gekko
	*	@license	http://www.gnu.org/copyleft/gpl.html GNU/GPL License 2.0
	*	@author		J. Carlos Nieto <xiam@users.sf.net>
	*	@version	CVS: $Id:$
	*	@link		http://www.gekkoware.org
	*/

	define("IN-GEKKO", true);
	define("IN-INSTALL", true);
	define("DB_DEFAULT_DRIVER", "mysql.driver");
	define("SITE_DEFAULT_LANGUAGE", "es");
	define("SITE_DEFAULT_LANG_CODE", "es");
	define("SITE_DEFAULT_COUNTRY_CODE", "MX");

	session_start();

	define("GEKKO_LANG", (isset($_SESSION["sess_lang"]) && (file_exists("install/lang/{$_SESSION["sess_lang"]}/main.php"))) ? $_SESSION["sess_lang"] : SITE_DEFAULT_LANGUAGE);

	require_once "conf.php";

	$Lang = new Lang(GEKKO_LANG);

	require_once "install/lang/".GEKKO_LANG."/main.php";

	require_once "lib/template.lib.php";
	require_once "lib/actions.lib.php";
	require_once "lib/network.lib.php";
	require_once "lib/file.lib.php";

	require_once GEKKO_ROOT."modules/packages/main.lib.php";
	require_once GEKKO_ROOT."modules/menu-editor/main.lib.php";

	use_ssl();

	function need_change() {
		$check_dirs = Array("temp", "data");
		$writable = Array();
		foreach ($check_dirs as $dir) {
			$files = listdir($dir, true);
			foreach ($files as $key => $test) {
				if (!is_writable(GEKKO_ROOT."{$dir}/".$test)) {
					return true;
				}
			}
		}
		return false;
	}
	function ftp_permfix() {

		// writable files
		$check_dirs = Array("temp", "data");
		$writable = Array();
		foreach ($check_dirs as $dir) {
			$files = listdir($dir, true);
			foreach ($files as $key => $test) {
				if (is_writable(GEKKO_ROOT."{$dir}/".$test)) {
					unset($files[$key]);
				} else {
					$files[$key] = $dir."/".$test;
				}
			}
			$writable = array_merge($writable, $files);
		}

		$ftp = new ftpSession (
			$_SESSION["sess_ftp"]["host"],
			$_SESSION["sess_ftp"]["port"],
			$_SESSION["sess_ftp"]["user"],
			$_SESSION["sess_ftp"]["pass"]
		);
		if ($ftp->auth()) {
			if ($ftp->cd($_SESSION["sess_ftp"]["path"])) {

				$ftp->chmod("dbconf.php", "0777");

				$ftp->chmod("temp", "0777");
				$ftp->chmod("data", "0777");

				foreach ($writable as $file)
					$ftp->chmod($file, "0777");

			} else {
				abort(_l("E_FTP_WRONG_PATH"));
			}
		} else {
			abort(_l("E_FTP_ERROR"));
		}
	}

	function mk_dbconf() {
		return "<?php\n\t\$dbinfo = Array (\n\t\t\"host\" => \"{$_SESSION["sess_db"]["host"]}\",\n\t\t\"name\" => \"{$_SESSION["sess_db"]["database"]}\",\n\t\t\"user\" => \"{$_SESSION["sess_db"]["user"]}\",\n\t\t\"pass\" => \"{$_SESSION["sess_db"]["pass"]}\",\n\t\t\"pref\" => \"{$_SESSION["sess_db"]["prefix"]}\",\n\t\t\"type\" => \"".substr($_SESSION["sess_db"]["driver"], 0, strpos($_SESSION["sess_db"]["driver"], "."))."\"\n\t);\n?>";
	}

	gpGet("step", 1);

	/* default configuration keys */
	$defkeys = Array (
		"site.gekko_version" => GEKKO_VERSION,
		"site.title:string" => "Site title",
		"site.name" => "Site name",
		"site.slogan" => "Site slogan",
		"site.description" => "Site description",
		"site.show_text_title:boolean" => 1,
		"site.icontheme" => "default",
		"site.template" => "default",
		"site.stylesheet" => "default",
		"site.gzip_output:boolean" => 1,
		"site.copyright" => "&amp;copy; ".date("Y")." example.org",
		"site.footer" => "Powered by <a href=\"http://www.gekkoware.org\">Gekko</a>",
		"site.lang" => SITE_DEFAULT_LANGUAGE,
		"site.primary_lang" => SITE_DEFAULT_LANG_CODE,
		"site.primary_country" => SITE_DEFAULT_COUNTRY_CODE,
		"site.contact_mail" => "webmaster@example.com",
		"site.cookie.prefix" => "gekkocms_",
		"site.cookie.path" => "/",
		"site.cookie.life:int" => 60*60*24*1,
		"ftp.user" => "",
		"ftp.pass" => "",
		"ftp.port" => "21",
		"ftp.save_pass:boolean" => 0,
		"ftp.host" => "localhost",
		"ftp.path" => "",
		"smtp.host" => "localhost",
		"smtp.port" => "25",
		"smtp.user" => "",
		"smtp.pass" => "",
		"smtp.enable:boolean" => 0,
		"html_filter:boolean" => 1,
		"rtbeditor:boolean" => 1,
		"rtbeditor.default:boolean" => 1,
		"gbbcode:boolean" => 1,
		"gbbcode.smileys:boolean" => 1,
		"magic_blacklist:boolean" => 1
	);

	$nextstep = false;

	switch ($step) {
		case "lang":
			gpGlobalize("lang");

			requireVars($lang);

			$_SESSION["sess_lang"] = $lang;

			abort(header("Location: install.php"));
		break;
		case "install":

			gpGlobalize("ftp_pass, db_pass");

			/* final authentication before install */
			if ($_SESSION["sess_db"]["pass"] != $db_pass)
				abort(_l("E_DB_PASSWORD_MISMATCH"));

			if (isset($_SESSION["sess_ftp"]) && $_SESSION["sess_ftp"]["pass"] != $ftp_pass)
				abort(sprintf(_l("E_ACCESS_DENIED"), "FTP"));

			/* checking database connection */

			require_once GEKKO_ROOT."lib/db/{$_SESSION["sess_db"]["driver"]}";

			$db = new Database();

			if (!($db->open("{$_SESSION["sess_db"]["host"]}:{$_SESSION["sess_db"]["port"]}", $_SESSION["sess_db"]["user"], $_SESSION["sess_db"]["pass"], $_SESSION["sess_db"]["database"]))) {
				abort(sprintf(_l("E_ACCESS_DENIED".": %s"), "Database", $db->get_error()));
			}

			/* checking file permissions */
			if (isset($_SESSION["sess_ftp"])) {
				ftp_permfix();
			} else {
				$nextstep = "manual_config";
			}

			/* creating dbconf.php */
			filewrite("dbconf.php", mk_dbconf());

			/* changing permissions after writing dbconf.php */
			@chmod("dbconf.php", 0775);

			/* loading dbinfo.php */
			include "dbconf.php";

			/* database options */
			if ($_SESSION["sess_db"]["clean_database"]) {
				$db->query("DROP DATABASE IF EXISTS `{$_SESSION["sess_db"]["database"]}`",
				__FILE__, __LINE__);
				$db->query("CREATE DATABASE `{$_SESSION["sess_db"]["database"]}`",
				__FILE__, __LINE__);
				$db->query("USE `{$_SESSION["sess_db"]["database"]}`",
				__FILE__, __LINE__);
			} elseif ($_SESSION["sess_db"]["clean_prefix"]) {
				$db->query("SHOW TABLES");
				$plen = strlen($_SESSION["sess_db"]["prefix"]);
				while ($row = $db->fetch_row()) {
					foreach ($row as $table) {
						if (substr($table, 0, $plen) == $_SESSION["sess_db"]["prefix"]) {
							$db->query("DROP TABLE `$table`", __FILE__, __LINE__, true);
						}
					}
				}
			}

			/* those modules must be installed first */
			$modlist = Array ("conf", "modules", "groups", "packages");

			/* listing the remaining modules */
			$d = opendir(GEKKO_ROOT."modules/");
			while (($m = readdir($d)) !== false) {
				if ($m != "." && $m != "..") {
					if (file_exists(GEKKO_ROOT."modules/$m/module.inc.php") && !in_array($m, $modlist)) {
						$modlist[] = $m;
					}
				}
			}
			closedir($d);

			$inform = "";
			/* checking dependencies */
			foreach ($modlist as $module) {
				$modxml = pkg_get_xml($module);
				$inform .= pkg_checkInstall($modxml);
			}
			if ($inform) {
				header("content-type: text/plain");
				echo $inform;
				abort();
			}

			/* installing */
			foreach ($modlist as $module) {
				modCore::modInstall($module, "I");
			}

			/* executing additional installation queries */
			$GLOBALS["db"]->query("
			CREATE TABLE ".db_table("control")." (
				IP VARCHAR (32),
				AccessType VARCHAR (128),
				Counter TINYINT (5),
				Time INT (11)
			)", __FILE__, __LINE__);

			/* creating default configuration keys */
			$corekeys = Array();
			foreach ($defkeys as $key => $value) {
				$key = explode(":", $key);
				$type = isset($key[1]) ? $key[1] : "string";
				$key = $key[0];
				conf::getKey("core", $key, $value, $type);
				$corekeys[$key] = $value;
			}

			/* user configuration */
			foreach ($_SESSION["sess_conf"] as $conf) {
				conf::setKey($conf["module"], $conf["keyname"], $conf["value"]);
				if ($conf["module"] == "core") {
					unset($corekeys[$conf["keyname"]]);
				}
			}

			/* creating user */
			$db->query("INSERT INTO ".db_table("user")." (
					ID,
					Username,
					Realname,
					Password,
					Email,
					RegTime,
					Status,
					Groups
				) VALUES (
					'".$db->free_id("user")."',
					'{$_SESSION["sess_user"]["user"]}',
					'{$_SESSION["sess_user"]["realname"]}',
					'".md5(strtolower($_SESSION["sess_user"]["user"]).$_SESSION["sess_user"]["pass"])."',
					'{$_SESSION["sess_user"]["email"]}',
					'".time()."',
					'1',
					'".$cgdb["admin"]."'
				)
			", __FILE__, __LINE__);

			if ($_SESSION["sess_options"]["create_menu"]) {

				/* base menu (id = 1) */
				$db->query("INSERT INTO ".db_table("menu_block")."
				(ID, Title, Type) VALUES
				('1', '"._l("L_MAIN")."', '0')",
				__FILE__, __LINE__);

				/* account menu (id = 2) */
				$db->query("INSERT INTO ".db_table("menu_block")."
				(ID, Title, Type) VALUES
				('2','"._l("L_MY_ACCOUNT")."', '0')",
				__FILE__, __LINE__);

				menuAddLink(1, _l("L_INDEX"), "%index%/index.php", "home.png", "*");

				$default_blocks = Array();

				/* Main menu */
				$default_blocks[] = Array(
					"Modules"				=> "*",
					"Icon"					=> "menu.png",
					"Title"					=> _l("L_MENU"),
					"ScriptPath"			=> "menu-editor/menu-loader.php",
					"ScriptVars"			=> "a:1:{s:2:\"id\";s:1:\"1\";}",
					"OrderID"				=> "0",
					"Position"				=> "L",
					"blockClass"			=> "block",
					"cssText"				=> "",
					"auth_Access"			=> "*"
				);

				/* Account menu */
				$default_blocks[] = Array(
					"Modules"				=> "*",
					"Icon"					=> "account.png",
					"Title"					=> _l("L_MY_ACCOUNT"),
					"ScriptPath"			=> "menu-editor/menu-loader.php",
					"ScriptVars"			=> "a:1:{s:2:\"id\";s:1:\"2\";}",
					"OrderID"				=> "1",
					"Position"				=> "L",
					"blockClass"			=> "block",
					"cssText"				=> "",
					"auth_Access"			=> "$"
				);

				/* Who am I? */
				$default_blocks[] = Array(
					"Modules"				=> "*",
					"Icon"					=> "profile.png",
					"Title"					=> _l("L_MY_ACCOUNT"),
					"ScriptPath"			=> "users/whoami.php",
					"ScriptVars"			=> "a:0:{}",
					"OrderID"				=> "1",
					"Position"				=> "R",
					"blockClass"			=> "block",
					"cssText"				=> "",
					"auth_Access"			=> "*"
				);

				/* translating array into sql */

				foreach ($default_blocks as $query_info) {
					$sql_fields = $sql_values = Array();
					foreach ($query_info as $field => $value) {
						$sql_fields[] = $field;
						$sql_values[] = "'$value'";
					}
					// inserting main menu in a new block
					$db->query("INSERT INTO ".db_table("block")."
					(
						ID,
						".implode("\n,", $sql_fields)."
					)
					VALUES
					(
						'".$db->free_id("block")."',
						".implode("\n,", $sql_values)."
					)", __FILE__, __LINE__);
				}
			}

			foreach ($modlist as $module) {

				$modclass = modCore::getModClass($module);
				$modclass = new $modclass;

				/* creating additional menu links */
				if ($_SESSION["sess_options"]["create_menu"]) {
					if (!$modclass->create_menu() && file_exists(GEKKO_ROOT."modules/$module/main.inc.php")) {
						/* default menu link */
						menuAddLink(1, _l("M_".strtoupper($module)), "%index%/index.php/$module", "$module.png", "*");
					}
				}

				unset($modclass);
			}

			if (isset($_SESSION["sess_ftp"])) {
				/* saving some ftp information */
				conf::setKey("core", "ftp.host", $_SESSION["sess_ftp"]["host"]);
				conf::setKey("core", "ftp.path", $_SESSION["sess_ftp"]["path"]);
				conf::setKey("core", "ftp.port", $_SESSION["sess_ftp"]["port"]);
			}

			$db->close();

			if (!$nextstep) {
				session_unset();
				abort(header("Location: index.php/users/login"));
			}
		break;
		case "siteconf":
			gpGlobalize("conf, option");

			requireVars($conf);

			// setting some unchecked checkboxes to 0 (they aren't sent since they're not checked)
			$temp = fileread(GEKKO_ROOT."install/tpl/index.tpl");
			preg_match_all("/<input.*type=\"checkbox\".*name=\"conf\[(.*?)\]\".*>/", $temp, $match);
			foreach ($match[1] as $key) {
				if (!isset($conf[$key])) $conf[$key] = 0;
			}

			$_SESSION["sess_conf"] = Array();
			foreach ($conf as $key => $value) {
				$module = substr($key, 0, $d = strpos($key, ":"));
				$keyname = substr($key, $d+1);
				$_SESSION["sess_conf"][] = Array(
					"module" => $module,
					"keyname" => $keyname,
					"value" => $value
				);
			}

			$_SESSION["sess_options"] = $option ? $option : Array();

			$nextstep = "install";

		break;
		case "createuser":
			gpGlobalize("user, realname, email, pass, pass2");

			requireVars($user, $realname, $email, $pass);

			if ($pass && ($pass == $pass2)) {
				$_SESSION["sess_user"] = Array (
					"user" => $user,
					"realname" => $realname,
					"email" => $email,
					"pass" => $pass,
				);
				$nextstep = "siteconf";
			} else {
				abort(_l("L_PASSWORD_MISMATCH"));
			}

		break;
		case "upgrade":
			define("IN-UPGRADE", true);

			gpGlobalize("new_modules");

			if (isset($_SESSION["sess_ftp"]))
				ftp_permfix();

			filewrite("dbconf.php", mk_dbconf());
			@chmod("dbconf.php", 0755);

			require_once "dbconf.php";

			db_load_driver();

			db_init();

			/* checking for installed modules */
			$db->query("SELECT Module FROM ".db_table("module")."", __FILE__, __LINE__);
			$installed = Array();
			while ($row = $db->fetch_row())
				$installed[$row["Module"]] = true;

			/* comparing installed modules against packages */
			if ($new_modules) {

				/* getting a list of module packages */
				$packages = Array();
				$dh = opendir(GEKKO_ROOT."modules/");
				while (($md = readdir($dh)) !== false) {
					if ($md != "." && $md != "..") {
						$modpath = GEKKO_ROOT."modules/$md";
						if (is_dir($modpath)) {
							$packages[] = $md;
						}
					}
				}
				closedir($dh);

				foreach ($packages as $pkg) {
					if (!isset($installed[$pkg])) {
						// setting as false means to do a clean install for this module
						$installed[$pkg] = false;
					}
				}
			}

			/* upgrading/installing routine */
			foreach ($installed as $module => $status) {
				modCore::modInstall($module, $status ? "P" : "I");
			}

			db_exit();

			abort(header("Location: index.php/users/login"));
		break;
		case "dbconf":

			gpGlobalize("driver, host, port, database, user, pass, prefix,
			clean_prefix, clean_database, installtype");

			requireVars($driver, $host, $database);

			if (!$port)
				$port = 3306;

			/* connection test */
			if (!ereg("\.\.", $driver)) {
				require_once GEKKO_ROOT."lib/db/{$driver}";
				$db = new Database();
				if ($db->open("$host:$port", $user, $pass, $database)) {
					$_SESSION["sess_db"] = Array (
						"driver" => $driver,
						"host" => $host,
						"port" => $port,
						"database" => $database,
						"user" => $user,
						"pass" => $pass,
						"prefix" => $prefix,
						"clean_prefix" => $clean_prefix,
						"clean_database" => $clean_database
					);

					/*
						switching nextstep to installation type
						0 = clean install
						1 = upgrade
					*/

					$nextstep = $installtype ? "upgrade": "createuser";
				} else {
					abort(sprintf(_l("E_ACCESS_DENIED").": %s", "Database", $db->get_error()));
				}

			} else {
				abort(accessDenied(true));
			}

		break;
		case "ftp":
			gpGlobalize("host, port, path, user, pass");

			requireVars($host, $user);

			if (!$port) $port = 21;

			$ftp = new ftpSession($host, $port, $user, $pass);
			if ($ftp->auth()) {
				if (@$ftp->cd($path)) {
					if ($ftp->mtime("conf.php")) {
						/* storing data in session for furter access */
						$_SESSION["sess_ftp"] = Array(
							"host" => $host,
							"port" => $port,
							"user" => $user,
							"pass" => $pass,
							"path" => $path,
						);
						$nextstep = "dbconf";
					} else {
						$pwd = $ftp->pwd();
						preg_match("/\"(.*?)\"/", $pwd, $mwd);
						// expecting: "/foo/bar" is current directory.
						if (isset($mwd[1])) {
							$wd = $mwd[1];
							if (substr($_SERVER["SCRIPT_FILENAME"], 0, strlen($wd)) == $wd) {
								$prob_path = dirname($path.substr($_SERVER["SCRIPT_FILENAME"], strlen($wd)+1));
							}
						}
						// guessing probable path
						$ftp->bye();
						abort(_l("E_WRONG_PATH")."<br />".$pwd."<br />".(isset($prob_path) ? "Probable path (just guessing): $prob_path" : ""));
					}
				} else {
					$ftp->bye();
					abort(_l("E_FTP_CANNOT_CHDIR"));
				}
				$ftp->bye();
			} else {
				abort(sprintf(_l("E_ACCESS_DENIED"), "FTP"));
			}
		break;
		default: {
			// session_unset();
			if (!isset($_SESSION["sess_lang"])) {
				$nextstep = "lang";
				break;
			} else {
				if ($step == "manual_config") {
					if (!need_change() && !is_writable("dbconf.php") && filesize("dbconf.php")) {
						die(header("Location: index.php/users/login"));
					} else {
						$nextstep = "manual_config";
					}
				} else {
					$nextstep = (need_change() || !is_writable("dbconf.php")) ? "ftp" : "dbconf";
				}
			}
		}
	}

	switch ($nextstep) {
		case "manual_config": {
			$data = Array(
				"V_STEP" => $nextstep,
			);
		}
		case "install":
			$data = Array(
				"V_STEP" => $nextstep,
				"V_FTP" => isset($_SESSION["sess_ftp"])
			);
		break;
		case "siteconf":
			require GEKKO_ROOT."lang/lang_db.inc.php";

			$data = Array (
				"V_STEP" => $nextstep,
				"V_SITELANG.SEL" => mkSelect($lang_db, SITE_DEFAULT_LANGUAGE, "core:site.lang"),
				"V_LANG_CODE.SEL" => mkSelect($ISO_639, SITE_DEFAULT_LANG_CODE, "core:site.primary_lang"),
				"V_COUNTRY_CODE.SEL" => mkSelect($ISO_3166, SITE_DEFAULT_COUNTRY_CODE, "core:site.primary_country"),

			);
			/* loading some default keys */
			foreach ($defkeys as $key => $value) {
				$keyname = (($d = strpos($key, ":")) !== false) ? substr($key, 0, $d) : $key;
				$data["V_CORE_".strtoupper($keyname).""] = $value;
			}

		break;
		case "createuser":
			$data = Array (
				"V_STEP" => $nextstep
			);
		break;
		case "upgrade":
			$data = Array (
				"V_STEP" => $nextstep
			);
		break;
		case "dbconf":
			$drivers = listdir(GEKKO_ROOT."lib/db");
			$driver_sel = Array();
			foreach ($drivers as $driver) {
				if (file_extension($driver) == "driver") {
					$driver_sel[$driver] = substr($driver, 0, strpos($driver, "."));
				}
			}
			$data = Array (
				"V_STEP" => $nextstep,
				"V_DBDRIVERS.SEL" => mkSelect($driver_sel, DB_DEFAULT_DRIVER, "driver"),
				"V_INSTALLATION.SEL" => mkSelect(Array(_l("L_CLEAN_INSTALL"), _l("L_VERSION_UPGRADE")), filesize("dbconf.php") ? 1 : 0, "installtype"),
			);
		break;
		case "ftp":
			$data = Array (
				"V_STEP" => $nextstep
			);
		break;
		case "lang":
			require GEKKO_ROOT."lang/lang_db.inc.php";
			$data = Array (
				"V_STEP" => $nextstep,
				"V_LANG.SEL" => mkSelect($lang_db, SITE_DEFAULT_LANGUAGE, "lang")
			);
		break;
	}

	$t = new gtEngine();
	$buff = $t->load(GEKKO_ROOT."install/tpl/index.tpl", true);
	$buff = $t->parse($buff, $data, true);
	$t->output($buff);

?>