[ Index ]

PHP Cross Reference of e107 v1


title

Body

[close]

/ -> class2.php (source)

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


Generated: Mon Mar 12 16:28:38 2012 Cross Reference PHPXref