<?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);

	// keep old tables after upgrade?
	define("KEEP_TABLES", isset($_POST["keep_tables"]) ? $_POST["keep_tables"] : false);

	// your old Gekko 0.4.2 table prefix
	define("OLD_PREFIX", isset($_POST["prefix"]) ? $_POST["prefix"] : "gekko_");

	if (isset($_POST["utf8_convert"])) define ("UTF8_CONVERT", true);

	require_once "../../conf.php";

	if (!(isset($_POST["pass"]) && ($_POST["pass"] == $dbinfo["pass"]))) {
		echo "
		<html>

		<head>
		<title>Upgrading tool</title>
		</head>

		<body>
		<h1>Upgrading tool</h1>

		<form action=\"".basename($_SERVER["SCRIPT_FILENAME"])."\" method=\"post\">

		Database password:<br />
		<input type=\"password\" name=\"pass\"><br />

		Old Gekko Table Prefix:<br />
		<input type=\"text\" name=\"prefix\" value=\"gekko_\"><br />
		<hr />
		<input type=\"checkbox\" name=\"keep_tables\" value=\"1\" checked=\"checked\"> Keep old tables<br />
		<input type=\"checkbox\" name=\"utf8_convert\" value=\"1\" checked=\"checked\"> Convert ISO-8859-1 data to UTF-8<br />


		<button type=\"submit\">Next</button>
		<button type=\"reset\">Reset</button>
		</form>
		</body>

		</html>
		";
		exit;
	}

	db_init();

	function fix_link($src) {
		if (!preg_match("/^[a-z]*:/", $src)) {
			$src = "%index%/$src";
		}
		return $src;
	}

	// hmm... it's true, i'm so lazy to correct my own group levels mess
	function fixgroups($glist) {
		$glist = explode(",", $glist);
		while ($g = intval(trim(array_shift($glist)))) {
			if ($g === 1) return "1";
		}
		return "500";
	}

	function gbbc_escape($data) {
		return urlencode($data);
	}
	function gbbc_unescape($data) {
		return urldecode($data);
	}
	function gbbc_code_hide($code) {
		return "[code]".gbbc_escape($code)."[/code]";
	}
	function gbbc_code_unhide($code) {
		$code = nl2br(trim(gbbc_unescape($code)));

		$code = str_replace("\t", "&nbsp;&nbsp;", $code);
		return "<code>".$code."</code>";
	}
	function gbbc_block($contents, $style) {
		$css = "";
		$style = explode(":", substr($style, 1));
		foreach ($style as $tmp) {
			if ($tmp == "left" || $tmp == "right") {
				$css["float"] = $tmp;
			} elseif (strpos($tmp, "%") !== false) {
				$tmp = trim(preg_replace("/[^0-9]/", "", $tmp));
				if ($tmp) {
					$css["width"] = intval($tmp)."%";
				}
			} elseif (strpos($tmp, "/") !== false) {
				$tmp = explode("/", $tmp);
				for ($i = 0; $i < 1; $i++) {
					$tmp[$i] = trim(preg_replace("/[^0-9]/", "", $tmp[$i]));
				}
				if ($tmp[0] && $tmp[1]) {
					$css["width"] = round($tmp[0]/$tmp[1]*100)."%";
				}
			}
		}
		$style = "";
		foreach ($css as $obj => $tmp) {
			$style .= $obj.":".$tmp.";";
		}
		return "<div style=\"$style\">$contents</div>";
	}
	function gbbc_url($url, $text = null) {

		if (!$text) $text = $url;

		$banned = array("javascript");

		$proto = (($d = strpos($url, ":")) !== false) ? strtolower(substr($url, 0, $d)) : null;

		if (in_array($proto, $banned)) {
			return $text ? $text : $url;
		} else {
			if (strtolower(substr($url, 0, 3)) == "www") {
				return "<a class=\"link\" href=\"http://$url\" title=\"$url\">$text</a>";
			} elseif (strpos($url, "@")) {
				return "<a class=\"link\" href=\"mailto:$url\" title=\"$url\">$text</a>";
			} else {
				return "<a class=\"link\" href=\"$url\" title=\"$url\">$text</a>";
			}
		}

	}
	function gbb2html($text) {

		$pattern = Array();
		$replace = Array();

		$transpr = Array (
			"b", "u", "i", "s", "sup", "sub", "@hr", "@br", "ul", "ol", "li"
		);

		$pattern[] = "'\](\r\n|\n)\['";
		$replace[] = "] [";

		$pattern[] = "'\[code\](.+?)\[/code\]'sie";
		$replace[] = 'gbbc_code_hide(\'\\1\')';

		$pattern[] = "'\[left\](.+)\[/left\]'si";
		$replace[] = "<div style=\"text-align:left\">\\1</div> ";

		$pattern[] = "'\[right\](.+)\[/right\]'si";
		$replace[] = "<div style=\"text-align:right\">\\1</div> ";

		$pattern[] = "'\[center\](.+)\[/center\]'si";
		$replace[] = "<div style=\"text-align:center\">\\1</div> ";

		$pattern[] = "'\[justify\](.+)\[/justify\]'si";
		$replace[] = "<div style=\"text-align:justify\">\\1</div> ";

		$pattern[] = "'\[block(.*?)\](.*?)\[/block\]'ie";
		$replace[] = "gbbc_block('\\2', '\\1')";

		$pattern[] = "'\[color=([a-z0-9#]+?)\](.+?)\[/color\]'si";
		$replace[] = "<span style=\"color:\\1;\">\\2</span>";

		$pattern[] = "'\[size=([a-z0-9\-%]+?)\](.+?)\[/size\]'si";
		$replace[] = "<span style=\"font-size:\\1;\">\\2</span>";

		$pattern[] = "'\[font=([a-z0-9 ]+?)\](.+?)\[/font\]'si";
		$replace[] = "<span style=\"font-family:\\1;\">\\2</span>";

		$pattern[] = "'\[highlight\](.+?)\[/highlight\]'si";
		$replace[] = "<span class=\"highlight\">\\1</span>";

		$pattern[] = "'\[highlight\](.+?)\[/highlight\]'si";
		$replace[] = "<span class=\"highlight\">\\1</span>";

		$pattern[] = "'\[indent\](.+?)\[/indent\]'si";
		$replace[] = "<div style=\"margin:15px;\">\\1</div>";

		$pattern[] = "'\[(url|a)\](.+?)\[/(url|a)\]'ie";
		$replace[] = "gbbc_url('\\2')";

		$pattern[] = "'\[(url|a)=(.+?)\](.+?)\[/(url|a)\]'ie";
		$replace[] = "gbbc_url('\\2', '\\3')";

		$pattern[] = "'\[img\](.+?)\[/img\]'i";
		$replace[] = "<img class=\"photo\" style=\"margin:4px;\" src=\"\\1\" alt=\"\\1\" />";

		$pattern[] = "'\[img:([0-9]+?):([0-9]+?)\](.+?)\[/img\]'i";
		$replace[] = "<img class=\"photo\" width=\"\\1\" height=\"\\2\" style=\"margin:4px;\" src=\"\\3\" alt=\"\\3\" />";
/*
		$pattern[] = "'\[quote\](.+?)\[/quote\]'si";
		$replace[] = "<div class=\"quote\">\\1</div>";

		$pattern[] = "'\[quote=(.+?)\](.+?)\[/quote\]'si";
		$replace[] = "<div class=\"quote\"><b>\\1:</b><br />\\2</div>";

		$pattern[] = "'\[quote:([0-9]+?)\](.+?)\[/quote\]'sie";
		$replace[] = "gbbc_make_user_quote('\\1','\\2')";
*/
		$pattern[] = "'\[hr\]'si";
		$replace[] = "<hr />";

		foreach ($transpr as $tag) {
			if (strpos("@", $tag) == false) {
				$pattern[] = "'\[$tag\]'si";
				$pattern[] = "'\[/$tag\]'si";
				$replace[] = "<$tag>";
				$replace[] = "</$tag>";
			} else {
				$pattern[] = "'\[$tag\]'si";
				$replace[] = "<$tag />";
			}
		}

		$text = " $text ";

		$text = preg_replace($pattern, $replace, $text);

		$text = preg_replace("'\[code\](.+?)\[/code\]'sie", "gbbc_code_unhide('\\1')", $text);

		$text = substr($text, 1, strlen($text) - 2);

		$text = str_replace("\\r\\n", "<br />\n", $text);

		$text = preg_replace("/<(.*?)(src|href)=\"(.*?)\"(.*?)>/e", "'<\\1\\2=\\\"'.fix_link('\\3').'\\\"\\4>'", $text);

		return $text;
	}

	function sql_data_fix(&$array) {
		reset ($array);
		while (list($key) = each($array)) {
			$array[$key] = $GLOBALS["db"]->escape($array[$key]);
			if (defined("UTF8_CONVERT")) {
				$array[$key] = utf8_encode($array[$key]);
			}
		}
	}

	// begin users
	if (file_exists("../../modules/users")) {
		$q = $db->query("SELECT
		ID, Username, Realname, Password, EmailAddr, LastLogin, RegDate, Status, SesLen, Groups
		FROM ".OLD_PREFIX."users", __FILE__, __LINE__, true);

		// truncating new table
		$r = $db->query("TRUNCATE TABLE ".db_table("user")."", __FILE__, __LINE__, true);

		while ($row = $db->fetch_row($q)) {

			// skipping "unknown" user
			if ($row["ID"] == "65535") continue;

			sql_data_fix($row);

			$r = $db->query("INSERT INTO ".db_table("user")."
			(ID, Username, Realname, Password, Email, Seslen, RegTime, Status, Groups)
			VALUES
			('{$row["ID"]}', '{$row["Username"]}', '{$row["Realname"]}', '{$row["Password"]}',
			'{$row["EmailAddr"]}', '{$row["SesLen"]}', '{$row["RegDate"]}', '{$row["Status"]}',
			'".fixgroups($row["Groups"])."')", __FILE__, __LINE__);
		}
	}
	// end users

	// begin profile
	if (file_exists("../../modules/users")) {
		$q = $db->query("SELECT
		UserID, Nickname, PublicEmail, BirthDate, Gender, Country, State, City,
		Avatar, WebSite, About, opt_hSex, opt_hAge, opt_hEmail, Signature,
		ICQ, MSN, YIM, AIM
		FROM ".OLD_PREFIX."profile", __FILE__, __LINE__, true);

		// truncating new table
		$r = $db->query("TRUNCATE TABLE ".db_table("user_profile")."", __FILE__, __LINE__, true);

		while ($row = $db->fetch_row($q)) {

			// skipping "unknown" user
			if ($row["UserID"] == "65535") continue;

			sql_data_fix($row);

			$r = $db->query("INSERT INTO ".db_table("user_profile")."
			(ID, Nickname, PublicEmail, BirthDate, WebSite, Avatar, AboutMe,
			Signature, Location, Gender, imMSN, imYIM, imICQ)
			VALUES
			('{$row["UserID"]}', '{$row["Nickname"]}', '{$row["PublicEmail"]}',
			'".timestamp($row["BirthDate"])."', '{$row["WebSite"]}', '{$row["Avatar"]}',
			'".gbb2html($row["About"])."', '{$row["Signature"]}', '{$row["City"]}, {$row["State"]}, {$row["Country"]}',
			'{$row["Gender"]}', '{$row["MSN"]}', '{$row["YIM"]}', '{$row["ICQ"]}')", __FILE__, __LINE__);
		}
	}
	// end profile

	// begin categories
	if (file_exists("../../modules/categories")) {
		$q = $db->query("SELECT ID, Title, Status FROM ".OLD_PREFIX."topics", __FILE__, __LINE__, true);

		$db->query("TRUNCATE TABLE ".db_table("category")."");

		if ($db->num_rows($q)) {
			while ($row = $db->fetch_row($q)) {
				sql_data_fix($row);
				$r = $db->query("INSERT INTO ".db_table("category")." (ID, Category, Status)
				VALUES ('{$row["ID"]}','{$row["Title"]}','{$row["Status"]}')", __FILE__, __LINE__, true);
			}
		} else {
			$r = $db->query("INSERT INTO ".db_table("category")." (ID, Category, Status)
			VALUES ('1','General','1')", __FILE__, __LINE__, true);
		}
	}
	// end categories

	// begin blog
	if (file_exists("../../modules/blog")) {
		$q = $db->query("SELECT
		ID, UserID, CreationDate, Subject, Contents, Footer, AllowComments
		FROM ".OLD_PREFIX."blog", __FILE__, __LINE__, true);

		$db->query("TRUNCATE TABLE ".db_table("blog")."");

		while ($row = $db->fetch_row($q)) {
			sql_data_fix($row);
			$r = $db->query("INSERT INTO ".db_table("blog")."
			(ID, UserID, Category, Title, Content, Footer, CreationTime,
			AllowComments, Icon)
			VALUES ('{$row["ID"]}', '{$row["UserID"]}', '1', '".$row["Subject"]."',
			'".gbb2html($row["Contents"])."', '".$row["Footer"]."',
			'{$row["CreationDate"]}', '{$row["AllowComments"]}', 'blog.png')",
			__FILE__, __LINE__, true);
		}
	}
	// end blog

	/*
	// converting news into blog entries
	if (file_exists("../../modules/blog")) {
		$q = $db->query("SELECT
		ID, Icon, Subject, Contents, opt_eComments, CreationDate, AuthorID
		FROM ".OLD_PREFIX."news", __FILE__, __LINE__, true);

		$db->query("TRUNCATE TABLE ".db_table("blog")."");

		while ($row = $db->fetch_row($q)) {
			sql_data_fix($row);
			$r = $db->query("INSERT INTO ".db_table("blog")."
			(ID, UserID, Category, Title, Content, Footer, CreationTime,
			AllowComments, Icon)
			VALUES ('{$row["ID"]}', '{$row["AuthorID"]}', '1', '".$row["Subject"]."',
			'".gbb2html($row["Contents"])."', '',
			'{$row["CreationDate"]}', '{$row["opt_eComments"]}', 'blog.png')",
			__FILE__, __LINE__, true);
		}
	}
	// converting news into blog entries
	*/

	// begin comments (only for blog)
	if (file_exists("../../modules/comments")) {
		$q = $db->query("SELECT
		ID, LinkID, Type, Guest, Icon, ContactMail, Subject, Contents, AuthorID, AuthorIP,
		CreationDate
		FROM ".OLD_PREFIX."comments
		WHERE Type = 'blog'
		", __FILE__, __LINE__, true);

		$db->query("TRUNCATE TABLE ".db_table("comment")."");

		while ($row = $db->fetch_row($q)) {
			sql_data_fix($row);
			$r = $db->query("INSERT INTO ".db_table("comment")."
			(ID, Module, Thread, UserID, Nickname, Email, Icon, Title, Content,
			CreationTime, IPAddr)
			VALUES ('{$row["ID"]}', '{$row["Type"]}', '{$row["LinkID"]}', '{$row["AuthorID"]}',
			'{$row["Guest"]}', '{$row["ContactMail"]}', '{$row["Icon"]}', '{$row["Subject"]}',
			'".gbb2html($row["Contents"])."', '{$row["CreationDate"]}', '{$row["AuthorIP"]}'
			)",
			__FILE__, __LINE__, true);
		}
	}
	// end comments

	// begin tagboard
	if (file_exists("../../modules/tagboard")) {
		$q = $db->query("SELECT
		ID, UserID, UserIP, CreationDate, Nickname, Link, Content,
		CreationDate
		FROM ".OLD_PREFIX."tagboard
		", __FILE__, __LINE__, true);

		$db->query("TRUNCATE TABLE ".db_table("tagboard")."");

		while ($row = $db->fetch_row($q)) {
			sql_data_fix($row);

			$r = $db->query("INSERT INTO ".db_table("tagboard")."
			(ID, UserID, UserIP, CreationTime, Nickname, Link, Message)
			VALUES ('{$row["ID"]}','{$row["UserID"]}','{$row["UserIP"]}',
			'{$row["CreationDate"]}','{$row["Nickname"]}','{$row["Link"]}',
			'{$row["Content"]}')",
			__FILE__, __LINE__, true);
		}
	}

	// end tagboard

	// begin statistics
	if (file_exists("../../modules/statistics")) {
		$db->query("TRUNCATE TABLE ".db_table("stats_uri_logs")."");

		$q = $db->query("SELECT
		Counter, LogString
		FROM ".OLD_PREFIX."url_logs
		", __FILE__, __LINE__, true);

		while ($row = $db->fetch_row($q)) {
			sql_data_fix($row);

			$r = $db->query("INSERT INTO ".db_table("stats_uri_logs")."
			(Type, Counter, URL, LastIP, LastTime)
			VALUES ('request', '{$row["Counter"]}', '{$row["LogString"]}', '', '".time()."')",
			__FILE__, __LINE__, true);
		}

		$q = $db->query("SELECT
		Counter, LogString
		FROM ".OLD_PREFIX."ref_logs
		", __FILE__, __LINE__, true);

		while ($row = $db->fetch_row($q)) {
			sql_data_fix($row);

			$r = $db->query("INSERT INTO ".db_table("stats_uri_logs")."
			(Type, Counter, URL, LastIP, LastTime)
			VALUES ('referer', '{$row["Counter"]}', '{$row["LogString"]}', '', '".time()."')",
			__FILE__, __LINE__, true);
		}

		$q = $db->query("SELECT
		Type, Var, Count
		FROM ".OLD_PREFIX."multicounter WHERE (Type = 'os' OR Type = 'browser' OR Type = 'total')
		", __FILE__, __LINE__, true);

		$db->query("TRUNCATE TABLE ".db_table("stats_counter")."");

		while ($row = $db->fetch_row($q)) {
			sql_data_fix($row);

			switch ($row["Type"]) {
				case "os":
					$row["Type"] = "user-agent-os";
				break;
				case "browser":
					$row["Type"] = "user-agent";
				break;
				case "total":
					$row["Type"] = "total";
					if ($row["Var"] != "visits") continue;
					// setting unique visits as total visits
					$r = $db->query("INSERT INTO ".db_table("stats_counter")."
					(Type, Variable, Counter)
					VALUES ('total', 'unique-visits', '{$row["Count"]}')",
					__FILE__, __LINE__, true);

					$row["Var"] = "clicks";
				break;
			}

			$r = $db->query("INSERT INTO ".db_table("stats_counter")."
			(Type, Variable, Counter)
			VALUES ('{$row["Type"]}', '".strtolower($row["Var"])."', '{$row["Count"]}')",
			__FILE__, __LINE__, true);

		}


		$fields = Array();
		for ($i = 0; $i < 24; $i++) {
			$fields[] = "h".(str_repeat("0", 2-strlen($i)))."$i";
		}

		$q = $db->query("SELECT
		Month, Day, Year, ".implode(", ", $fields).", Total
		FROM ".OLD_PREFIX."clickstats
		", __FILE__, __LINE__, true);

		$db->query("TRUNCATE TABLE ".db_table("stats_visits")."");

		while ($row = $db->fetch_row($q)) {
			sql_data_fix($row);

			$values = Array();
			foreach ($fields as $field) {
				$values[] = $row[$field];
			}
			$values = "'".implode("', '", $values)."'";

			$r = $db->query("INSERT INTO ".db_table("stats_visits")."
			(Year, Month, Day, ".implode(", ", $fields).", Total)
			VALUES ('{$row["Year"]}', '{$row["Month"]}', '{$row["Day"]}',
			$values, '{$row["Total"]}')",
			__FILE__, __LINE__, true);
		}
	}
	// end statistics

	// dropping tables
	if (!KEEP_TABLES && 1) {
		$q = $db->query("DROP TABLE IF EXISTS ".OLD_PREFIX."comments", __FILE__, __LINE__, true);
		$q = $db->query("DROP TABLE IF EXISTS ".OLD_PREFIX."blog", __FILE__, __LINE__, true);
		$q = $db->query("DROP TABLE IF EXISTS ".OLD_PREFIX."users", __FILE__, __LINE__, true);
		$q = $db->query("DROP TABLE IF EXISTS ".OLD_PREFIX."user_profile", __FILE__, __LINE__, true);
		$q = $db->query("DROP TABLE IF EXISTS ".OLD_PREFIX."topics", __FILE__, __LINE__, true);
		$q = $db->query("DROP TABLE IF EXISTS ".OLD_PREFIX."blog", __FILE__, __LINE__, true);
		$q = $db->query("DROP TABLE IF EXISTS ".OLD_PREFIX."url_logs", __FILE__, __LINE__, true);
		$q = $db->query("DROP TABLE IF EXISTS ".OLD_PREFIX."url_logs", __FILE__, __LINE__, true);
		$q = $db->query("DROP TABLE IF EXISTS ".OLD_PREFIX."statistics", __FILE__, __LINE__, true);
	}

	db_exit();

	header("Location: ../../index.php");

?>