<?php
/*
fiemeCP - BETA.
Written by, and managed by xDario.

The script may NOT BE ALTERED, and redistributing any part of it, even with credets, is prohibited. Currently, only myself and my website (http://www.dario-ml.com/) along with kryptodev are aloud to host my script.

©2011 xDario (created for Ohai Online)

You must provide a thanks on the page from which this is called, unless you have donated. If I find my class used without copyright, or a mention of appreciation, I will pursude you. Fiesta servers aren't thousands, so you're not hard to spot out.

Page: class.core.php
Last Change: 30 June 2011
*/

if (!defined('IN_FIEME'))
{
	die("canno't directly access this page");
}

class core
{
	function run_background($file_location)
	{
		if(!isset($_SERVER['PWD'])) //*nix (aka IS windows)
		{
			if (!file_exists(PHP_LOCATION))
			{
				die ("Please put a valid php loaction in /includes/settings/s.global.php");
			}
			$WshShell = new COM("WScript.Shell");
			$oExec = $WshShell->Run(PHP_LOCATION . " -q $file_location", 7, false);
		}
	}
	
	function true_time($filePath) 
	{
		$time = filemtime($filePath); 
	
		$isDST = (date('I', $time) == 1); 
		$systemDST = (date('I') == 1); 
	
		$adjustment = 0; 
	
		if($isDST == false && $systemDST == true) 
			$adjustment = 3600;
		
		else if($isDST == true && $systemDST == false) 
			$adjustment = -3600;
	
		else 
			$adjustment = 0; 
		return ($time + $adjustment); 
	}
	
	function cookie_logout($whereto = 'index.php')
	{
		global $plugin;
		
		$plugin->run_hooks("core_logout");
		
		if (@$_GET['do'] == 'logout')
		{
			$plugin->run_hooks("core_logout_main");
			setcookie ("fieme_uname", "", time() - 3600);
			setcookie ("fieme_uid", "", time() - 3600);
			setcookie ("fieme_pass_hash", "", time() - 3600);
			session_destroy();
			#header( "refresh:0;url=$whereto" );
			header("Location: $whereto");
		}
		if (@$_GET['do'] == 'removecook')
		{
			$plugin->run_hooks("core_logout_cookies");
			setcookie ("fieme_uname", "", time() - 3600);
			setcookie ("fieme_uid", "", time() - 3600);
			setcookie ("fieme_pass_hash", "", time() - 3600);
			#header( "refresh:0;url=$whereto" );
			header("Location: $whereto");
		}
		if (@$_GET['do'] == 'logout_admin')
		{
			$plugin->run_hooks("core_logout_admin");
			unset($_SESSION['fieme_a_auth']);
			unset($_SESSION['fieme_a_uname']);
			unset($_SESSION['fieme_a_uid']);
			unset($_SESSION['fieme_a_adminlevel']);
			#header( "refresh:0;url=$whereto" );
			header("Location: $whereto");
		}
	}
	
	function maintainance_functions()
	{
		global $settings, $cache, $fiemecp, $plugin;
		
		$plugin->run_hooks("core_maintainance_functions_start");
		
		if ($cache->read("LAST_GROOM", 43200) === FALSE) //let's groom our script. Make sure things are running ok, right?
		{
			$plugin->run_hooks("core_maintainance_functions_groom_start");
			
			$this->refresh_settings();
			
			if ($settings->security_auto_hide == 1)
			{
				//Let's start our log:
				$groom_notes = "Last groom completed on: " . date("jS M Y \a\\t H:i", time()) . "<br />\r\n" ;
				
				//protect the cache and include directories.
				$deny_htaccess = $settings->security_auto_hide_htaccess;
				
				if (($cache->read('.htaccess', '-1') === FALSE) || ($settings->security_auto_hide_overwrite == 1))
				{
					$cache->write(".htaccess", $deny_htaccess);
					$groom_notes .= "Successfully protected the cache directory<br />\r\n\r\n";
				}
				else
				{
					$groom_notes .= "Cache directory was already protected, so it was not protected<br />\r\n";
				}
				
				if (($cache->read('.htaccess', '-1', 'includes//') === FALSE) || ($settings->security_auto_hide_overwrite == 1))
				{
					$cache->write(".htaccess", $deny_htaccess, 'includes//');
					$groom_notes .= "Successfully protected the includes directory<br />\r\n";
				}
				else
				{
					$groom_notes .= "Includes directory was already protected, so it was not protected<br />\r\n";
				}
				
				//let's clean out the login logs:
				if ($settings->logging_logins_storetime != 0) //if we are supposed to groom, then let's!
				{
					if (sqlsrv_query($fiemecp->dbacc, "DELETE FROM [Account].[dbo].[fLoginLog] WHERE time <" . ( (time()) - $settings->logging_logins_storetime), array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET)))
					{
						$groom_notes .= "Successfully cleaned out all entries older than " . $settings->logging_logins_storetime . "seconds in the Login Logs<br />\r\n";
					}
					else
					{
						$groom_notes .= "Something went wrong when pruning the user login logs. If this error continues, please contact a fiemeCP developer to have it fixed<br />\r\n";
					}
				}
				
				//let's clean out the user CP logs:
				$settings->load('usercp');
				if ($settings->keep_usercp_logs != 0) //if we are supposed to groom, then let's!
				{
					if (sqlsrv_query($fiemecp->dbacc, "DELETE FROM [Account].[dbo].[fUserCPLog] WHERE time <" . ( (time()) - $settings->keep_usercp_logs), array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET)))
					{
						$groom_notes .= "Successfully cleaned out all entries older than " . $settings->keep_usercp_logs . "seconds in the UserCP Logs<br />\r\n";
					}
					else
					{
						$groom_notes .= "Something went wrong when pruning the user CP logs. If this error continues, please contact a fiemeCP developer to have it fixed<br />\r\n";
					}
				}
				
				//let's clean out the plugins:
				if (sqlsrv_query($fiemecp->dbacc, "DELETE FROM [Account].[dbo].[fPlugins] WHERE active = 0", array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET)))
				{
					$groom_notes .= "Successfully cleaned out all deinstalled and deactivated plugins from the database<br />\r\n";
				}
				else
				{
					$groom_notes .= "Something went wrong when pruning the plugins. If persistent, please contact fiemeCP developers<br />\r\n";
				}
				
				if (FIEME_DEV == 1)
				{
					sleep(1); //make sure windows writes the file before reading it
					global $dev_content;
					$dev_content .= $cache->read("LAST_GROOM");
				}
			}
			
			$plugin->run_hooks("core_maintainance_functions_groom_end");
			
			$cache->write("LAST_GROOM", $groom_notes);
		}
		$this->check_server();
		
		$plugin->run_hooks("core_maintainance_functions_end");
	}
	
	function update_plugins()
	{
		//let's update the plugin cache!
		
		global $fiemecp, $cache;
		
		$content = "<?php
//Plugin last updated:" . date("jS M Y \a\\t H:i", time()) . "\r\n";

		$result = sqlsrv_query($fiemecp->dbacc, "SELECT * FROM fPlugins WHERE active = '1' or active='2'", array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		
		while ($row = sqlsrv_fetch_array($result))
		{
			if (file_exists(FIEME_ROOT . "includes/plugins/$row[plugin_name].php"))
			{
				if ($row['active'] == 1)
				{
					$content .= "\$p_c['active']['$row[plugin_name]'] = \"ACTIVE\";\r\n";
				}
				elseif ($row['active'] == 2)
				{
					$content .= "\$p_c['deactive']['$row[plugin_name]'] = \"STILL INSTALLED\";\r\n";
				}
			}
			else
			{
				$content .= "//Failed to load $row[plugin_name]\r\n";
			}
		}
		$cache->write("plugins", $content . "\r\n?>");
	}
	
	function refresh_settings($what = "___all")
	{
		global $fiemecp, $cache;
		
		if ($what == "___all")
		{
			$query = sqlsrv_query($fiemecp->dbacc, "SELECT setting_group FROM fSettings GROUP BY setting_group", array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
			$i = 1;
			while ($row = sqlsrv_fetch_array($query))
			{
				
				$i = $row['setting_group'];
				$query2 = sqlsrv_query($fiemecp->dbacc, "SELECT * FROM dbo.fSettings WHERE setting_group = ?", array($row['setting_group']), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
				$content = "<?php
/*
fiemeCP - BETA.
Written by, and managed by xDario.

The script may be altered at wish, but redistributing any part of it, even with credets, is prohibited. Currently, only myself and my website (http://www.dario-ml.com/) along with kryptodev are aloud to host my script.

©2011 xDario (created for Ohai Online)

You must provide a thanks on the page from which this is called, unless you have donated. If I find my class used without copyright, or a mention of appreciation, I will pursude you. Fiesta servers aren't thousands, so you're not hard to spot out.

DO NOT EDIT THIS PAGE!!! IT WILL HAVE ONLY A SHORT TERM EFFECT! USE THE DATABASE, AND RUN \&core->refresh_settings

Page: s.$i.php
AUTOMATED: " . date("jS M Y \a\\t H:i", time()) . "
*/\r\n\r\n";
				while ($row2 = sqlsrv_fetch_array($query2))
				{
					$content .= "\$s['$row2[setting_save_name]'] = \"$row2[setting_value]\";\r\n";
				}
				$cache->write("s.$i.php", $content, "includes\settings\\");
			}
		}
		else
		{
			$query2 = sqlsrv_query($fiemecp->dbacc, "SELECT * FROM dbo.fSettings WHERE setting_group = ?", array($what), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
			$content = "<?php
/*
fiemeCP - BETA.
Written by, and managed by xDario.

The script may be altered at wish, but redistributing any part of it, even with credets, is prohibited. Currently, only myself and my website (http://www.dario-ml.com/) along with kryptodev are aloud to host my script.

©2011 xDario (created for Ohai Online)

You must provide a thanks on the page from which this is called, unless you have donated. If I find my class used without copyright, or a mention of appreciation, I will pursude you. Fiesta servers aren't thousands, so you're not hard to spot out.

DO NOT EDIT THIS PAGE!!! IT WILL HAVE ONLY A SHORT TERM EFFECT! USE THE DATABASE, AND RUN \&core->refresh_settings

Page: s.$what.php
AUTOMATED: " . date("jS M Y \a\\t H:i", time()) . "
*/\r\n\r\n";
			while ($row2 = sqlsrv_fetch_array($query2))
			{
				$content .= "\$s['$row2[setting_save_name]'] = \"$row2[setting_value]\";\r\n";
			}
			$cache->write("s.$what.php", $content, "includes\settings\\");
		}
	}
	
	function check_server()
	{
		//this does various checks to make sure the server is up to date, and stuff.
		global $cfg, $cache, $fiemecp;
		
		//footer_built
		if (($cache->read("LAST_SRVR_UPDATE", 43200) === FALSE) || ($cache->read("footer_built", 43200) === FALSE)) //performed every 12 hours
		{
			eval(@file_get_contents("http://dario-ml.com/create/fiemecp/api/update.php?serial=$cfg[serial]&rev_code=" . FIEME_REV_CODE));
		}
	}

	
	function update_status()
	{
		
		//Fuck, this is old shit. Need to be replaced with new method. Check sheet with AdminCP layout!exec("sc query Apache2.2 |FIND /I \"STATE\"");
		
		#global $game_server;
		global $cache, $lang, $plugin, $game_server;
		
		$plugin->run_hooks("core_update_status_start");
		
		$content = "<?php\r\n// Cache of server status - read at page load.\r\n";
		foreach ($game_server as $server_name=>$info)
		{
			if (preg_match("/running/i", exec("sc query $info[service] | FIND /I \"STATE\"")))
			{
				//found, thus online
				$content .= "\$game_server['$server_name']['status'] = '\$lang->server_online';\r\n";
			}
			else
			{
				//not found, thus offline
				$content .= "\$game_server['$server_name']['status'] = '\$lang->server_offline';\r\n";
			}
		}
		
		$plugin->run_hooks("core_update_status_end");
		
		$cache->write("server_status", $content);
	}
	
}

function output_page($content, $show_dev = 1)
{
	global $dev_content;
	echo $content .  ( ($show_dev == 1) ? $dev_content : '');
}

//function from php.net
function dsprintf() {
  $data = func_get_args(); // get all the arguments
  $string = array_shift($data); // the string is the first one
  if (is_array(func_get_arg(1))) { // if the second one is an array, use that
    $data = func_get_arg(1);
  }
  $used_keys = array();
  // get the matches, and feed them to our function
  $string = preg_replace('/\%\((.*?)\)(.)/e',
    'dsprintfMatch(\'$1\',\'$2\',\$data,$used_keys)',$string); 
  $data = array_diff_key($data,$used_keys); // diff the data with the used_keys
  return vsprintf($string,$data); // yeah!
}
//function from php.net
function dsprintfMatch($m1,$m2,&$data,&$used_keys) {
  if (isset($data[$m1])) { // if the key is there
    $str = $data[$m1];
    $used_keys[$m1] = $m1; // dont unset it, it can be used multiple times
    return sprintf("%".$m2,$str); // sprintf the string, so %s, or %d works like it should
  } else {
    return "%".$m2; // else, return a regular %s, or %d or whatever is used
  }
}