Guest User

Whole Code

a guest
Nov 6th, 2012
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 62.89 KB | None | 0 0
  1. <?php
  2. /*
  3. + ----------------------------------------------------------------------------+
  4. |     e107 website system
  5. |
  6. |     Copyright (C) 2001-2002 Steve Dunstan ([email protected])
  7. |     Copyright (C) 2008-2010 e107 Inc (e107.org)
  8. |
  9. |     Released under the terms and conditions of the
  10. |     GNU General Public License (http://gnu.org).
  11. |
  12. |     $URL: https://e107.svn.sourceforge.net/svnroot/e107/trunk/e107_0.7/class2.php $
  13. |     $Revision: 12996 $
  14. |     $Id: class2.php 12996 2012-10-21 08:15:31Z e107steved $
  15. |     $Author: e107steved $
  16. +----------------------------------------------------------------------------+
  17. */
  18. //
  19. // *** Code sequence for startup ***
  20. // IMPORTANT: These items are in a carefully constructed order. DO NOT REARRANGE
  21. // without checking with experienced devs! Various subtle things WILL break.
  22. //
  23. // A Get the current CPU time so we know how long all of this takes
  24. // B Remove output buffering so we are in control of text sent to user
  25. // C Remove registered globals (SECURITY for all following code)
  26. // D Setup PHP error handling (now we can see php errors ;))
  27. // E Setup other PHP essentials
  28. // F Grab e107_config to get directory paths
  29. // G Retrieve Query from URI (i.e. what are the request parameters?!)
  30. // H Initialize debug handling (NOTE: A-G cannot use debug tools!)
  31. // I: Sanity check to ensure e107_config is ok
  32. // J: MYSQL setup (NOTE: A-I cannot use database!)
  33. // K: Compatibility mode
  34. // L: Retrieve core prefs
  35. // M: Subdomain and language selection
  36. // N: Other misc setups (NOTE: Put most 'random' things here that don't require user session or theme
  37. // O: Start user session
  38. // P: Load theme
  39. // Q: Other setups
  40.  
  41. //
  42. // A: Honest global beginning point for processing time
  43. //
  44. $eTimingStart = microtime();                    // preserve these when destroying globals in step C
  45. $oblev_before_start = ob_get_level();
  46.  
  47. // Block common bad agents / queries / php issues.
  48. array_walk($_SERVER,  'e107_filter', '_SERVER');
  49. if (isset($_GET)) array_walk($_GET,     'e107_filter', '_GET');
  50. if (isset($_POST))
  51. {
  52.     array_walk($_POST,    'e107_filter', '_POST');
  53.     reset($_POST);          // Change of behaviour in PHP 5.3.17?
  54. }
  55. if (isset($_COOKIE)) array_walk($_COOKIE,  'e107_filter', '_COOKIE');
  56.  
  57. //
  58. // B: Remove all output buffering
  59. //
  60. while (@ob_end_clean());  // destroy all ouput buffering
  61. ob_start();             // start our own.
  62. $oblev_at_start = ob_get_level();   // preserve when destroying globals in step C
  63.  
  64. //
  65. // C: Find out if register globals is enabled and destroy them if so
  66. // (DO NOT use the value of any variables before this point! They could have been set by the user)
  67. //
  68. $register_globals = true;
  69. if(function_exists('ini_get')) {
  70.     $register_globals = ini_get('register_globals');
  71. }
  72.  
  73. // Destroy! (if we need to)
  74. if($register_globals == true){
  75.     while (list($global) = each($GLOBALS)) {
  76.         if (!preg_match('/^(_POST|_GET|_COOKIE|_SERVER|_FILES|GLOBALS|HTTP.*|_REQUEST|retrieve_prefs|eplug_admin|eTimingStart)|oblev_.*$/', $global)) {
  77.             unset($$global);
  78.         }
  79.     }
  80.     unset($global);
  81. }
  82.  
  83.  
  84. if(($pos = strpos(strtolower($_SERVER['PHP_SELF']), ".php/")) !== false) // redirect bad URLs to the correct one.
  85. {
  86.     $new_url = substr($_SERVER['PHP_SELF'], 0, $pos+4);
  87.     $new_loc = ($_SERVER['QUERY_STRING']) ? $new_url."?".$_SERVER['QUERY_STRING'] : $new_url;
  88.     header("Location: ".$new_loc);
  89.     exit();
  90. }
  91. // If url contains a .php in it, PHP_SELF is set wrong (imho), affecting all paths.  We need to 'fix' it if it does.
  92. $_SERVER['PHP_SELF'] = (($pos = strpos(strtolower($_SERVER['PHP_SELF']), ".php")) !== false ? substr($_SERVER['PHP_SELF'], 0, $pos+4) : $_SERVER['PHP_SELF']);
  93. unset($pos);
  94. //
  95. // D: Setup PHP error handling
  96. //    (Now we can see PHP errors) -- but note that DEBUG is not yet enabled!
  97. //
  98. $error_handler = new error_handler();
  99. set_error_handler(array(&$error_handler, "handle_error"));
  100.  
  101. //
  102. // E: Setup other essential PHP parameters
  103. //
  104. define("e107_INIT", TRUE);
  105.  
  106. // setup some php options
  107. e107_ini_set('magic_quotes_runtime',     0);
  108. e107_ini_set('magic_quotes_sybase',      0);
  109. e107_ini_set('arg_separator.output',     '&amp;');
  110. e107_ini_set('session.use_only_cookies', 1);
  111. e107_ini_set('session.use_trans_sid',    0);
  112.  
  113.  
  114.  
  115.  
  116. if(isset($retrieve_prefs) && is_array($retrieve_prefs)) {
  117.     foreach ($retrieve_prefs as $key => $pref_name) {
  118.          $retrieve_prefs[$key] = preg_replace("/\W/", '', $pref_name);
  119.     }
  120. } else {
  121.     unset($retrieve_prefs);
  122. }
  123.  
  124. define("MAGIC_QUOTES_GPC", (ini_get('magic_quotes_gpc') ? TRUE : FALSE));
  125.  
  126. // Define the domain name and subdomain name.
  127. if(is_numeric(str_replace(".","",$_SERVER['HTTP_HOST'])))
  128. {
  129.     $domain = FALSE;
  130.     $subdomain = FALSE;
  131. }
  132. else
  133. {  
  134.     if(preg_match("/\.?([a-z0-9-]+)(\.(com|net|org|co|me|ltd|plc|gov)\.[a-z]{2})$/i",$_SERVER['HTTP_HOST'],$m)) //eg. mysite.co.uk
  135.     {
  136.         $domain = $m[1].$m[2];
  137.     }
  138.     elseif(preg_match("/\.?([a-z0-9-]+)(\.[a-z]{2,})$/i",$_SERVER['HTTP_HOST'],$m))//  eg. .com/net/org/ws/biz/info
  139.     {      
  140.         $domain = $m[1].$m[2];     
  141.     }
  142.     else
  143.     {
  144.         $domain = FALSE; //invalid domain
  145.     }
  146.    
  147.     $replace = array(".".$domain,"www.","www",$domain);
  148.     $subdomain = str_replace($replace,'',$_SERVER['HTTP_HOST']);
  149. }
  150.  
  151. define("e_DOMAIN",$domain);
  152. define("e_SUBDOMAIN",($subdomain) ? $subdomain : FALSE);
  153. unset($domain,$subdomain,$replace,$m);
  154.  
  155. // ---------------------------
  156.  
  157. //  Ensure thet '.' is the first part of the include path
  158. $inc_path = explode(PATH_SEPARATOR, ini_get('include_path'));
  159. if($inc_path[0] != ".") {
  160.     array_unshift($inc_path, ".");
  161.     $inc_path = implode(PATH_SEPARATOR, $inc_path);
  162.     e107_ini_set("include_path", $inc_path);
  163. }
  164. unset($inc_path);
  165.  
  166. //
  167. // F: Grab e107_config, get directory paths and create $e107 object
  168. //
  169. @include_once(realpath(dirname(__FILE__).'/e107_config.php'));
  170.  
  171. // set debug mode in e107_config.php when admin access is unavailable
  172. if(defset('e_DEBUG')==TRUE)
  173. {
  174.     $error_handler->debug = true;
  175.     error_reporting(E_ALL);
  176. }
  177.  
  178. if(isset($CLASS2_INCLUDE) && ($CLASS2_INCLUDE!=''))
  179. {
  180.      require_once(realpath(dirname(__FILE__).'/'.$CLASS2_INCLUDE));
  181. }
  182.  
  183. if(!isset($ADMIN_DIRECTORY))
  184. {
  185.   // e107_config.php is either empty, not valid or doesn't exist so redirect to installer..
  186.   header("Location: install.php");
  187.   exit();
  188. }
  189.  
  190. //
  191. // clever stuff that figures out where the paths are on the fly.. no more need fo hard-coded e_HTTP :)
  192. //
  193. e107_require_once(realpath(dirname(__FILE__).'/'.$HANDLERS_DIRECTORY).'/e107_class.php');
  194. $e107_paths = compact('ADMIN_DIRECTORY', 'FILES_DIRECTORY', 'IMAGES_DIRECTORY', 'THEMES_DIRECTORY', 'PLUGINS_DIRECTORY', 'HANDLERS_DIRECTORY', 'LANGUAGES_DIRECTORY', 'HELP_DIRECTORY', 'DOWNLOADS_DIRECTORY');
  195. $e107 = new e107($e107_paths, realpath(dirname(__FILE__)));
  196.  
  197. $inArray = array("'", ";", "/**/", "/UNION/", "/SELECT/", "AS ");
  198. if (strpos($_SERVER['PHP_SELF'], "trackback") === false) {
  199.     foreach($inArray as $res) {
  200.         if(stristr($_SERVER['QUERY_STRING'], $res)) {
  201.             die("Access denied.");
  202.         }
  203.     }
  204. }
  205. unset($inArray);
  206.  
  207. /**
  208.  * NEW - system security levels
  209.  * Could be overridden by e107_config.php OR $CLASS2_INCLUDE script (if not set earlier)
  210.  *
  211.  * 0 (disabled)
  212.  * 5 (balanced) - token value once per session
  213.  * 8 (high) - token value regenerated on every page load
  214.  * 10 (insane) - #8 + regenerate SID on every page load
  215.  * default is 5
  216.  */
  217. if(!defined('e_SECURITY_LEVEL'))
  218. {
  219.     define('e_SECURITY_LEVEL', 5);
  220. }
  221.  
  222. /**
  223.  * G: Retrieve Query data from URI
  224.  * (Until this point, we have no idea what the user wants to do)
  225.  */
  226.  
  227. if (preg_match("#\[(.*?)](.*)#", $_SERVER['QUERY_STRING'], $matches)) {
  228.     define("e_MENU", $matches[1]);
  229.     $e_QUERY = $matches[2];
  230.     unset($matches);
  231. }
  232. else
  233. {
  234.     define("e_MENU", "");
  235.     $e_QUERY = $_SERVER['QUERY_STRING'];
  236. }
  237.  
  238. //
  239. // Start the parser; use it to grab the full query string
  240. //
  241.  
  242. e107_require_once(e_HANDLER.'e_parse_class.php');
  243. $tp = new e_parse;
  244.  
  245. $e_QUERY = str_replace(array('{', '}', '%7B', '%7b', '%7D', '%7d'), '', rawurldecode($e_QUERY));
  246. $e_QUERY = str_replace('&', '&amp;', $tp->post_toForm($e_QUERY));
  247.  
  248. /**
  249.  * e_QUERY notes:
  250.  * It seems _GET / _POST / _COOKIE are doing pre-urldecode on their data.
  251.  * There is no official documentation/php.ini setting to confirm this.
  252.  * We could add rawurlencode() after the replacement above if problems are reported.
  253.  *
  254.  * @var string
  255.  */
  256. define('e_QUERY', $e_QUERY);
  257.  
  258. //$e_QUERY = e_QUERY;
  259.  
  260. define("e_TBQS", $_SERVER['QUERY_STRING']);
  261. $_SERVER['QUERY_STRING'] = e_QUERY;
  262.  
  263. define("e_UC_PUBLIC", 0);
  264. define('e_UC_NEWUSER', 247);    // Users in 'probationary' period
  265. define('e_UC_BOTS', 246);   // Reserved to identify search bots
  266. define("e_UC_MAINADMIN", 250);
  267. define("e_UC_READONLY", 251);
  268. define("e_UC_GUEST", 252);
  269. define("e_UC_MEMBER", 253);
  270. define("e_UC_ADMIN", 254);
  271. define("e_UC_NOBODY", 255);
  272. define("ADMINDIR", $ADMIN_DIRECTORY);
  273.  
  274. /**
  275.  * H: Initialize debug handling
  276.  * (NO E107 DEBUG CONSTANTS OR CODE ARE AVAILABLE BEFORE THIS POINT)
  277.  * All debug objects and constants are defined in the debug handler
  278.  * i.e. from here on you can use E107_DEBUG_LEVEL or any
  279.  * E107_DBG_* constant for debug testing.
  280.  */
  281.  
  282. require_once(e_HANDLER.'debug_handler.php');
  283.  
  284. if(E107_DEBUG_LEVEL && isset($db_debug) && is_object($db_debug)) {
  285.     $db_debug->Mark_Time('Start: Init ErrHandler');
  286. }
  287.  
  288. //
  289. // I: Sanity check on e107_config.php
  290. //     e107_config.php upgrade check
  291. if (!$ADMIN_DIRECTORY && !$DOWNLOADS_DIRECTORY) {
  292.     message_handler("CRITICAL_ERROR", 8, ": generic, ", "e107_config.php");
  293.     exit;
  294. }
  295.  
  296. //
  297. // J: MYSQL INITIALIZATION
  298. //
  299. @require_once(e_HANDLER.'traffic_class.php');
  300. $eTraffic=new e107_traffic; // We start traffic counting ASAP
  301. $eTraffic->Calibrate($eTraffic);
  302.  
  303. define("MPREFIX", $mySQLprefix);
  304.  
  305. e107_require_once(e_HANDLER."mysql_class.php");
  306.  
  307. $sql = new db;
  308. $sql2 = new db;
  309.  
  310. $sql->db_SetErrorReporting(FALSE);
  311.  
  312. $sql->db_Mark_Time('Start: SQL Connect');
  313. $merror=$sql->db_Connect($mySQLserver, $mySQLuser, $mySQLpassword, $mySQLdefaultdb);
  314. $sql->db_Mark_Time('Start: Prefs, misc tables');
  315.  
  316. require_once(e_HANDLER.'admin_log_class.php');
  317. $admin_log = new e_admin_log();
  318.  
  319. if ($merror == "e1") {
  320.     message_handler("CRITICAL_ERROR", 6, ": generic, ", "class2.php");
  321.     exit;
  322. }
  323. else if ($merror == "e2") {
  324.     message_handler("CRITICAL_ERROR", 7, ": generic, ", "class2.php");
  325.     exit;
  326. }
  327.  
  328. //
  329. // K: Load compatability mode.
  330. //
  331. /* At a later date add a check to load e107 compat mode by $pref
  332. PHP Compatabilty should *always* be on. */
  333. e107_require_once(e_HANDLER."php_compatibility_handler.php");
  334. e107_require_once(e_HANDLER."e107_Compat_handler.php");
  335. $aj = new textparse; // required for backwards compatibility with 0.6 plugins.
  336.  
  337. //
  338. // L: Extract core prefs from the database
  339. //
  340. $sql->db_Mark_Time('Start: Extract Core Prefs');
  341. e107_require_once(e_HANDLER."pref_class.php");
  342. $sysprefs = new prefs;
  343.  
  344. e107_require_once(e_HANDLER.'cache_handler.php');
  345. e107_require_once(e_HANDLER.'arraystorage_class.php');
  346. $eArrayStorage = new ArrayData();
  347.  
  348. $PrefCache = ecache::retrieve('SitePrefs', 24 * 60, true);
  349. if(!$PrefCache){
  350.     // No cache of the prefs array, going for the db copy..
  351.     $retrieve_prefs[] = 'SitePrefs';
  352.     $sysprefs->ExtractPrefs($retrieve_prefs, TRUE);
  353.     $PrefData = $sysprefs->get('SitePrefs');
  354.     $pref = $eArrayStorage->ReadArray($PrefData);
  355.     if(!$pref){
  356.         $admin_log->log_event("CORE_LAN8", "CORE_LAN7", E_LOG_WARNING); // Core prefs error, core is attempting to
  357.         // Try for the automatic backup..
  358.         $PrefData = $sysprefs->get('SitePrefs_Backup');
  359.         $pref = $eArrayStorage->ReadArray($PrefData);
  360.         if(!$pref){
  361.             // No auto backup, try for the 'old' prefs system.
  362.             $PrefData = $sysprefs->get('pref');
  363.             $pref = unserialize($PrefData);
  364.             if(!is_array($pref)){
  365.                 message_handler("CRITICAL_ERROR", 3, __LINE__, __FILE__);
  366.                 // No old system, so point in the direction of resetcore :(
  367.                 message_handler("CRITICAL_ERROR", 4, __LINE__, __FILE__);
  368.                 $admin_log->log_event("CORE_LAN8", "CORE_LAN9", E_LOG_FATAL); // Core could not restore from automatic backup. Execution halted.
  369.                 exit;
  370.             } else {
  371.                 // old prefs found, remove old system, and update core with new system
  372.                 $PrefOutput = $eArrayStorage->WriteArray($pref);
  373.                 if(!$sql->db_Update('core', "e107_value='{$PrefOutput}' WHERE e107_name='SitePrefs'")){
  374.                     $sql->db_Insert('core', "'SitePrefs', '{$PrefOutput}'");
  375.                 }
  376.                 if(!$sql->db_Update('core', "e107_value='{$PrefOutput}' WHERE e107_name='SitePrefs_Backup'")){
  377.                     $sql->db_Insert('core', "'SitePrefs_Backup', '{$PrefOutput}'");
  378.                 }
  379.                 $sql->db_Delete('core', "`e107_name` = 'pref'");
  380.             }
  381.         } else {
  382.             message_handler("CRITICAL_ERROR", 3, __LINE__, __FILE__);
  383.             // auto backup found, use backup to restore the core
  384.             if(!$sql->db_Update('core', "`e107_value` = '".addslashes($PrefData)."' WHERE `e107_name` = 'SitePrefs'")){
  385.                 $sql->db_Insert('core', "'SitePrefs', '".addslashes($PrefData)."'");
  386.             }
  387.         }
  388.     }
  389.     // write pref cache array
  390.     $PrefCache = $eArrayStorage->WriteArray($pref, false);
  391.     // store the prefs in cache if cache is enabled
  392.     ecache::set('SitePrefs', $PrefCache);
  393. } else {
  394.     // cache of core prefs was found, so grab all the useful core rows we need
  395.     if(!isset($sysprefs->DefaultIgnoreRows)){
  396.         $sysprefs->DefaultIgnoreRows = "";
  397.     }
  398.     $sysprefs->DefaultIgnoreRows .= '|SitePrefs';
  399.     $sysprefs->prefVals['core']['SitePrefs'] = $PrefCache;
  400.     if(isset($retrieve_prefs))
  401.     {
  402.         $sysprefs->ExtractPrefs($retrieve_prefs, TRUE);
  403.     }
  404.     $pref = $eArrayStorage->ReadArray($PrefCache);
  405. }
  406.  
  407. $e107->set_base_path();
  408.  
  409. // extract menu prefs
  410. $menu_pref = unserialize(stripslashes($sysprefs->get('menu_pref')));
  411.  
  412. $sql->db_Mark_Time('(Extracting Core Prefs Done)');
  413.  
  414.  
  415. //
  416. // M: Subdomain and Language Selection
  417. //
  418. define("SITEURLBASE", ($pref['ssl_enabled'] == '1' ? "https://" : "http://").$_SERVER['HTTP_HOST']);
  419. define("SITEURL", SITEURLBASE.e_HTTP);
  420.  
  421. if(!defined('e_SELF')) // user override option
  422. {
  423.     define("e_SELF", ($pref['ssl_enabled'] == '1' ? "https://".$_SERVER['HTTP_HOST'] : "http://".$_SERVER['HTTP_HOST']) . ($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_FILENAME']));
  424. }
  425.  
  426. $page = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);
  427. define("e_PAGE", $page);
  428.      
  429. /**
  430.  * Detect if we are in the Admin Area.
  431.  * The following files are assumed to be admin areas:
  432.  * 1. Any file in the admin directory (check for non-plugin added to avoid mismatches)
  433.  * 2. any plugin file starting with 'admin_'
  434.  * 3. any plugin file in a folder called admin/
  435.  * 4. any file that specifies $eplug_admin = TRUE before class2.php is included.
  436.  */
  437. $inAdminDir = FALSE;
  438. $isPluginDir = strpos(e_SELF,'/'.$PLUGINS_DIRECTORY) !== FALSE;     // True if we're in a plugin
  439. $e107Path = str_replace($e107->base_path, "", e_SELF);              // Knock off the initial bits
  440. if  (
  441.          (!$isPluginDir && strpos($e107Path, $ADMIN_DIRECTORY) === 0 )                              // Core admin directory
  442.       || ($isPluginDir && (strpos(e_PAGE,"admin_") === 0 || strpos($e107Path, "admin/") !== FALSE)) // Plugin admin file or directory
  443.       || (varsettrue($eplug_admin))                                                                 // Admin forced
  444.     )
  445. {
  446.     $inAdminDir = TRUE;
  447. }
  448.  
  449. // -----------------------------------------
  450.  
  451. // Ensure $pref['sitelanguage'] is set if upgrading from 0.6
  452. $pref['sitelanguage'] = (isset($pref['sitelanguage']) ? $pref['sitelanguage'] : 'English');
  453.  
  454. // if a cookie name pref isn't set, make one :)
  455. if (!$pref['cookie_name']) {
  456.     $pref['cookie_name'] = "e107cookie";
  457. }
  458.  
  459. $sql->db_Mark_Time('Start: Init Language and detect changes');
  460. require_once(e_HANDLER."language_class.php");
  461. $lng = new language;
  462. $lng->detect(); // Must be before session_start(). Requires $pref, e_DOMAIN, e_MENU;
  463.  
  464. // e-Token START
  465. $sql->db_Mark_Time('Start: e-Token creation');
  466.  
  467. /**
  468.  * Set Cache Headers
  469.  * Must be set before session_start()
  470.  */
  471. if($inAdminDir || defined('e_NOCACHE'))
  472. {
  473.      session_cache_limiter('nocache'); // don't cache the html. (Should fix back-button issues)
  474. }
  475. else
  476. {
  477.     header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
  478.     header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
  479.     header("Cache-Control: post-check=0, pre-check=0",false);
  480.     session_cache_limiter("must-revalidate");  
  481. }
  482.  
  483. $SESS_NAME = strtoupper(preg_replace("/[\W_]/","",$pref['cookie_name'])); // clean-up characters.  
  484. session_name('SESS'.$SESS_NAME); // avoid session conflicts with separate sites within subdomains
  485. $doma = ((!e_SUBDOMAIN || defsettrue('MULTILANG_SUBDOMAIN')) && e_DOMAIN != FALSE) ? ".".e_DOMAIN : FALSE;
  486. session_set_cookie_params(FALSE,e_HTTP,$doma); // same cookie for www. and without
  487. unset($SESS_NAME,$doma);
  488.  
  489. // Start session after $prefs are available.
  490. session_start(); // Needs to be started after language detection (session.cookie_domain) to avoid multi-language 'access-denied' issues.
  491. header("Cache-Control: must-revalidate");  
  492. // TODO - maybe add IP as well?
  493. define('e_TOKEN_NAME', 'e107_token_'.md5($_SERVER['HTTP_HOST'].e_HTTP));
  494.  
  495. // Ajax calls should be handled manual at this time (set e_TOKEN_FREEZE in Ajax scripts before the API is loaded)
  496. if(e_SECURITY_LEVEL > 0 && session_id() && isset($_POST['e-token']) && ($_POST['e-token'] != varset($_SESSION[e_TOKEN_NAME]))/* && $_POST['ajax_used']!=1*/)
  497. {
  498.     if(defsettrue('e_DEBUG'))
  499.     {      
  500.         $details = "HOST: ".$_SERVER['HTTP_HOST']."\n";
  501.         $details .= "REQUEST_URI: ".$_SERVER['REQUEST_URI']."\n";      
  502.         $details .= "_SESSION:\n";
  503.         $details .= print_r($_SESSION,true);
  504.         $details .= "\n_POST:\n";
  505.         $details .= print_r($_POST,true);
  506.         $details .= "\nPlugins:\n";
  507.         $details .= print_r($pref['plug_installed'],true);
  508.            
  509.         $admin_log->log_event("Access denied", $details, E_LOG_WARNING); // admin access may not be possible.
  510.         echo nl2br($details);              
  511.     }  
  512.         // do not redirect, prevent dead loop, save server resources
  513.  
  514.     die('Access denied');
  515. }
  516.  
  517. // Create new token only if not exists or session id is regenerated (footer.php), respect security level
  518. if(!isset($_SESSION[e_TOKEN_NAME]) || (e_SECURITY_LEVEL >= 8 && isset($_SESSION['regenerate_'.e_TOKEN_NAME]) && !defsettrue('e_TOKEN_FREEZE')))
  519. {
  520.     // we should not break ajax calls this way
  521.     $_SESSION[e_TOKEN_NAME] = uniqid(md5(rand()), true);
  522.     // this will be reset in the end of the script (footer) if needed
  523.     unset($_SESSION['regenerate_'.e_TOKEN_NAME]);
  524. }
  525.  
  526. // use it now
  527. define('e_TOKEN', $_SESSION[e_TOKEN_NAME]);
  528.  
  529. // Debug
  530. //header('X-etoken-name: '.e_TOKEN_NAME);
  531. //header('X-etoken-value: '.e_TOKEN);
  532. //header('X-etoken-freeze: '.(defsettrue('e_TOKEN_FREEZE') ? 1 : 0));
  533.  
  534. // e-Token END
  535. // start a session if session based login is enabled
  536.  
  537. // if ($pref['user_tracking'] == "session")
  538. //{
  539. //  session_start(); // start the session, even if it won't be used for login-tracking.
  540. //}
  541.  
  542.  
  543. // if the option to force users to use a particular url for the site is enabled, redirect users there as needed
  544. // Now matches RFC 2616 (sec 3.2): case insensitive, https/:443 and http/:80 are equivalent.
  545. // And, this is robust against hack attacks. Malignant users can put **anything** in HTTP_HOST!
  546. if($pref['redirectsiteurl'] && $pref['siteurl'])
  547. {
  548.  
  549.     if(isset($pref['multilanguage_subdomain']) && $pref['multilanguage_subdomain'])
  550.     {
  551.         if(substr(e_SELF,7,4)=="www." || substr(e_SELF,8,4)=="www.")
  552.         {
  553.             $self = e_SELF;
  554.             if(e_QUERY){ $self .= "?".e_QUERY; }
  555.             $location = str_replace("://www.","://",$self);
  556.             header("Location: {$location}", true, 301); // send 301 header, not 302
  557.             exit();
  558.         }
  559.     }
  560.     else
  561.     {
  562.         // Find domain and port from user and from pref
  563.         list($urlbase,$urlport) = explode(':',$_SERVER['HTTP_HOST'].':');
  564.         if (!$urlport) { $urlport = $_SERVER['SERVER_PORT']; }
  565.         if (!$urlport) { $urlport = 80; }
  566.         $aPrefURL = explode('/',$pref['siteurl'],4);
  567.         if (count($aPrefURL) > 2) { // we can do this -- there's at least http[s]://dom.ain/whatever
  568.             $PrefRoot = $aPrefURL[2];
  569.             list($PrefSiteBase,$PrefSitePort) = explode(':',$PrefRoot.':');
  570.             if (!$PrefSitePort) {
  571.                 $PrefSitePort = ( $aPrefURL[0] == "https:" ) ? 443 : 80;    // no port so set port based on 'scheme'
  572.             }
  573.  
  574.             // Redirect only if
  575.             // -- ports do not match (http <==> https)
  576.             // -- base domain does not match (case-insensitive)
  577.             // -- NOT admin area
  578.             if (($urlport != $PrefSitePort || stripos($PrefSiteBase, $urlbase) === FALSE) && strpos(e_SELF, ADMINDIR) === FALSE)        {
  579.                 $aeSELF = explode('/',e_SELF,4);
  580.                 $aeSELF[0] = $aPrefURL[0];  // Swap in correct type of query (http, https)
  581.                 $aeSELF[1] = '';                        // Defensive code: ensure http:// not http:/<garbage>/
  582.                 $aeSELF[2] = $aPrefURL[2];  // Swap in correct domain and possibly port
  583.                 $location = implode('/',$aeSELF).(e_QUERY ? "?".e_QUERY : "");
  584.  
  585.             header("Location: {$location}", true, 301); // send 301 header, not 302
  586.             exit();
  587.         }
  588.  
  589.         }
  590.     }
  591. }
  592.  
  593. /**
  594.  * Set the User's Language
  595.  */
  596. $sql->db_Mark_Time('Start: Set User Language');
  597.  
  598. $lng->set(); // set e_LANGUAGE, USERLAN, Language Session / Cookies etc. requires $pref;
  599.  
  600. header('Content-Language: '.e_LAN);
  601.  
  602. if(varset($pref['multilanguage']) && (e_LANGUAGE != $pref['sitelanguage']))
  603. {
  604.     $sql->mySQLlanguage  = e_LANGUAGE;
  605.     $sql2->mySQLlanguage = e_LANGUAGE;
  606. }
  607.  
  608. //TODO do it only once and with the proper function
  609. include_lan(e_LANGUAGEDIR.e_LANGUAGE."/".e_LANGUAGE.".php");
  610. include_lan(e_LANGUAGEDIR.e_LANGUAGE."/".e_LANGUAGE."_custom.php");
  611.  
  612. define('e_LOCALE',(strtolower(CORE_LC)."-".strtoupper(CORE_LC2)));
  613. //
  614. // N: misc setups: online user tracking, cache
  615. //
  616. $sql -> db_Mark_Time('Start: Misc resources. Online user tracking, cache');
  617. $e_online = new e_online();
  618.  
  619. // cache class
  620. $e107cache = new ecache;
  621.  
  622.  
  623. if (isset($pref['del_unv']) && $pref['del_unv'] && $pref['user_reg_veri'] != 2)
  624. {
  625.     $threshold = intval(time() - ($pref['del_unv'] * 60));
  626.     $sql->db_Delete('user', "user_ban = 2 AND user_join < ".$threshold);
  627. }
  628.  
  629. e107_require_once(e_HANDLER.'override_class.php');
  630. $override=new override;
  631.  
  632. e107_require_once(e_HANDLER.'event_class.php');
  633. $e_event=new e107_event;
  634.  
  635. if (isset($pref['notify']) && $pref['notify'] == true)
  636. {
  637.     e107_require_once(e_HANDLER.'notify_class.php');
  638. }
  639.  
  640. //
  641. // O: Start user session
  642. //
  643. $sql -> db_Mark_Time('Start: Init session');
  644. init_session();
  645.  
  646. // for multi-language these definitions needs to come after the language loaded.
  647. define("SITENAME", trim($tp->toHTML($pref['sitename'], "", 'USER_TITLE,defs')));
  648. define("SITEBUTTON", $pref['sitebutton']);
  649. define("SITETAG", $tp->toHTML($pref['sitetag'], FALSE, "emotes_off, defs"));
  650. define("SITEDESCRIPTION", $tp->toHTML($pref['sitedescription'], "", "emotes_off,defs"));
  651. define("SITEADMIN", $pref['siteadmin']);
  652. define("SITEADMINEMAIL", $pref['siteadminemail']);
  653. define("SITEDISCLAIMER", $tp->toHTML($pref['sitedisclaimer'], "", "emotes_off,defs"));
  654. define("SITECONTACTINFO", $tp->toHTML($pref['sitecontactinfo'], TRUE, "emotes_off,defs"));
  655.  
  656. // legacy module.php file loading.
  657. if (isset($pref['modules']) && $pref['modules']) {
  658.     $mods=explode(",", $pref['modules']);
  659.     foreach ($mods as $mod) {
  660.         if (is_readable(e_PLUGIN."{$mod}/module.php")) {
  661.             require_once(e_PLUGIN."{$mod}/module.php");
  662.         }
  663.     }
  664. }
  665.  
  666.  
  667. $js_body_onload = array();          // Initialise this array in case a module wants to add to it
  668.  
  669.  
  670. // Load e_modules after all the constants, but before the themes, so they can be put to use.
  671. if(isset($pref['e_module_list']) && $pref['e_module_list']){
  672.     foreach ($pref['e_module_list'] as $mod){
  673.         if (is_readable(e_PLUGIN."{$mod}/e_module.php")) {
  674.             require_once(e_PLUGIN."{$mod}/e_module.php");
  675.         }
  676.     }
  677. }
  678.  
  679. //
  680. // P: THEME LOADING
  681. //
  682.  
  683. $sql->db_Mark_Time('Start: Load Theme');
  684.  
  685. //###########  Module redefinable functions ###############
  686. if (!function_exists('checkvalidtheme'))
  687. {
  688.     // arg1 = theme to check
  689.     function checkvalidtheme($theme_check)
  690.     {
  691.       global $ADMIN_DIRECTORY, $tp, $e107;
  692.  
  693.       if (ADMIN && strpos(e_QUERY, "themepreview") !== FALSE)
  694.       { // Theme preview
  695.             list($action, $id) = explode('.', e_QUERY);
  696.             require_once(e_HANDLER."theme_handler.php");
  697.             $themeArray = themeHandler :: getThemes("id");
  698.             define("PREVIEWTHEME", e_THEME.$themeArray[$id]."/");
  699.             define("PREVIEWTHEMENAME", $themeArray[$id]);
  700.             define("THEME", e_THEME.$themeArray[$id]."/");
  701.             define("THEME_ABS", e_THEME_ABS.$themeArray[$id]."/");
  702.             return;
  703.       }
  704.       if (@fopen(e_THEME.$theme_check."/theme.php", "r"))
  705.       {  // 'normal' theme load
  706.         define("THEME", e_THEME.$theme_check."/");
  707.         define("THEME_ABS", e_THEME_ABS.$theme_check."/");
  708.         $e107->site_theme = $theme_check;
  709.       }
  710.       else
  711.       {
  712.         function search_validtheme()
  713.         {
  714.           global $e107;
  715.           $th=substr(e_THEME, 0, -1);
  716.           $handle=opendir($th);
  717.           while ($file = readdir($handle))
  718.           {
  719.             if (is_dir(e_THEME.$file) && is_readable(e_THEME.$file.'/theme.php'))
  720.             {
  721.               closedir($handle);
  722.               $e107->site_theme = $file;
  723.               return $file;
  724.             }
  725.           }
  726.           closedir($handle);
  727.         }
  728.  
  729.         $e107tmp_theme = search_validtheme();
  730.         define("THEME", e_THEME.$e107tmp_theme."/");
  731.         define("THEME_ABS", e_THEME_ABS.$e107tmp_theme."/");
  732.         if (ADMIN && strpos(e_SELF, $ADMIN_DIRECTORY) === FALSE)
  733.         {
  734.           echo '<script>alert("'.$tp->toJS(CORE_LAN1).'")</script>';
  735.         }
  736.       }
  737.       $themes_dir = $e107->e107_dirs["THEMES_DIRECTORY"];
  738.       $e107->http_theme_dir = "{$e107->server_path}{$themes_dir}{$e107->site_theme}/";
  739.     }
  740. }
  741.  
  742. //
  743. // Q: ALL OTHER SETUP CODE
  744. //
  745. $sql->db_Mark_Time('Start: Misc Setup');
  746.  
  747. //------------------------------------------------------------------------------------------------------------------------------------//
  748. if (!class_exists('e107table'))
  749. {
  750.     class e107table
  751.     {
  752.         function tablerender($caption, $text, $mode = "default", $return = false) {
  753.             /*
  754.             # Render style table
  755.             # - parameter #1:                string $caption, caption text
  756.             # - parameter #2:                string $text, body text
  757.             # - return                                null
  758.             # - scope                                        public
  759.             */
  760.             global $override;
  761.  
  762.             if ($override_tablerender = $override->override_check('tablerender')) {
  763.                 $result=call_user_func($override_tablerender, $caption, $text, $mode, $return);
  764.  
  765.                 if ($result == "return") {
  766.                     return;
  767.                 }
  768.                 extract($result);
  769.             }
  770.  
  771.             if ($return) {
  772.                 ob_start();
  773.                 tablestyle($caption, $text, $mode);
  774.                 $ret=ob_get_contents();
  775.                 ob_end_clean();
  776.                 return $ret;
  777.             } else
  778.            
  779.        
  780.    
  781.  
  782. //#############################################################
  783.  
  784. $ns=new e107table;
  785.  
  786. $e107->ban();
  787.  
  788. if(varset($pref['force_userupdate']) && USER)
  789. {
  790.   if(force_userupdate())
  791.   {
  792.     header("Location: ".e_BASE."usersettings.php?update");
  793.     exit();
  794.   }
  795. }
  796.  
  797. $sql->db_Mark_Time('Start: Signup/splash/admin');
  798.  
  799. define("e_SIGNUP", e_BASE.(file_exists(e_BASE."customsignup.php") ? "customsignup.php" : "signup.php"));
  800.  
  801. if(!defined('e_LOGIN')) // customizable via e107_config.php
  802. {
  803.     define("e_LOGIN", e_BASE.(file_exists(e_BASE."customlogin.php") ? "customlogin.php" : "login.php"));   
  804. }
  805.  
  806.  
  807. if ($pref['membersonly_enabled'] && !USER && e_SELF != SITEURL.e_SIGNUP && e_SELF != SITEURL."index.php" && e_SELF != SITEURL."fpw.php" && e_SELF != SITEURL.e_LOGIN && strpos(e_PAGE, "admin") === FALSE && e_SELF != SITEURL.'membersonly.php' && e_SELF != SITEURL.'sitedown.php')
  808. {
  809.     header("Location: ".e_HTTP."membersonly.php");
  810.     exit();
  811. }
  812.  
  813. $sql->db_Delete("tmp", "tmp_time < ".(time() - 300)." AND tmp_ip!='data' AND tmp_ip!='submitted_link'");
  814.  
  815.  
  816.  
  817. if (varset($pref['maintainance_flag'])
  818.  && strpos(e_SELF, 'admin.php') === FALSE && strpos(e_SELF, 'sitedown.php') === FALSE && strpos(e_SELF, '/secure_img_render.php') === FALSE)
  819. {
  820.     if(!ADMIN || ($pref['maintainance_flag'] == e_UC_MAINADMIN && !getperms('0')))
  821.     {
  822.         // 307 Temporary Redirect
  823.         header('Location: '.SITEURL.'sitedown.php', TRUE, 307);
  824.         exit();
  825.     }
  826. }
  827.  
  828. $sql->db_Mark_Time('(Start: Login/logout/ban/tz)');
  829.  
  830. if (isset($_POST['userlogin']) || isset($_POST['userlogin_x'])) {
  831.     e107_require_once(e_HANDLER."login.php");
  832.     $usr = new userlogin($_POST['username'], $_POST['userpass'], $_POST['autologin']);
  833. }
  834.  
  835. if (e_QUERY == 'logout')
  836. {
  837.     $ip = $e107->getip();
  838.     $udata=(USER === TRUE) ? USERID.".".USERNAME : "0";
  839.     if (isset($pref['track_online']) && $pref['track_online'])
  840.     {
  841.         $sql->db_Update("online", "online_user_id = '0', online_pagecount=online_pagecount+1 WHERE online_user_id = '{$udata}' LIMIT 1");
  842.     }
  843.  
  844.     //if ($pref['user_tracking'] == 'session')
  845.     {
  846.         $_SESSION[$pref['cookie_name']]='';
  847.         session_destroy();
  848.     }
  849.  
  850.     cookie($pref['cookie_name'], '', (time() - 2592000));
  851.     $e_event->trigger('logout');
  852.     header('location:'.e_BASE.'index.php');
  853.     exit();
  854. }
  855.  
  856.  
  857. /*
  858. * Calculate time zone offset, based on session cookie set in e107.js.
  859. * (Buyer beware: this may be wrong for the first pageview in a session,
  860. * which is while the user is logged out, so not a problem...)
  861. *
  862. * Time offset is SECONDS. Seconds is much better than hours as a base,
  863. * as some places have 30 and 45 minute time zones.
  864. * It matches user clock time, instead of only time zones.
  865. * Add the offset to MySQL/server time to get user time.
  866. * Subtract the offset from user time to get server time.
  867. *
  868. */
  869.  
  870. $e_deltaTime=0;
  871.  
  872. if (isset($_COOKIE['e107_tdOffset'])) {
  873.     // Actual seconds of delay. See e107.js and footer_default.php
  874.     $e_deltaTime = (15*floor((($_COOKIE['e107_tdOffset'] + 450)/60)/15))*60; // Delay in seconds rounded to the nearest quarter hour
  875. }
  876.  
  877. if (isset($_COOKIE['e107_tzOffset'])) {
  878.     // Relative client-to-server time zone offset in seconds.
  879.     $e_deltaTime += (-($_COOKIE['e107_tzOffset'] * 60 + date("Z")));
  880. }
  881.  
  882. define("TIMEOFFSET", $e_deltaTime);
  883.  
  884. $sql->db_Mark_Time('Start: Get menus');
  885.  
  886. $menu_data = $e107cache->retrieve("menus_".USERCLASS_LIST."_".md5(e_LANGUAGE));
  887. $menu_data = $eArrayStorage->ReadArray($menu_data);
  888. $eMenuList=array();
  889. $eMenuActive=array();
  890. if(!is_array($menu_data)) {
  891.     if ($sql->db_Select('menus', '*', "menu_location > 0 AND menu_class IN (".USERCLASS_LIST.") ORDER BY menu_order")) {
  892.         while ($row = $sql->db_Fetch()) {
  893.             $eMenuList[$row['menu_location']][]=$row;
  894.             $eMenuActive[]=$row['menu_name'];
  895.         }
  896.     }
  897.     $menu_data['menu_list'] = $eMenuList;
  898.     $menu_data['menu_active'] = $eMenuActive;
  899.     $menu_data = $eArrayStorage->WriteArray($menu_data, false);
  900.     $e107cache->set("menus_".USERCLASS_LIST."_".md5(e_LANGUAGE), $menu_data);
  901.     unset($menu_data);
  902. } else {
  903.     $eMenuList = $menu_data['menu_list'];
  904.     $eMenuActive = $menu_data['menu_active'];
  905.     unset($menu_data);
  906. }
  907.  
  908. $sql->db_Mark_Time('(Start: Find/Load Theme)');
  909.  
  910. // Load admin Language File.
  911. if($inAdminDir == TRUE)
  912. {
  913.     include_lan(e_LANGUAGEDIR.e_LANGUAGE.'/admin/lan_admin.php');  
  914. }
  915.  
  916. if(!defined("THEME"))
  917. {
  918.     if ($inAdminDir && varsettrue($pref['admintheme'])&& (strpos(e_SELF.'?'.e_QUERY, 'menus.php?configure') === FALSE))
  919.     {
  920. /*    if (strpos(e_SELF, "newspost.php") !== FALSE)
  921.       {
  922.         define("MAINTHEME", e_THEME.$pref['sitetheme']."/");        MAINTHEME no longer used in core distribution
  923.       }  */
  924.         checkvalidtheme($pref['admintheme']);
  925.     }
  926.     elseif (USERTHEME !== FALSE && USERTHEME != "USERTHEME" && !$inAdminDir)
  927.     {
  928.         checkvalidtheme(USERTHEME);
  929.     }
  930.     else
  931.     {
  932.         checkvalidtheme($pref['sitetheme']);
  933.     }
  934. }
  935.  
  936.  
  937. // --------------------------------------------------------------
  938.  
  939.  
  940. // here we USE the theme
  941. if ($inAdminDir)
  942. {
  943.   if (file_exists(THEME.'admin_theme.php'))
  944.   {
  945.     require_once(THEME.'admin_theme.php');
  946.   }
  947.   else
  948.   {
  949.     require_once(THEME."theme.php");
  950.   }
  951. }
  952. else
  953. {
  954.   require_once(THEME."theme.php");
  955. }
  956.  
  957.  
  958.  
  959.  
  960. $exclude_lan = array("lan_signup.php");  // required for multi-language.
  961.  
  962. //TODO remove autoload
  963. if ($inAdminDir)
  964. {
  965.   include_lan(e_LANGUAGEDIR.e_LANGUAGE."/admin/lan_".e_PAGE);
  966. }
  967. elseif (!in_array("lan_".e_PAGE,$exclude_lan) && !$isPluginDir)
  968. {
  969.   include_lan(e_LANGUAGEDIR.e_LANGUAGE."/lan_".e_PAGE);
  970. }
  971.  
  972.  
  973.  
  974.  
  975. if(!defined("IMODE")) define("IMODE", "lite");
  976.  
  977. if ($pref['anon_post'] ? define("ANON", TRUE) : define("ANON", FALSE));
  978.  
  979. if (Empty($pref['newsposts']) ? define("ITEMVIEW", 15) : define("ITEMVIEW", $pref['newsposts']));
  980.  
  981. if ($pref['antiflood1'] == 1)
  982. {
  983.   define('FLOODPROTECT', TRUE);
  984.   define('FLOODTIMEOUT', max(varset($pref['antiflood_timeout'],10),3));
  985. }
  986. else
  987. {
  988.   define('FLOODPROTECT', FALSE);
  989. }
  990.  
  991. $layout = isset($layout) ? $layout : '_default';
  992. define("HEADERF", e_THEME."templates/header{$layout}.php");
  993. define("FOOTERF", e_THEME."templates/footer{$layout}.php");
  994.  
  995. if (!file_exists(HEADERF)) {
  996.     message_handler("CRITICAL_ERROR", "Unable to find file: ".HEADERF, __LINE__ - 2, __FILE__);
  997. }
  998.  
  999. if (!file_exists(FOOTERF)) {
  1000.     message_handler("CRITICAL_ERROR", "Unable to find file: ".FOOTERF, __LINE__ - 2, __FILE__);
  1001. }
  1002.  
  1003. define("LOGINMESSAGE", "");
  1004. define("OPEN_BASEDIR", (ini_get('open_basedir') ? TRUE : FALSE));
  1005. define("SAFE_MODE", (ini_get('safe_mode') ? TRUE : FALSE));
  1006. define("FILE_UPLOADS", (ini_get('file_uploads') ? TRUE : FALSE));
  1007. define("INIT", TRUE);
  1008. if(isset($_SERVER['HTTP_REFERER'])) {
  1009.     $tmp = explode("?", $_SERVER['HTTP_REFERER']);
  1010.     define("e_REFERER_SELF",($tmp[0] == e_SELF));
  1011. } else {
  1012.     define('e_REFERER_SELF', FALSE);
  1013. }
  1014.  
  1015. if (!class_exists('convert'))
  1016. {
  1017.     require_once(e_HANDLER."date_handler.php");
  1018. }
  1019.  
  1020.  
  1021.  
  1022.  
  1023.  
  1024. //@require_once(e_HANDLER."IPB_int.php");
  1025. //@require_once(e_HANDLER."debug_handler.php");
  1026. //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
  1027. function js_location($qry){
  1028.     global $error_handler;
  1029.     if (count($error_handler->errors)) {
  1030.         echo $error_handler->return_errors();
  1031.         exit;
  1032.     } else {
  1033.         echo "<script type='text/javascript'>document.location.href='{$qry}'</script>\n"; exit;
  1034.     }
  1035. }
  1036.  
  1037. function check_email($email) {
  1038.     return preg_match("/^([_a-zA-Z0-9-+]+)(\.[_a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+)(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,6})$/" , $email) ? $email : FALSE;
  1039. }
  1040.  
  1041. //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
  1042.  
  1043. /**
  1044.  *
  1045.  * @param mixed $var
  1046.  * @param string $userclass
  1047.  * @param mixed $peer
  1048.  * @param boolean $debug
  1049.  * @return boolean
  1050.  */
  1051. function check_class($var, $userclass = USERCLASS, $peer = FALSE, $debug = FALSE)
  1052. {
  1053.     global $tp,$pref;
  1054.     if($var == e_LANGUAGE){
  1055.         return TRUE;
  1056.     }
  1057.  
  1058.     if (is_numeric($var) && !$var) return TRUE;     // Accept numeric class zero - 'PUBLIC'
  1059.  
  1060.     if (!$var || $var == '')
  1061.     {   // ....but an empty string or NULL variable is not valid
  1062.         return FALSE;
  1063.     }
  1064.  
  1065.     if(strpos($var, ',') !== FALSE)
  1066.     {
  1067.         $lans = explode(',', e_LANLIST);
  1068.         $varList = explode(',', $var);
  1069.         rsort($varList); // check the language first.(ie. numbers come last)
  1070.         foreach($varList as $v)
  1071.         {
  1072.             if (in_array($v,$lans) && strpos($v, e_LANGUAGE) === FALSE) {
  1073.                 return FALSE;
  1074.             }
  1075.  
  1076.             if(check_class($v, $userclass, $debug)) {
  1077.                 return TRUE;
  1078.             }
  1079.         }
  1080.         return FALSE;
  1081.     }
  1082.    
  1083.     //if peer is array, assume it's a user record
  1084.     if(is_array($peer)) {
  1085.         $_adminperms = ($peer['user_admin'] === 1 ? $peer['user_perms'] : '');
  1086.         $_user = true;
  1087.         $_admin = $peer['user_admin'] === 1;
  1088.         $peer = false;
  1089.         $_userjoined = $peer['user_joined'];
  1090.     } else {
  1091.         $_adminperms = defined('ADMINPERMS') ? ADMINPERMS : '';
  1092.         $_user = USER;
  1093.         $_admin = ADMIN;
  1094.         $_userjoined = USERJOINED;
  1095.     }
  1096.  
  1097.     //Test 'special' userclass numbers
  1098.     if (preg_match("/^([0-9]+)$/", $var) && !$peer)
  1099.     {
  1100.         if ($var == e_UC_MAINADMIN && getperms('0', $_adminperms))
  1101.         {
  1102.             return TRUE;
  1103.         }
  1104.         //&& $_admin == FALSE
  1105.         if ($var == e_UC_NEWUSER  && (time() < ($_userjoined + (varset($pref['user_new_period'],0)*86400))))
  1106.         {
  1107.             return TRUE;
  1108.         }
  1109.  
  1110.         if ($var == e_UC_MEMBER && $_user == TRUE)
  1111.         {
  1112.             return TRUE;
  1113.         }
  1114.  
  1115.         if ($var == e_UC_GUEST && $_user == FALSE) {
  1116.             return TRUE;
  1117.         }
  1118.  
  1119.         if ($var == e_UC_PUBLIC) {
  1120.             return TRUE;
  1121.         }
  1122.  
  1123.         if ($var == e_UC_NOBODY) {
  1124.             return FALSE;
  1125.         }
  1126.  
  1127.         if ($var == e_UC_ADMIN && $_admin) {
  1128.             return TRUE;
  1129.         }
  1130.         if ($var == e_UC_READONLY) {
  1131.             return TRUE;
  1132.         }
  1133.     }
  1134.  
  1135.     if ($debug) {
  1136.         echo "USERCLASS: ".$userclass.", \$var = $var : ";
  1137.     }
  1138.  
  1139.     if (!defined("USERCLASS") || $userclass == "") {
  1140.         if ($debug) {
  1141.             echo "FALSE<br />";
  1142.         }
  1143.         return FALSE;
  1144.     }
  1145.  
  1146.     // user has classes set - continue
  1147.     if (preg_match("/^([0-9]+)$/", $var)) {
  1148.         $tmp=explode(',', $userclass);
  1149.         if (is_numeric(array_search($var, $tmp))) {
  1150.             if ($debug) {
  1151.                 echo "TRUE<br />";
  1152.             }
  1153.             return TRUE;
  1154.         }
  1155.     } else {
  1156.         // var is name of class ...
  1157.         $sql=new db;
  1158.         if ($sql->db_Select("userclass_classes", "*", "userclass_name='".$tp -> toDB($var)."' ")) {
  1159.             $row=$sql->db_Fetch();
  1160.             $tmp=explode(',', $userclass);
  1161.             if (is_numeric(array_search($row['userclass_id'], $tmp))) {
  1162.                 if ($debug) {
  1163.                     echo "TRUE<br />";
  1164.                 }
  1165.                 return TRUE;
  1166.             }
  1167.         }
  1168.     }
  1169.  
  1170.     if ($debug) {
  1171.         echo "NOTNUM! FALSE<br />";
  1172.     }
  1173.  
  1174.     return FALSE;
  1175. }
  1176.  
  1177. function getperms($arg, $ap = ADMINPERMS)
  1178. {
  1179.     global $PLUGINS_DIRECTORY;
  1180.    
  1181.     if(!ADMIN)
  1182.     {
  1183.         return FALSE;
  1184.     }
  1185.     if ($ap == "0")
  1186.     {
  1187.         return TRUE;
  1188.     }
  1189.     if ($ap == "")
  1190.     {
  1191.         return FALSE;
  1192.     }
  1193.     $ap='.'.$ap;
  1194.     if ($arg == 'P' && preg_match("#(.*?)/".$PLUGINS_DIRECTORY."(.*?)/(.*?)#", e_SELF, $matches))
  1195.     {
  1196.         $psql=new db;
  1197.         if ($psql->db_Select('plugin', 'plugin_id', "plugin_path = '".$matches[2]."' "))
  1198.         {
  1199.             $row=$psql->db_Fetch();
  1200.             $arg='P'.$row[0];
  1201.         }
  1202.     }
  1203.     if (strpos($ap, ".".$arg.".") !== FALSE)
  1204.     {
  1205.         return TRUE;
  1206.     }
  1207.     else
  1208.     {
  1209.         return FALSE;
  1210.     }
  1211. }
  1212.  
  1213. /**
  1214.  * Get the user data from user and user_extended tables
  1215.  *
  1216.  * @return array
  1217.  */
  1218. function get_user_data($uid, $extra = "")
  1219. {
  1220.     global $pref, $sql;
  1221.     $uid = intval($uid);
  1222.     $var = array();
  1223.     if($uid == 0) { return $var; }
  1224.     if($ret = getcachedvars("userdata_{$uid}"))
  1225.     {
  1226.         return $ret;
  1227.     }
  1228.  
  1229.     $qry = "
  1230.     SELECT u.*, ue.* FROM #user AS u
  1231.     LEFT JOIN #user_extended AS ue ON ue.user_extended_id = u.user_id
  1232.     WHERE u.user_id = {$uid} {$extra}
  1233.     ";
  1234.     if (!$sql->db_Select_gen($qry))
  1235.     {
  1236.         $qry = "SELECT * FROM #user AS u WHERE u.user_id = {$uid} {$extra}";
  1237.         if(!$sql->db_Select_gen($qry))
  1238.         {
  1239.             return FALSE;
  1240.         }
  1241.     }
  1242.  
  1243.     $var = $sql->db_Fetch(MYSQL_ASSOC);
  1244.     $extended_struct = getcachedvars("extended_struct");
  1245.     if(!$extended_struct)
  1246.     {
  1247.         unset($extended_struct);
  1248.         $qry = "SHOW COLUMNS FROM #user_extended ";
  1249.         if($sql->db_Select_gen($qry))
  1250.         {
  1251.             while($row = $sql->db_Fetch(MYSQL_ASSOC))
  1252.             {
  1253.                 if($row['Default'] != "")
  1254.                 {
  1255.                     $extended_struct[] = $row;
  1256.                 }
  1257.             }
  1258.             if(isset($extended_struct))
  1259.             {
  1260.                 cachevars("extended_struct", $extended_struct);
  1261.             }
  1262.         }
  1263.     }
  1264.  
  1265.     if(isset($extended_struct))
  1266.     {
  1267.         foreach($extended_struct as $row)
  1268.         {
  1269.             if($row['Default'] != "" && ($var[$row['Field']] == NULL || $var[$row['Field']] == "" ))
  1270.             {
  1271.                 $var[$row['Field']] = $row['Default'];
  1272.             }
  1273.         }
  1274.     }
  1275.     if ($var['user_perms'] == '0.') $var['user_perms'] = '0';       // Handle some legacy situations
  1276.     cachevars("userdata_{$uid}", $var);
  1277.     return $var;
  1278. }
  1279.  
  1280. //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
  1281.  
  1282. function save_prefs($table = 'core', $uid = USERID, $row_val = '')
  1283. {
  1284.   global $pref, $user_pref, $tp, $PrefCache, $sql, $eArrayStorage;
  1285.   if ($table == 'core')
  1286.   {
  1287.     if ($row_val == '')
  1288.     {       // Save old version as a backup first
  1289.       $sql->db_Select_gen("REPLACE INTO `#core` (e107_name,e107_value) values ('SitePrefs_Backup', '".addslashes($PrefCache)."') ");
  1290.  
  1291.       // Now save the updated values
  1292.       // traverse the pref array, with toDB on everything
  1293.       $_pref = $tp -> toDB($pref, true, true, 'pReFs');
  1294.       // Create the data to be stored
  1295.       $sql->db_Select_gen("REPLACE INTO `#core` (e107_name,e107_value) values ('SitePrefs', '".$eArrayStorage->WriteArray($_pref)."') ");
  1296.       ecache::clear('SitePrefs');
  1297.     }
  1298.   }
  1299.   else
  1300.   {
  1301.     $_user_pref = $tp -> toDB($user_pref);
  1302.     $tmp=addslashes(serialize($_user_pref));
  1303.     $sql->db_Update("user", "user_prefs='$tmp' WHERE user_id=".intval($uid));
  1304.     return $tmp;
  1305.   }
  1306. }
  1307.  
  1308. //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
  1309. class e_online {
  1310.     function online($online_tracking = false, $flood_control = false) {
  1311.         if($online_tracking == true || $flood_control == true)
  1312.         {
  1313.             global $online_timeout, $online_warncount, $online_bancount;
  1314.             if(!isset($online_timeout)) {
  1315.                 $online_timeout = 300;
  1316.             }
  1317.             if(!isset($online_warncount)) {
  1318.                 $online_warncount = 90;
  1319.             }
  1320.             if(!isset($online_bancount)) {
  1321.                 $online_bancount = 100;
  1322.             }
  1323.             global $sql, $pref, $e107, $listuserson, $e_event, $tp;
  1324.             $page = (strpos(e_SELF, "forum_") !== FALSE) ? e_SELF.".".e_QUERY : e_SELF;
  1325.             $page = (strpos(e_SELF, "comment") !== FALSE) ? e_SELF.".".e_QUERY : $page;
  1326.             $page = (strpos(e_SELF, "content") !== FALSE) ? e_SELF.".".e_QUERY : $page;
  1327.             $page = $tp -> toDB($page, true);
  1328.  
  1329.             $ip = $e107->getip();
  1330.             $udata = (USER === true ? USERID.".".USERNAME : "0");
  1331.  
  1332.             if (USER)
  1333.             {
  1334.                 // Find record that matches IP or visitor, or matches user info
  1335.                 if ($sql->db_Select("online", "*", "(`online_ip` = '{$ip}' AND `online_user_id` = '0') OR `online_user_id` = '{$udata}'")) {
  1336.                     $row = $sql->db_Fetch();
  1337.  
  1338.                     if ($row['online_user_id'] == $udata) {
  1339.                         //Matching user record
  1340.                         if ($row['online_timestamp'] < (time() - $online_timeout)) {
  1341.                             //It has been at least 'timeout' seconds since this user has connected
  1342.                             //Update user record with timestamp, current IP, current page and set pagecount to 1
  1343.                             $query = "online_timestamp='".time()."', online_ip='{$ip}', online_location='{$page}', online_pagecount=1 WHERE online_user_id='{$row['online_user_id']}' LIMIT 1";
  1344.                         } else {
  1345.                             if (!ADMIN) {
  1346.                                 $row['online_pagecount'] ++;
  1347.                             }
  1348.                             // Update user record with current IP, current page and increment pagecount
  1349.                             $query = "online_ip='{$ip}', `online_location` = '{$page}', `online_pagecount` = '".intval($row['online_pagecount'])."' WHERE `online_user_id` = '{$row['online_user_id']}' LIMIT 1";
  1350.                         }
  1351.                     } else {
  1352.                         //Found matching visitor record (ip only) for this user
  1353.                         if ($row['online_timestamp'] < (time() - $online_timeout)) {
  1354.                             // It has been at least 'timeout' seconds since this user has connected
  1355.                             // Update record with timestamp, current IP, current page and set pagecount to 1
  1356.                             $query = "`online_timestamp` = '".time()."', `online_user_id` = '{$udata}', `online_location` = '{$page}', `online_pagecount` = 1 WHERE `online_ip` = '{$ip}' AND `online_user_id` = '0' LIMIT 1";
  1357.                         } else {
  1358.                             if (!ADMIN) {
  1359.                                 $row['online_pagecount'] ++;
  1360.                             }
  1361.                             //Update record with current IP, current page and increment pagecount
  1362.                             $query = "`online_user_id` = '{$udata}', `online_location` = '{$page}', `online_pagecount` = ".intval($row['online_pagecount'])." WHERE `online_ip` = '{$ip}' AND `online_user_id` = '0' LIMIT 1";
  1363.                         }
  1364.                     }
  1365.                     $sql->db_Update("online", $query);
  1366.                 } else {
  1367.                     $sql->db_Insert("online", " '".time()."', '0', '{$udata}', '{$ip}', '{$page}', 1, 0");
  1368.                 }
  1369.             }
  1370.             else
  1371.             {
  1372.                 //Current page request is from a visitor
  1373.                 if ($sql->db_Select("online", "*", "`online_ip` = '{$ip}' AND `online_user_id` = '0'")) {
  1374.                     $row = $sql->db_Fetch();
  1375.  
  1376.                     if ($row['online_timestamp'] < (time() - $online_timeout)) //It has been at least 'timeout' seconds since this ip has connected
  1377.                     {
  1378.                         //Update record with timestamp, current page, and set pagecount to 1
  1379.                         $query = "`online_timestamp` = '".time()."', `online_location` = '{$page}', `online_pagecount` = 1 WHERE `online_ip` = '{$ip}' AND `online_user_id` = '0' LIMIT 1";
  1380.                     } else {
  1381.                         //Update record with current page and increment pagecount
  1382.                         $row['online_pagecount'] ++;
  1383.                         //   echo "here {$online_pagecount}";
  1384.                         $query="`online_location` = '{$page}', `online_pagecount` = {$row['online_pagecount']} WHERE `online_ip` = '{$ip}' AND `online_user_id` = '0' LIMIT 1";
  1385.                     }
  1386.                     $sql->db_Update("online", $query);
  1387.                 } else {
  1388.                     $sql->db_Insert("online", " '".time()."', '0', '0', '{$ip}', '{$page}', 1, 0");
  1389.                 }
  1390.             }
  1391.  
  1392.         if (ADMIN || ($pref['autoban'] != 1 && $pref['autoban'] != 2) || (!isset($row['online_pagecount']))) // Auto-Ban is switched off. (0 or 3)
  1393.             {
  1394.                 $row['online_pagecount'] = 1;
  1395.             }
  1396.  
  1397.             if ($row['online_pagecount'] > $online_bancount && ($row['online_ip'] != "127.0.0.1"))
  1398.             {
  1399.                 include_lan(e_LANGUAGEDIR.e_LANGUAGE.'/admin/lan_banlist.php');
  1400.                 $sql->db_Insert('banlist', "'{$ip}', '0', '".str_replace('--HITS--',$row['online_pagecount'],BANLAN_78)."' ");
  1401.                 $e_event->trigger("flood", $ip);
  1402.                 exit();
  1403.             }
  1404.             if ($row['online_pagecount'] >= $online_warncount && $row['online_ip'] != "127.0.0.1") {
  1405.                 echo "<div style='text-align:center; font: 11px verdana, tahoma, arial, helvetica, sans-serif;'><b>".LAN_WARNING."</b><br /><br />".CORE_LAN6."<br /></div>";
  1406.                 exit();
  1407.             }
  1408.  
  1409.             $sql->db_Delete("online", "`online_timestamp` < ".(time() - $online_timeout));
  1410.  
  1411.             global $members_online, $total_online, $member_list, $listuserson;
  1412.             $total_online = $sql->db_Count("online");
  1413.             if ($members_online = $sql->db_Select("online", "*", "online_user_id != '0' ")) {
  1414.                 $member_list = '';
  1415.                 $listuserson = array();
  1416.                 while ($row = $sql->db_Fetch()) {
  1417.                     $vals = explode(".", $row['online_user_id'], 2);
  1418.                     $member_list .= "<a href='".e_BASE."user.php?id.{$vals[0]}'>{$vals[1]}</a> ";
  1419.                     $listuserson[$row['online_user_id']] = $row['online_location'];
  1420.                 }
  1421.             }
  1422.             define("TOTAL_ONLINE", $total_online);
  1423.             define("MEMBERS_ONLINE", $members_online);
  1424.             define("GUESTS_ONLINE", $total_online - $members_online);
  1425.             define("ON_PAGE", $sql->db_Count("online", "(*)", "WHERE `online_location` = '{$page}' "));
  1426.             define("MEMBER_LIST", $member_list);
  1427.         }
  1428.         else
  1429.         {
  1430.             define("e_TRACKING_DISABLED", true);
  1431.             define("TOTAL_ONLINE", "");
  1432.             define("MEMBERS_ONLINE", "");
  1433.             define("GUESTS_ONLINE", "");
  1434.             define("ON_PAGE", "");
  1435.             define("MEMBER_LIST", ""); //
  1436.         }
  1437.     }
  1438. }
  1439. //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
  1440. function cachevars($id, $var) {
  1441.     global $cachevar;
  1442.     $cachevar[$id]=$var;
  1443. }
  1444.  
  1445. function getcachedvars($id) {
  1446.     global $cachevar;
  1447.     return (isset($cachevar[$id]) ? $cachevar[$id] : false);
  1448. }
  1449.  
  1450. //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
  1451. class floodprotect {
  1452.     function flood($table, $orderfield) {
  1453.         /*
  1454.         # Test for possible flood
  1455.         #
  1456.         # - parameter #1                string $table, table being affected
  1457.         # - parameter #2                string $orderfield, date entry in respective table
  1458.         # - return                                boolean
  1459.         # - scope                                        public
  1460.         */
  1461.         $sql=new db;
  1462.  
  1463.         if (FLOODPROTECT == TRUE) {
  1464.             $sql->db_Select($table, "*", "ORDER BY ".$orderfield." DESC LIMIT 1", "no_where");
  1465.             $row=$sql->db_Fetch();
  1466.             return ($row[$orderfield] > (time() - FLOODTIMEOUT) ? FALSE : TRUE);
  1467.         } else {
  1468.             return TRUE;
  1469.         }
  1470.     }
  1471. }
  1472.  
  1473. //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
  1474. //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
  1475. function init_session() {
  1476.     /*
  1477.     # Validate user
  1478.     #
  1479.     # - parameters none
  1480.     # - return boolean
  1481.     # - scope public
  1482.     */
  1483.     global $sql, $pref, $user_pref, $tp, $currentUser, $e107;
  1484.  
  1485.     define('USERIP', $e107->getip());
  1486.     if (!isset($_COOKIE[$pref['cookie_name']]) && !isset($_SESSION[$pref['cookie_name']]))
  1487.     {
  1488.         setGuest();
  1489.     }
  1490.     else
  1491.     {
  1492.         list($uid, $upw)=(isset($_COOKIE[$pref['cookie_name']]) && $_COOKIE[$pref['cookie_name']] ? explode(".", $_COOKIE[$pref['cookie_name']]) : explode(".", $_SESSION[$pref['cookie_name']]));
  1493.  
  1494.         if (empty($uid) || empty($upw))
  1495.         {
  1496.             cookie($pref['cookie_name'], "", (time() - 2592000));
  1497.             $_SESSION[$pref['cookie_name']] = "";
  1498.             session_destroy();
  1499.             setGuest();
  1500.             define('USERCLASS_LIST', class_list());
  1501.             define('LOGINMESSAGE',CORE_LAN10.'<br /><br />');
  1502.             return (FALSE);
  1503.         }
  1504.  
  1505.         $result = get_user_data($uid);
  1506.         if(is_array($result) && (md5($result['user_password']) == $upw) && ($result['user_ban'] == 0))
  1507.         {
  1508.             define('USER', TRUE);
  1509.             define('USERID', $result['user_id']);
  1510.             define('USERNAME', $result['user_name']);
  1511.             define('USERURL', (isset($result['user_homepage']) ? $result['user_homepage'] : false));
  1512.             define('USEREMAIL', $result['user_email']);
  1513.             define('USERCLASS', $result['user_class']);
  1514.             define('USERREALM', $result['user_realm']);
  1515.             define('USERVIEWED', $result['user_viewed']);
  1516.             define('USERVISITS', $result['user_visits']);
  1517.             define('USERIMAGE', $result['user_image']);
  1518.             define('USERSESS', $result['user_sess']);
  1519.             define('USERJOINED', $result['user_join']);
  1520.  
  1521.             $update_ip = ($result['user_ip'] != USERIP ? ", user_ip = '".USERIP."'" : "");
  1522.  
  1523.             if($result['user_currentvisit'] + 3600 < time() || !$result['user_lastvisit'])
  1524.             {   // New visit
  1525.                 $result['user_lastvisit'] = $result['user_currentvisit'];
  1526.                 $result['user_currentvisit'] = time();
  1527.                 $sql->db_Update('user', "user_visits = user_visits + 1, user_lastvisit = '{$result['user_lastvisit']}', user_currentvisit = '{$result['user_currentvisit']}', user_viewed = ''{$update_ip} WHERE user_id=".USERID);
  1528.             }
  1529.             else
  1530.             {
  1531.                 $result['user_currentvisit'] = time();
  1532.                 $sql->db_Update('user', "user_currentvisit = '{$result['user_currentvisit']}'{$update_ip} WHERE user_id=".USERID);
  1533.             }
  1534.  
  1535.             $currentUser = $result;
  1536.             $currentUser['user_realname'] = $result['user_login']; // Used by force_userupdate
  1537.             define('USERLV', $result['user_lastvisit']);
  1538.  
  1539.             if ($result['user_admin'])
  1540.             {
  1541.                 define('ADMIN', TRUE);
  1542.                 define('ADMINID', $result['user_id']);
  1543.                 define('ADMINNAME', $result['user_name']);
  1544.                 define('ADMINPERMS', $result['user_perms']);
  1545.                 define('ADMINEMAIL', $result['user_email']);
  1546.                 define('ADMINPWCHANGE', $result['user_pwchange']);
  1547.             }
  1548.             else
  1549.             {
  1550.                 define('ADMIN', FALSE);
  1551.             }
  1552.  
  1553.             $user_pref = unserialize($result['user_prefs']);
  1554.  
  1555.             $tempClasses = class_list();
  1556.             if (check_class(varset($pref['allow_theme_select'],FALSE), $tempClasses))
  1557.             {   // User can set own theme
  1558.                 if (isset($_POST['settheme']))
  1559.                 {
  1560.                     $user_pref['sitetheme'] = ($pref['sitetheme'] == $_POST['sitetheme'] ? "" : $_POST['sitetheme']);
  1561.                     save_prefs('user');
  1562.                 }
  1563.             }
  1564.             elseif (isset($user_pref['sitetheme']))
  1565.             {   // User obviously no longer allowed his own theme - clear it
  1566.                 unset($user_pref['sitetheme']);
  1567.                 save_prefs('user');
  1568.             }
  1569.  
  1570.  
  1571.             define("USERTHEME", (isset($user_pref['sitetheme']) && file_exists(e_THEME.$user_pref['sitetheme']."/theme.php") ? $user_pref['sitetheme'] : FALSE));
  1572. //          global $ADMIN_DIRECTORY, $PLUGINS_DIRECTORY;   Don't look very necessary
  1573.         }
  1574.         else
  1575.         {
  1576.             setGuest();
  1577.             define('CORRUPT_COOKIE', TRUE);
  1578.         }
  1579.     }
  1580.  
  1581.     define('USERCLASS_LIST', class_list());
  1582.     define('e_CLASS_REGEXP', "(^|,)(".str_replace(",", "|", USERCLASS_LIST).")(,|$)");
  1583. //
  1584. //  if(USER)
  1585. //  {
  1586. //      define('POST_REFERER', md5($currentUser['user_password'].$currentUser['user_lastvisit'].USERCLASS_LIST));
  1587. //  }
  1588. //  else
  1589. //  {
  1590. //      define('POST_REFERER', '');
  1591. //  }
  1592. //  if(isset($_POST['__referer']) && $_POST['__referer'] != POST_REFERER) {
  1593. //      header('location:'.e_BASE.'index.php');
  1594. //      exit;
  1595. //  }
  1596. }
  1597.  
  1598.  
  1599. /**
  1600.  *  Set all the defines appropriate to a guest (visitor or user who isn't logged in)
  1601.  */
  1602. function setGuest()
  1603. {
  1604.     define('USER', FALSE);
  1605.     define('ADMIN', FALSE);
  1606.     define('GUEST', TRUE);
  1607.     define('USERID', 0);
  1608.     define('USERTHEME', FALSE);
  1609.     define('USERCLASS', '');
  1610.     define('USEREMAIL', '');
  1611.     define('USERURL', '');
  1612.     define('USEREMAIL', '');
  1613.     define('USERREALM', '');
  1614.     define('USERVIEWED', '');
  1615.     define('USERIMAGE', '');
  1616.     define('USERSESS', '');
  1617. }
  1618.  
  1619.  
  1620.  
  1621. $sql->db_Mark_Time('Start: Go online');
  1622. if(isset($pref['track_online']) && $pref['track_online']) {
  1623.     $e_online->online($pref['track_online'], $pref['flood_protect']);
  1624. }
  1625.  
  1626. function cookie($name, $value, $expire=0, $path = e_HTTP, $domain = "", $secure = 0)
  1627. {
  1628.     if(!e_SUBDOMAIN || (defined('MULTILANG_SUBDOMAIN') && MULTILANG_SUBDOMAIN === TRUE))
  1629.     {
  1630.         $domain = (e_DOMAIN != FALSE) ? ".".e_DOMAIN : "";
  1631.     }
  1632.  
  1633.     setcookie($name, $value, $expire, $path, $domain, $secure);
  1634. }
  1635.  
  1636. //
  1637. // Use these to combine isset() and use of the set value. or defined and use of a constant
  1638. // i.e. to fix  if($pref['foo']) ==> if ( varset($pref['foo']) ) will use the pref, or ''.
  1639. // Can set 2nd param to any other default value you like (e.g. false, 0, or whatever)
  1640. // $testvalue adds additional test of the value (not just isset())
  1641. // Examples:
  1642. // $something = pref;  // Bug if pref not set         ==> $something = varset(pref);
  1643. // $something = isset(pref) ? pref : "";              ==> $something = varset(pref);
  1644. // $something = isset(pref) ? pref : default;         ==> $something = varset(pref,default);
  1645. // $something = isset(pref) && pref ? pref : default; ==> use varsettrue(pref,default)
  1646. //
  1647. function varset(&$val,$default='') {
  1648.     if (isset($val)) {
  1649.         return $val;
  1650.     }
  1651.     return $default;
  1652. }
  1653. function defset($str,$default='') {
  1654.     if (defined($str)) {
  1655.         return constant($str);
  1656.     }
  1657.     return $default;
  1658. }
  1659.  
  1660. //
  1661. // These variants are like the above, but only return the value if both set AND 'true'
  1662. //
  1663. function varsettrue(&$val,$default='') {
  1664.     if (isset($val) && $val) return $val;
  1665.     return $default;
  1666. }
  1667. function defsettrue($str,$default='') {
  1668.     if (defined($str) && constant($str)) return constant($str);
  1669.     return $default;
  1670. }
  1671.  
  1672. //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
  1673. function message_handler($mode, $message, $line = 0, $file = "") {
  1674.     e107_require_once(e_HANDLER."message_handler.php");
  1675.     show_emessage($mode, $message, $line, $file);
  1676. }
  1677.  
  1678. // -----------------------------------------------------------------------------
  1679. function table_exists($check) {
  1680.     if (!$GLOBALS['mySQLtablelist']) {
  1681.         $tablist=mysql_list_tables($GLOBALS['mySQLdefaultdb']);
  1682.         while (list($temp) = mysql_fetch_array($tablist)) {
  1683.             $GLOBALS['mySQLtablelist'][] = $temp;
  1684.         }
  1685.     }
  1686.  
  1687.     $mltable=MPREFIX.strtolower($check);
  1688.  
  1689.     foreach ($GLOBALS['mySQLtablelist'] as $lang) {
  1690.         if (strpos($lang, $mltable) !== FALSE) {
  1691.             return TRUE;
  1692.         }
  1693.     }
  1694. }
  1695.  
  1696. function class_list($uid = '') {
  1697.     $clist=array();
  1698.  
  1699.     if ($uid == '')
  1700.     {
  1701.         if (USER === TRUE)
  1702.         {
  1703.             if(USERCLASS)
  1704.             {
  1705.                 $clist=explode(',', USERCLASS);
  1706.             }
  1707.             $clist[]=e_UC_MEMBER;
  1708.             if (ADMIN === TRUE) {
  1709.                 $clist[] = e_UC_ADMIN;
  1710.             }
  1711.             if (getperms('0')) {
  1712.               $clist[] = e_UC_MAINADMIN;
  1713.             }
  1714.         } else {
  1715.             $clist[] = e_UC_GUEST;
  1716.         }
  1717.         $clist[]=e_UC_READONLY;
  1718.         $clist[]=e_UC_PUBLIC;
  1719.         return implode(',', $clist);
  1720.     }
  1721. }
  1722.  
  1723. // ---------------------------------------------------------------------------
  1724. function e107_include($fname) {
  1725.     global $e107_debug;
  1726.     $ret = ($e107_debug ? include($fname) : @include($fname));
  1727.     return $ret;
  1728. }
  1729.  
  1730. function e107_include_once($fname) {
  1731.     global $e107_debug;
  1732.     if(is_readable($fname)){
  1733.         $ret = (!$e107_debug)? @include_once($fname) : include_once($fname);
  1734.     }
  1735.     return (isset($ret)) ? $ret : "";
  1736. }
  1737.  
  1738. function e107_require_once($fname) {
  1739.     global $e107_debug;
  1740.     $ret = ($e107_debug ? require_once($fname) : @require_once($fname));
  1741.     return $ret;
  1742. }
  1743.  
  1744. function e107_require($fname) {
  1745.     global $e107_debug;
  1746.     $ret = ($e107_debug ? require($fname) : @require($fname));
  1747.     return $ret;
  1748. }
  1749.  
  1750. function e107_filter($input,$key,$type,$base64=FALSE)
  1751. {
  1752.     if(is_string($input) && trim($input)=="")
  1753.     {
  1754.         return;
  1755.     }
  1756.        
  1757.     if(is_array($input))
  1758.     {
  1759.         return array_walk($input, 'e107_filter', $type);   
  1760.     }
  1761.            
  1762.     if($type == "_POST" || ($type == "_SERVER" && ($key == "QUERY_STRING")))
  1763.     {
  1764.         if($type == "_POST" && ($base64 == FALSE))
  1765.         {
  1766.             $input = preg_replace("/(\[code\])(.*?)(\[\/code\])/is","",$input);
  1767.         }
  1768.    
  1769.         $regex = "/(document\.location|document\.write|base64_decode|chr|php_uname|fwrite|fopen|fputs|passthru|popen|proc_open|shell_exec|exec|proc_nice|proc_terminate|proc_get_status|proc_close|pfsockopen|apache_child_terminate|posix_kill|posix_mkfifo|posix_setpgid|posix_setsid|posix_setuid|phpinfo) *?\((.*) ?\;?/i";
  1770.         if(preg_match($regex,$input))
  1771.         {
  1772.             header('HTTP/1.0 400 Bad Request', true, 400);
  1773.             exit();
  1774.         }
  1775.        
  1776.         if(preg_match("/system *?\((.*);.*\)/i",$input))
  1777.         {
  1778.             header('HTTP/1.0 400 Bad Request', true, 400);
  1779.             exit();
  1780.         }
  1781.        
  1782.         $regex = "/(wget |curl -o |fetch -|lwp-download|onmouse)/i";
  1783.         if(preg_match($regex,$input))
  1784.         {
  1785.             header('HTTP/1.0 400 Bad Request', true, 400);
  1786.             exit();
  1787.         }
  1788.    
  1789.     }
  1790.    
  1791.     if($type == "_SERVER")
  1792.     {
  1793.         if(($key == "QUERY_STRING") && (
  1794.             strpos(strtolower($input),"../../")!==FALSE
  1795.             || strpos(strtolower($input),"=http")!==FALSE
  1796.             || strpos(strtolower($input),strtolower("http%3A%2F%2F"))!==FALSE
  1797.             || strpos(strtolower($input),"php:")!==FALSE  
  1798.             || strpos(strtolower($input),"data:")!==FALSE
  1799.             || strpos(strtolower($input),strtolower("%3Cscript"))!==FALSE
  1800.             ))
  1801.         {
  1802.  
  1803.             header('HTTP/1.0 400 Bad Request', true, 400);
  1804.             exit();
  1805.         }
  1806.                    
  1807.         if(($key == "HTTP_USER_AGENT") && strpos($input,"libwww-perl")!==FALSE)
  1808.         {
  1809.             header('HTTP/1.0 400 Bad Request', true, 400);
  1810.             exit();
  1811.         }
  1812.        
  1813.                        
  1814.     }
  1815.        
  1816.     if(strpos(str_replace('.', '', $input), '22250738585072011') !== FALSE) // php-bug 53632
  1817.     {
  1818.         header('HTTP/1.0 400 Bad Request', true, 400);
  1819.         exit();
  1820.     }
  1821.    
  1822.     if($base64 != TRUE)
  1823.     {
  1824.         e107_filter(base64_decode($input),$key,$type,TRUE);
  1825.     }
  1826.    
  1827. }
  1828.  
  1829.  
  1830.  
  1831.  
  1832. function include_lan($path, $force = FALSE)
  1833. {
  1834.     if ( ! is_readable($path))
  1835.     {
  1836.         $path = str_replace(e_LANGUAGE, 'English', $path);
  1837.     }
  1838.     $ret = ($force) ? e107_include($path) : e107_include_once($path);
  1839.     return (isset($ret)) ? $ret : '';
  1840. }
  1841.  
  1842. if(!function_exists("print_a"))
  1843. {
  1844.   function print_a($var, $return = false)
  1845.   {
  1846.     $charset = "utf-8";
  1847.     if(defined("CHARSET"))
  1848.     {
  1849.       $charset = CHARSET;
  1850.     }
  1851.     if(!$return)
  1852.     {
  1853.       echo '<pre>'.htmlspecialchars(print_r($var, true), ENT_QUOTES, $charset).'</pre>';
  1854.       return true;
  1855.     }
  1856.     else
  1857.     {
  1858.       return '<pre>'.htmlspecialchars(print_r($var, true), ENT_QUOTES, $charset).'</pre>';
  1859.     }
  1860.   }
  1861. }
  1862.  
  1863.  
  1864. // Check that all required user fields (including extended fields) are valid.
  1865. // Return TRUE if update required
  1866. function force_userupdate()
  1867. {
  1868.     global $sql,$pref,$currentUser;
  1869.  
  1870.     if (e_PAGE == "usersettings.php" || strpos(e_SELF, ADMINDIR) == TRUE || (defined("FORCE_USERUPDATE") && (FORCE_USERUPDATE == FALSE)))
  1871.     {
  1872.         return FALSE;
  1873.     }
  1874.  
  1875.     $signup_option_names = array("realname", "signature", "image", "timezone", "class");
  1876.  
  1877.     foreach($signup_option_names as $key => $value)
  1878.     {
  1879.         if ($pref['signup_option_'.$value] == 2 && !$currentUser['user_'.$value])
  1880.         {
  1881.             return TRUE;
  1882.         }
  1883.     }
  1884.  
  1885.     if (!varset($pref['disable_emailcheck'],TRUE) && !trim($currentUser['user_email'])) return TRUE;
  1886.  
  1887.     if($sql -> db_Select('user_extended_struct', 'user_extended_struct_applicable, user_extended_struct_write, user_extended_struct_name, user_extended_struct_type', 'user_extended_struct_required = 1 AND user_extended_struct_applicable != '.e_UC_NOBODY))
  1888.     {
  1889.         while($row = $sql -> db_Fetch())
  1890.         {
  1891.             if (!check_class($row['user_extended_struct_applicable'])) { continue; }        // Must be applicable to this user class
  1892.             if (!check_class($row['user_extended_struct_write'])) { continue; }             // And user must be able to change it
  1893.             $user_extended_struct_name = "user_{$row['user_extended_struct_name']}";
  1894.             if (!isset($currentUser[$user_extended_struct_name]))
  1895.             {
  1896.                 return TRUE;
  1897.             }
  1898.             if (($row['user_extended_struct_type'] == 7) && ($currentUser[$user_extended_struct_name] == '0000-00-00'))
  1899.             {
  1900.                 return TRUE;
  1901.             }
  1902.         }
  1903.     }
  1904.     return FALSE;
  1905. }
  1906.  
  1907. class error_handler {
  1908.  
  1909.     var $errors;
  1910.     var $debug = false;
  1911.  
  1912.     function error_handler() {
  1913.         //
  1914.         // This is initialized before the current debug level is known
  1915.         //
  1916.         if ((isset($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'debug=') !== FALSE) || isset($_COOKIE['e107_debug_level'])) {
  1917.             $this->debug = true;
  1918.             error_reporting(E_ALL);
  1919.         } else {
  1920.             error_reporting(E_ERROR | E_PARSE);
  1921.         }
  1922.     }
  1923.  
  1924.     function handle_error($type, $message, $file, $line, $context) {
  1925.         $startup_error = (!defined('E107_DEBUG_LEVEL')); // Error before debug system initialized
  1926.         switch($type) {
  1927.             case E_NOTICE:
  1928.             if ($startup_error || E107_DBG_ALLERRORS) {
  1929.                 $error['short'] = "Notice: {$message}, Line {$line} of {$file}<br />\n";
  1930.                 $trace = debug_backtrace();
  1931.                 $backtrace[0] = (isset($trace[1]) ? $trace[1] : "");
  1932.                 $backtrace[1] = (isset($trace[2]) ? $trace[2] : "");
  1933.                 $error['trace'] = $backtrace;
  1934.                 $this->errors[] = $error;
  1935.             }
  1936.             break;
  1937.             case E_WARNING:
  1938.             if ($startup_error || E107_DBG_BASIC) {
  1939.                 $error['short'] = "Warning: {$message}, Line {$line} of {$file}<br />\n";
  1940.                 $trace = debug_backtrace();
  1941.                 $backtrace[0] = (isset($trace[1]) ? $trace[1] : "");
  1942.                 $backtrace[1] = (isset($trace[2]) ? $trace[2] : "");
  1943.                 $error['trace'] = $backtrace;
  1944.                 $this->errors[] = $error;
  1945.             }
  1946.             break;
  1947.             case E_USER_ERROR:
  1948.             if ($this->debug == true) {
  1949.                 $error['short'] = "&nbsp;&nbsp;&nbsp;&nbsp;Internal Error Message: {$message}, Line {$line} of {$file}<br />\n";
  1950.                 $trace = debug_backtrace();
  1951.                 $backtrace[0] = (isset($trace[1]) ? $trace[1] : "");
  1952.                 $backtrace[1] = (isset($trace[2]) ? $trace[2] : "");
  1953.                 $error['trace'] = $backtrace;
  1954.                 $this->errors[] = $error;
  1955.             }
  1956.             default:
  1957.             return true;
  1958.             break;
  1959.         }
  1960.     }
  1961.  
  1962.     function return_errors() {
  1963.         $index = 0; $colours[0] = "#C1C1C1"; $colours[1] = "#B6B6B6";
  1964.         $ret = "" ;
  1965.         if (E107_DBG_ERRBACKTRACE)
  1966.         {
  1967.             foreach ($this->errors as $key => $value) {
  1968.                 $ret .= "\t<tr>\n\t\t<td class='forumheader3' >{$value['short']}</td><td><input class='button' type ='button' style='cursor: hand; cursor: pointer;' size='30' value='Back Trace' onclick=\"expandit('bt_{$key}')\" /></td>\n\t</tr>\n";
  1969.                 $ret .= "\t<tr>\n<td style='display: none;' colspan='2' id='bt_{$key}'>".print_a($value['trace'], true)."</td></tr>\n";
  1970.                 if($index == 0) { $index = 1; } else { $index = 0; }
  1971.             }
  1972.         } else {
  1973.             foreach ($this->errors as $key => $value)
  1974.             {
  1975.                 $ret .= "<tr class='forumheader3'><td>{$value['short']}</td></tr>\n";
  1976.             }
  1977.         }
  1978.  
  1979.         return ($ret) ? "<table class='fborder'>\n".$ret."</table>" : "";
  1980.     }
  1981.  
  1982.     function trigger_error($information, $level) {
  1983.         trigger_error($information);
  1984.     }
  1985. }
  1986.  
  1987. /**
  1988.  * Strips slashes from a var if magic_quotes_gqc is enabled
  1989.  *
  1990.  * @param mixed $data
  1991.  * @return mixed
  1992.  */
  1993. function strip_if_magic($data) {
  1994.     if (MAGIC_QUOTES_GPC == true) {
  1995.         return array_stripslashes($data);
  1996.     } else {
  1997.         return $data;
  1998.     }
  1999. }
  2000.  
  2001. /**
  2002.  * Strips slashes from a string or an array
  2003.  *
  2004.  * @param mixed $value
  2005.  * @return mixed
  2006.  */
  2007. function array_stripslashes($data) {
  2008.     return is_array($data) ? array_map('array_stripslashes', $data) : stripslashes($data);
  2009. }
  2010.  
  2011. $sql->db_Mark_Time('(After class2)');
  2012.  
  2013.  
  2014. function e107_ini_set($var, $value)
  2015. {
  2016.     if (function_exists('ini_set'))
  2017.     {
  2018.         return ini_set($var, $value);
  2019.     }
  2020.     return FALSE;
  2021. }
  2022.  
  2023. ?>
Add Comment
Please, Sign In to add comment