<?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
	*/

	if (!defined("IN-GEKKO")) die("Get a life!");

	require_once GEKKO_ROOT."modules/groups/main.lib.php";

	$cookie = explode(":", rcookie("auth"));
	if (count($cookie) == 2)
		list($auth_key, $auth_hash) = $cookie;

	$User = Array (
		"ID" => "0",
		"Username" => "",
		"Groups" => "0"
	);

	// auth string for those who hasn't login yet
	$L["C_AUTH_STR"] = md5(date("dmY").IP_ADDR.$_SERVER["HTTP_USER_AGENT"]);

	if (isset($auth_key) && isset($auth_hash)) {

		$db->query("SELECT ID, Password FROM ".db_table("user")." WHERE AuthKey = '{$auth_key}'", __FILE__, __LINE__);

		if ($db->num_rows()) {

			$row = $db->fetch_row();

			if ($auth_hash == md5($row["Password"].IP_ADDR)) {

				$db->query("
					SELECT
						ID,
						Username,
						Realname,
						Email,
						Status,
						Groups,
						Preferences
					FROM ".db_table("user")."
					WHERE ID = '".$row["ID"]."'
				", __FILE__, __LINE__);

				$User = $db->fetch_row();

				if (function_exists("saneHTML")) saneHTML($User, "Groups");

				$User["Groups"] = implode(",", getAllLinkedGroups($User["Groups"]));

				define("AUTH", 1);

				$L["C_AUTH_STR"] = md5(conf::getKey("core", "gekko.key", genkey(32), "s").$auth_key.$row["Password"].IP_ADDR.$_SERVER["HTTP_USER_AGENT"]);

			} else {
				slog("Wrong cookie data.", "warning", 5);
			}
		}
	}

	/*
		Performing another authentication if we are in ./modules
		I hope this will keep away some spammers and script kiddies :)
	*/
	preg_match("/(modules)\/([a-zA-Z0-9\-_.]*)\/([a-zA-Z0-9\-_.]*)/", $_SERVER["PHP_SELF"], $act_info);

	if (count($act_info) >= 4) {

		list($act_path, $act_reqdir, $act_module, $act_action) = $act_info;

		switch ($act_reqdir) {
			case "modules":

				// Cannot allow privileged actions when Gekko is in demo mode.
				if (defined("AUTH") && GEKKO_DEMO_MODE)
					abort(_l("E_DEMO_MODE"));

				require_once GEKKO_ROOT."lib/actions.lib.php";
				/*
					This means the user requested an action script so him/her
					must provide a valid "Auth String".

					To do this you only must add the following line to your
					html form:

					<input type="hidden" name="auth" value="{C_AUTH_STR}" />

					Gekko will automatically fill {C_AUTH_STR} with the
					required value.

					In case you're using an URL:
					.../main.act.php?var1=foo&var2=foo&auth=_l("C_AUTH_STR")

				*/
				// auth string
				if (!checkAuthStr(gpGet("auth"))) {
					slog("Using an invalid auth string.", "warning", 2);
					abort(accessDenied(1, __FILE__, __LINE__));
				}

				// module access
				$db->query("SELECT auth_Exec FROM ".db_table("module")."
				WHERE Module = '{$act_module}'");
				$row = $db->fetch_row();

				if (!gauth($row["auth_Exec"]))
					abort(accessDenied(1, __FILE__, __LINE__));

				break;
		}
	}

	// BAN LIST (read conf.php)
	if (Conf::getKey("core", "magic_blacklist", 1) && $AccessTable->check("core-exec-requests", Conf::getKey("core", "exec_requests.interval", 5, "i"), Conf::getKey("core", "exec_requests.requests", 8, "i"), 1)) {

		/*
			If him continues bothering our server, we will ban him/she/it to
			prevent waste of database connections, and the major part of our
			script execution.

			After allowing a maximum of 8 advisories in a minute,  we will
			proceed to add him/she/it to our blacklist.
		*/

		// ok, we advised him 3 times, we're not playing...
		if ($AccessTable->check("core-exec-preban", 60, 3, 1)) {

			// creating new entry for this ip in our banlist ($banlist array is already declared)
			$banlist[getIP()] = time();

			// saving the new entry in the banlist
			$ban_fh = fopen(GEKKO_BLACKLIST, "w");
			fwrite($ban_fh, serialize($banlist));
			fclose($ban_fh);

			// showing him/her/it an non-friendly error message
			header("HTTP/1.1 403 Forbidden");
			echo "<h1>That's annoying!</h1>
			Do you have a girlfriend?
			<hr /><address>Powered by <a href=\"http://www.gekkoware.org\">Gekko</a></address>
			";
			slog("Banned user: script executions exceeded", "warning", 1);
			abort();
		}

		// keeping flooders & annoying scripts away
		echo "<h1>Please wait.</h1>";
		echo "I'm sorry but you've made too many requests within a very short
		period of time, please be kind and wait some seconds before reload
		this page. You're advised!
		<hr /><address>Powered by <a href=\"http://www.gekkoware.org\">Gekko</a></address>";

		slog("User is reaching script execution limit.", "warning", 2);

		abort();
	}
	unset($banlist);

	slog("", "access");

	// setting antibot obfuscated string
	if (function_exists("jsobfuscate")) _l("C_ANTIBOT", jsobfuscate($L["C_AUTH_STR"]));

?>