<?php
  $Testing    = true;
//  $MobileTest = true;
//  $MobileRes  = 1;
//  $Debugger = true;


  if (!isset($Site))  $Site   = $_SERVER['DOCUMENT_ROOT'].'/';
  if (!isset($DSite)) $DSite  = $_SERVER['DOCUMENT_ROOT'].'/Admin/Debugger/';
  if (!isset($URL))   $URL    = (($_SERVER['HTTPS'] == 'on')?'https://':'http://').$_SERVER ['SERVER_NAME'].'/';
  if (!isset($Root))  $Root   = '/usr/home/wcard/Include/';
  if (!isset($SRoot)) $SRoot  = str_replace('public_html','Include',$Site);

  global $Session;
  global $Root;
  global $SRoot;
  global $URL;
  global $Site;
  global $Testing;
  global $Debugger;
  global $MobileTest;
  global $MobileRes;

  function HTTPType() { return (($_SERVER['REDIRECT_HTTPS'] == 'on')?'https://':'http://'); }

  static $CSSFiles          = array();
  static $JSFiles           = array();
  static $DialogFiles       = array();

  function file_test($file) { return ($ch = curl_init($file)) ? @curl_close($ch) || true : false; }

  function CSSFile($file,$path='')
  { global $URL;
    global $CSSFiles;
    $file = ((empty($path))?$URL.'CSS/':$path).$file;
    if (empty($CSSFiles[$file]))
    { $CSSFiles[$file] = true;
      echo "    <link rel='stylesheet' type='text/css' href='",$file,"'>\r\n";
    }
  }

  function JSFile($file,$path='')
  { global $URL;
    global $JSFiles;
    $file = ((empty($path))?$URL.'JS/':$path).$file;
    if (empty($JSFiles[$file]))
    { $JSFiles[$file] = true;
      echo "    <script src='",$file,"'></script>\r\n";
    }
  }

  if (!function_exists ('Table'))
  { function Table($Table)
    { global $Root;
      global $Testing;
      global $Session;
      if(empty($Table))
      { if (!empty($Session) && $Session->Admin) echo "Table is blank.<br>";
        return false;
      }
      switch($Table[1])
      { case 'M': $file = $Root.'CM/DB/Tables/'.$Table.'.inc';    break;
        case 'B': $file = $Root.'MB/DB/Tables/'.$Table.'.inc';    break;
        default:  $file = $Root.'Host/DB/Tables/'.$Table.'.inc';  break;
      }
      if (!file_exists($file))
      { //if (!empty($Session) && $Session->Admin)
        echo "Table file ",$file," was not found.<br>";
        return false;
      }
      include_once $file;
//      $temp = DBT::IndexedTable($Table);
//      if (!empty($temp)) return $temp;
      if (!$Testing)  return  new  $Table(DB::SiteDatabase());
      return new $Table(DBTesting);
    }
  }

  function iPageLink($target)
  { global $Session;
    global $Cypher;
    global $URL;

    if($target[0] == '#') return $target;

    if (($target[0] !== '.') && !empty($Session->ST->Record[SessionUserName]))
      $link = $Cypher->encrypt($Session->ST->Record[SessionUserName].'$'.$target.'#18396423');
    else
      $link = $Cypher->encrypt($target.'#18396423');

    $A = (empty($Session->Admin))?'':'&admin=true&page=' . $target;
    return $URL.'iPage.php'.'?id='.urlencode($link).$A;
  }

  function iFileLink($target)
  { global $Session;
    global $Cypher;
    global $URL;

    if($target[0] == '#') return $target;

    if (($target[0] !== '.') && !empty($Session->ST->Record[SessionUserName]))
      $link = $Cypher->encrypt($Session->ST->Record[SessionUserName].'$'.$target.'#18396423');
    else
      $link = $Cypher->encrypt($target.'#18396423');

    $A = (empty($Session->Admin))?'':'&admin=true&page=' . $target;
    return $URL.'iFile.php'.'?id='.urlencode($link).$A;
  }

  function iAdminPageLink($target)
  { global $Session;
    global $Cypher;
    global $URL;

    if($target[0] == '#') return $target;

    if (($target[0] !== '.') && !empty($Session->ST->Record[SessionUserName]))
      $link = $Cypher->encrypt($Session->ST->Record[SessionUserName].'$'.$target.'#18396423');
    else
      $link = $Cypher->encrypt($target.'#18396423');

    $S = (empty($Session->ST->RawRecord[SessionID]))?'':'&idx='.$Cypher->encrypt($Session->ST->RawRecord[SessionID]);
    $A = (empty($Session->Admin))?'':'&admin=true&page=' . $target;
    return $URL.'iPage.php'.'?id='.urlencode($link).$A.$S;
  }

  function HostFile($file)          { global $Site;   return $Site.'Host/'.$file; };
  function HostIncludeFile($file)   { global $Root;   return $Root.'Host/Include/'.$file; };
  function HostDBFile($file)        { global $Root;   return $Root.'Host/DB/'.$file; };
  function SiteIncludeFile($file)   { global $SRoot;  return $SRoot.'Include/'.$file; };
  function IncludeDialogFile($file) { global $Site;   return $Site.'Host/Include/'.$file; };
  function IncludeDialog($file,$args='')
  { global $DialogFiles;
    global $Root;
    global $Site;
    global $URL;
    if (empty($DialogFiles[$file]))
    { $DialogFiles[$file] = true;
      $File = $Root.'Host/Include/Dialogs/i'.$file.'.inc';
      if (file_test($File)) include_once($File);
      $File = $URL.'Host/Include/Dialogs/i'.$file.'.js';
      if (file_test($File))
        echo "    <script src='",$File,"'></script>\r\n";
      $File = $URL.'Host/Include/Dialogs/i'.$file.'.css';
      if (file_exists($File))
        echo "    <link rel='stylesheet' type='text/css' href='",$File,"'>\r\n";
    }
    if ($args)
    { echo "    <script>\r\n";
      if (!empty($args['var'])) echo $args['var'],'  ';
      echo '      new i',$file,'(';
      if (!empty($args['parent'])) echo '{parent:',$args['parent'],'}';
      echo ");\r\n";
      echo "    </script>\r\n";
    }
  }
  function IncludeDB($tbl,$match=null,$index=null)
  { $tbl  = Table($tbl);
    $temp = $tbl->GetRecords($match,$index);

  }

  class Session
  { const UserCookie            = 'u287469';
    const SessionCookie         = 's67309763';
    const AdminSessionCookie    = 'sa7493852';
    const SessionVarCookie      = 'sv9836821s';
    const AdminSessionVarCookie = 'sva946325s';
    const OptionCookie          = 'o37925682';
    const OptionAdminCookie     = 'oa4727409s';


    public $ID                = 0;

    public $MemberID          = 0;                         public $ActingMemberID    = 0;

    public $MemberType        = 0;

    public $MemberActingType  = 0;

    public $Width             = 0;

    public $Height            = 0;

    public $History           = 0;

    public $NewSession        = false;

    public $SuperUser         = false;

    public $Portrait          = false;
    public $Mobile            = false;
    public $DynamicIP         = false;
    public $Track             = false;
    public $Admin             = false;
    public $ActingAdmin       = false;
    public $BotFlag           = false;
    public $NoTerms           = false;
    public $NoSessions        = false;
    public $NoStatusChk       = false;
    public $NoCookieChk       = false;
    public $NoTimer           = false;
    public $TermsWarning      = false;
    public $Monitored         = false;
    public $Debugging         = false;
    public $Debuggable        = false;
    public $TrackLoading      = false;
    public $Timing            = array();
    public $Time              = 0;
    public $StartTime         = 0;
    public $Accredited        = false;
    public $NDA               = false;
    public $EPCNDA            = false;
    public $TNDA              = false;
    public $TTNDA             = false;
    public $TWNDA             = false;
    public $SiteAcc           = false;
    public $EPCAcc            = false;
    public $TCMAcc            = false;
    public $TTCMAcc           = false;
    public $TWCMAcc           = false;
    public $BoardAcc          = false;
    public $AutoStart         = false;
    public $SmallScreen       = false;
    public $MobileRes         = 0;

    public $SSL               = true;
    public $ST                = null;

    public $MT                = null;
    public $PT                = null;
    public $SCT               = null;
    public $ACT               = null;
    public $AT                = null;
    public $Page              = null;
    public $User              = null;
    public $Browser           = null;
    public $Log               = null;

    public $SessionCookie     = '';
    public $SessionVarCookie  = '';

    function __construct($SessionType=0)
    { global $MobileTest;
      global $MobileRes;
      global $Root;
      $this->StartTime        = $this->Time = microtime(true);
      $Time                   = $this->Time;
      include_once $Root.'Host/DB/Tables/SiteCfgOptionTableConstants.inc';
      $this->Timing['cfgi']   = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      include_once $Root.'Host/DB/Tables/SessionTypeTableConstants.inc';
      $this->Timing['sti']    = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      include_once $Root.'Host/DB/Tables/SessionOptionTableConstants.inc';
      $this->Timing['soi']    = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      include_once $Root.'Host/DB/Objects/Browser.inc';
      $this->Timing['broi']   = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      include_once $Root.'Host/DB/Objects/Encrypt.inc';
      $this->Timing['enci']   = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;

      $this->LT               = Table('CMLogTable');
      $this->Timing['logt']   = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      $this->ST               = Table('CMSessionTable');
      $this->Timing['st']     = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      $this->MT               = Table('CMMemberTable');
      $this->Timing['mt']     = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      $this->SCT              = Table('CMSiteControlTable');
      $this->Timing['sct']    = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      $this->ACT              = Table('CMAccessTable');
      $this->Timing['act']    = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      $this->PT               = Table('CMPageTable');
      $this->Timing['pt']     = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      $this->Cypher           = $Cypher;
      $this->Timing['cypt']   = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;

      $this->Browser          = new Browser();
      $this->Timing['brow']   = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
      $this->Mobile           = ($this->Browser->Mobile || !empty($MobileTest))?true:false;
      $this->MobileRes        = $MobileRes;
      $this->SessionType      = $SessionType;

      $GLOBALS['LT']          = $this->LT;      // Log Table
      $GLOBALS['ST']          = $this->ST;      // Session Table
      $GLOBALS['MT']          = $this->MT;      // Member Table
      $GLOBALS['SCT']         = $this->SCT;     // Site Control Table
      $GLOBALS['Cypher']      = $this->Cypher;  // Encryption
      $GLOBALS['Browser']     = $this->Browser; // Browser Info
      $GLOBALS['Admin']       = $this->Admin;   // An Admin Session
      $this->Timing['glob']   = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;

      $this->BadBotChk();
      $this->Timing['bbot']   = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
//      $this->ExpireChk();
      $this->Timing['expir']  = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;
    }

    function __destruct ()
    { unset($GLOBALS['ST']);
      unset($GLOBALS['MT']);
      unset($GLOBALS['SCT']);
      unset($GLOBALS['Cypher']);
      unset($GLOBALS['Browser']);
      unset($GLOBALS['Admin']);
    }

    function PageCount()
    { if (!empty($this->Page))
      { if (!$this->PT->GetPage($this->Page))
        { $this->PT->NewPage();
          $this->PT->AddRecord();
        }
        if (!$this->PT->PageOption(PageOptionCountDisabled)) $this->PT->IncPageCount();
      }
    }

    function BeginAccess()
    { $this->ACT->NewAccess();
      $this->ACT->RawRecord[AccessMemberID]        = (!empty($this->ST->RawRecord[SessionMemberID]))?$this->ST->RawRecord[SessionMemberID]:0;
      $this->ACT->RawRecord[AccessSessionID]       = (!empty($this->ST->RawRecord[SessionID]))?$this->ST->RawRecord[SessionID]:0;
      $this->ACT->RawRecord[AccessSessionType]     = $this->SessionType;
      $this->ACT->RawRecord[AccessStart]           = time();
      $this->ACT->RawRecord[AccessEnd]             = 0;
      $this->ACT->RawRecord[AccessPage]            = $this->Page;
      $this->ACT->RawRecord[AccessReq]             = $this->Query;
      $this->ACT->RawRecord[AccessRef]             = (isset($_SERVER['HTTP_REFERER']))?$_SERVER['HTTP_REFERER']:'';
      $this->ACT->RawRecord[AccessThreat]          = (!empty($this->ST->RawRecord[SessionThreat]))?$this->ST->RawRecord[SessionThreat]:0;
      $this->ACT->RawRecord[AccessThreatSeverity]  = (!empty($this->ST->RawRecord[SessionThreatSeverity]))?$this->ST->RawRecord[SessionThreatSeverity]:0;
      $this->ACT->RawRecord[AccessWhoIsID]         = (!empty($this->ST->RawRecord[SessionWhoIsID]))?$this->ST->RawRecord[SessionWhoIsID]:0;
      $this->ACT->RawRecord[AccessAuthenticated]   = (isset($_SERVER['PHP_AUTH_USER']))?$_SERVER['PHP_AUTH_USER']:'';

      $this->ACT->AddRecord();
      $this->ST->RawRecord[SessionAccessID]  = $this->ACT->RawRecord[AccessID];
    }

    function EndAccess()
    { if (!empty($this->ST->RawRecord[SessionAccessID]))
      { $this->ACT->GetRecord('AccessID',$this->ST->RawRecord[SessionAccessID]);
        $this->ACT->RawRecord[AccessID] = $this->ST->RawRecord[SessionAccessID];
        $this->ACT->RawRecord[AccessEnd] = time();
        $this->ACT->UpdateItems(AccessEnd);
      }

    }


//  Check Sessions

    function CookieChk()
    { if (!empty($_COOKIE[self::SessionCookie]))
      { $this->ST->GetSessionByID($this->Cypher->decrypt($ID,true));
        if (empty($this->ST->RawRecord[SessionID]) || ($this->ST->RawRecord[SessionStatus] == SessionClosed))
        { setcookie (self::SessionCookie, "", time() - 3600,'/');
          $dst = 'location: '.iPageLink('iTimeOut.php');
          header($dst);
          exit;
        }
      }
      return true;
    }

    function ExpireChk()
    { $Record = $this->ST->Record;
      if ($this->ST->GetOpenSessions())
      { for ($i=0;$i < $this->ST->NRecords;$i++)
        { $this->ST->NextRecord();
          if (!empty($this->ST->RawRecord[SessionID])) continue;    // Skip Bad Record
          $ElapsedTime  = (!empty($this->ST->RawRecord[SessionAcc]))?time() - $this->ST->RawRecord[SessionAcc]:0;
          $Expired      = ((!empty($this->ST->RawRecord[SessionTimeout])) && (($this->ST->RawRecord[SessionTimeout]-$ElapsedTime) <= -1800))?true:false;
          if ($Expired)
          { $this->CloseSession();
            continue;
          }
        }
      }
    }

    function BadBotChk()
    {
      return false;
    }

    function Start($Page='',$User='',$ID=0,$Query='')
    { global $Ajax;
      global $MobileRes;
      global $Cypher;
      global $URL;

      $Time         = $this->Time;
      $this->Timing['start']  = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;

      $this->Page   = $Page;
      $this->User   = $User;
      $this->ID     = $ID;
      $this->Query  = $Query;

// Setting up Admin Section

      $this->Admin      = (!empty($_POST['admin']) || !empty($_GET['admin']) || (!empty($_SERVER['REQUEST_URI']) && ($_SERVER['REQUEST_URI'] == '/Admin/') && !empty($_SERVER['REDIRECT_REMOTE_USER'])))?true:false;

      if ($this->Admin)
      { $this->SessionCookie    = self::AdminSessionCookie;
        $this->SessionVarCookie = self::AdminSessionVarCookie;

        $this->AT               = Table('CMAlertTable');
        $this->AT->GetRawRecord(AlertID,0);
      }
      else
      { $this->SessionCookie    = self::SessionCookie;
        $this->SessionVarCookie = self::SessionVarCookie;

      }

      if ($this->Page == 'index.php')
      { if (!empty($_COOKIE[$this->SessionCookie]))
          setcookie ($this->SessionCookie, "", time() - 3600,'/');

        if (!empty($_COOKIE[$this->SessionVarCookie]))

          setcookie ($this->SessionVarCookiee, "", time() - 3600,'/');

      }

      if (!empty($this->ID)) $this->ID = $Cypher->decrypt($this->ID,true);


// Find the Session ID


      if (!empty($this->ID))

      { $this->ST->GetSessionByID($this->ID);

        $this->ID = $this->ST->RawRecord[SessionID];
      }
      if (empty($this->ID) && !empty($this->User))
      { $this->ST->GetSessionByUser($Cypher->encrypt($this->User),$this->Admin,$this->Browser->Agent);
        $this->ID = $this->ST->RawRecord[SessionID];
      }
      if (empty($this->ID) && !empty($_GET['session']))
      { $this->ID = $Cypher->decrypt($_GET['session'],true);

        $this->ST->GetSessionByID($this->ID);

        $this->ID = $this->ST->RawRecord[SessionID];
      }
      if (empty($this->ID) && !empty($_POST['session']))

      { $this->ID = $Cypher->decrypt($_POST['session'],true);

        $this->ST->GetSessionByID($this->ID);

        $this->ID = $this->ST->RawRecord[SessionID];
      }
      if (empty($this->ID) && !$this->Mobile)
      { $this->ST->GetSessionByIP($_SERVER['REMOTE_ADDR'],$this->Admin,$this->Browser->Agent);
        $this->ID = $this->ST->RawRecord[SessionID];
      }
      if (empty($this->ID) && !empty($_COOKIE[$this->SessionCookie]))
      { $ID = $Cypher->decrypt($_COOKIE[$this->SessionCookie],true);
        if (!empty($ID))
        { $this->ST->GetSessionByID($ID);

          $this->ID = $this->ST->RawRecord[SessionID];

        }
      }

// Session ID Set if Found

      if ($this->ID && ($this->ST->RawRecord[SessionStatus] == SessionOpen) && ($this->Page == 'index.php'))
      { $this->CloseSession();
        echo "<script>\r\n";
        echo "  window.location.reload();\r\n";
        echo "</script>\r\n";
        exit();
      }

      if ($this->ID && ($this->ST->RawRecord[SessionStatus] == SessionBackingUp))
      { if ($this->Page != 'index.php')
        { echo "<script>\r\n";
          echo "  window.history.go(-1);\r\n";
          echo "</script>\r\n";
          exit();
        }
        else LoggingIn();
      }
      else if ($this->ID && ($this->ST->RawRecord[SessionStatus] == SessionLoggingOut))
      { $this->ST->RawRecord[SessionID] = $this->ID;
        if ($this->Page == 'index.php')
        { $this->CloseSession();
          echo "<script>\r\n";
          echo "  window.location.reload();\r\n";
          echo "</script>\r\n";
          exit();
        }
        else
        { if ($this->Page == 'iEntrance.php') $this->CloseSession();
          echo "<script>\r\n";
          echo "  window.history.go(-1);\r\n";
          echo "</script>\r\n";
          exit();
        }
      }

// Find the Member Table

      if ($this->ID)
      { if (!empty($this->ST->RawRecord[SessionMemberID]))
        { $this->MT->GetMemberById($this->ST->RawRecord[SessionMemberID]);
          $this->MemberID = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberID]:0;
        }
        else if (!empty($this->ST->RawRecord[SessionUserName]))
        { $this->MT->GetMemberByUser($this->ST->RawRecord[SessionUserName]);
          $this->MemberID = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberID]:0;
        }
        else $this->MemberID = 0;

        if ($this->MemberID)
        { // Check if really an Administrator
          if ($this->Admin && (!$this->MemberID || ($this->MT->RawRecord[MemberType] < SessionTypeAdmin)))
          { // Not an Administrator Session ID in error
            $this->Admin            = false;
            $this->SessionCookie    = 0;
            $this->SessionVarCookie = 0;

            if (!empty($_COOKIE[self::AdminSessionCookie]))

              setcookie (self::AdminSessionCookie, "", time() - 3600,'/');

            if (!empty($_COOKIE[self::AdminSessionVarCookie]))

              setcookie (self::AdminSessionVarCookie, "", time() - 3600,'/');

            $this->ID               = 0;

            $this->MemberID         = 0;

            if (!empty($_COOKIE[self::SessionCookie]))

            { $this->ID = $Cypher->decrypt($_COOKIE[self::SessionCookie],true);

              if ($this->ID)

              { $this->ST->GetSessionByID($this->ID);

                $this->ID = $this->ST->RawRecord[SessionID];

              }

              if (!$this->ID && !$this->Mobile)

              { $this->ST->GetSessionByIP($_SERVER['REMOTE_ADDR'],$this->Admin,$this->Browser->Agent);

                $this->ID = $this->ST->RawRecord[SessionID];
              }
              if ($this->ID)
              { $this->SessionCookie    = self::SessionCookie;
                $this->SessionVarCookie = self::SessionVarCookie;


              // Find the Member Table Again

                if (!empty($this->ST->RawRecord[SessionMemberID]))
                { $this->MT->GetMemberById($this->ST->RawRecord[SessionMemberID]);
                  $this->MemberID = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberID]:0;
                }
                else if (!empty($this->ST->RawRecord[SessionUserName]))
                { $this->MT->GetMemberByUser($this->ST->RawRecord[SessionUserName]);
                  $this->MemberID = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberID]:0;
                }
                else $this->MemberID = 0;
              }
            }
          }
          if (!$this->SuperUser) $this->SuperUser = ($this->MT->RawRecord[MemberType] == MemberTypeSuper)?true:false;
        }
      }

      if (!empty($this->ID))
      { if (!empty($this->ST->RawRecord[SessionIP]) && ($this->ST->RawRecord[SessionIP] != $_SERVER['REMOTE_ADDR']))
        { $this->ST->SetOption(SessionOptionDynamicIP,true);
          $this->ST->UpdateItem(SessionOptions);
          $this->DynamicIP  = true;
        }
        else if ($this->Mobile)
        { $this->ST->SetOption(SessionOptionDynamicIP,true);
          $this->ST->UpdateItem(SessionOptions);
          $this->DynamicIP  = true;
        }
      }
      else $this->DynamicIP  = true;

// Session Setup

      if (!$this->Admin && !empty($_SESSION['Admin'])) $this->Admin = true;
      else $this->ActingMemberID = $this->MemberID;

      ini_set('session.save_path',"/usr/home/wcard/Sessions");
      ini_set('session.gc_maxlifetime',86400);

      if ($this->Admin)
      { $this->SessionCookie    = self::AdminSessionCookie;
        $this->SessionVarCookie = self::AdminSessionVarCookie;

      }
      else
      { $this->SessionCookie    = self::SessionCookie;
        $this->SessionVarCookie = self::SessionVarCookie;

      }

      if ($this->Admin)
      { set_exception_handler('CustomErrorHandler');
        ini_set('display_errors', 'On');
        ini_set('html_errors', 0);
        error_reporting(-1);
//        register_shutdown_function('ShutdownHandler');
//        $old_error_handler = set_error_handler("ErrorHandler");
      }

      if (!empty($this->DynamicIP) && ($this->Page !== 'index.php'))
      { $ID = 0;
        if (!empty($_COOKIE[$this->SessionCookie]))
        { $ID = $Cypher->decrypt($_COOKIE[$this->SessionCookie],true);
        }
        if (empty($ID) || ($this->ID != $ID))
        { if (basename($this->Page) !== 'iCookiesRequired.php')
          { $dst = "location:".iPageLink('iCookiesRequired.php').'&target='.$Page;
            header($dst);
            exit();
          }
          else return;
        }
      }

      $user = $this->ST->RawRecord[SessionUserName];
      if (!empty($user))
      { $Field = $this->ST->Table['fields'][SessionUserName];
        $Flags = $Field['flags'];
        if (((int)$Flags & FE) != 0)
        { $user = $this->ST->Decrypt($user,(((int)$Flags & Fe) != 0));
        }
        if ($this->User && ($this->User != $user))
        { $this->CloseSession();
          $this->NewSession($this->User);
        }
      }

      if ($this->ST->RawRecord[SessionStatus] == SessionExpired)
      { if (!empty($this->Page) && ($this->Page === 'iEntrance.php'))
        { $this->CloseSession();
          $this->NewSession($user);
        }
        else if (empty($this->Page) || ($this->Page != 'iExpired.php'))
        { echo "<script>\r\n";
          echo "  window.history.go(-1);\r\n";
          echo "</script>\r\n";
          exit();
        }
      }
      else if ($this->ID && ($this->ST->RawRecord[SessionStatus] == SessionLoggingIn))
      { if ($this->Page === 'iEntrance.php')
        { if (empty($User))
          { $User   = $this->ST->RawRecord[SessionUserName];
            $Field  = $this->ST->Table['fields'][SessionUserName];
            $Flags  = $Field['flags'];
            if (((int)$Flags & FE) != 0)
            { $User = $this->ST->Decrypt($User,(((int)$Flags & Fe) != 0));
            }
          }
          $this->CloseSession();
          $this->NewSession($User);
        }
        else if ($this->Page != 'index.php')
        { echo "<script>\r\n";
          echo "  window.history.go(-1);\r\n";
          echo "</script>\r\n";
          exit();
        }
      }
      else if (!empty($this->ID) && isset($this->ST->RawRecord[SessionStatus]) && ($this->ST->RawRecord[SessionStatus] == SessionOpen))
      { $this->UpdateSession();
      }
      else if (!empty($this->ID) && isset($this->ST->RawRecord[SessionStatus]) && ($this->ST->RawRecord[SessionStatus] == SessionClosed))
      { $this->ID = 0;
        $this->NewSession($User);
      }
      else
      { $this->ID = 0;
        $this->NewSession($User);
      }

      $_SESSION['Admin'] = $this->Admin;

      $this->PageCount();

      if (!empty($this->PT->PageOption(PageOptionNoCache)))
      { ini_set('session.cache_limiter','public');
        session_cache_limiter(false);
      }

// Setting Cookies if Necessary

      if($this->ID && $this->DynamicIP)
      { setcookie($this->SessionCookie,$Cypher->encrypt($this->ID,true),0,'/','charged-motion.com',false,true);
      }

      $this->Width  = (!empty($this->ST->RawRecord[SessionWidth]))?$this->ST->RawRecord[SessionWidth]:0;
      $this->Height = (!empty($this->ST->RawRecord[SessionHeight]))?$this->ST->RawRecord[SessionHeight]:0;

      $this->SmallScreen = ($this->Width && ($this->Width < 600))?true:false;

      if (!empty($this->MemberID))
      { if (!empty($this->MT->RawRecord[MemberFlags]))
        { $Flags = $this->MT->RawRecord[MemberFlags];
          $this->Accredited   = ($Flags&0x1)?true:false;
          $this->NDA          = ($Flags&0x2)?true:false;
          $this->EPCNDA       = ($Flags&0x4)?true:false;
          $this->SiteAcc      = ($Flags&0x8)?true:false;
          $this->EPCAcc       = ($Flags&0x10)?true:false;
          $this->BoardAcc     = ($Flags&0x20)?true:false;
          $this->AutoStart    = ($Flags&0x200)?true:false;
          if ($Flags&0x400) $this->SmallScreen  = true;
          if ($Flags&0x800) $this->Mobile = true;
          $this->TrackLoading = ($Flags&0x1000)?true:false;
        }
        if (!empty($this->MT->RawRecord[MemberActingType]))
        { $this->MemberActingType = $this->MT->RawRecord[MemberActingType];
        }
        else
        { $this->MemberActingType = $this->MT->RawRecord[MemberType];
          $this->MT->RawRecord[MemberActingType] = $this->MemberActingType;
        }
      }

      if (!empty($this->ST->RawRecord[SessionMemberType]))        $this->MemberType       = $this->ST->RawRecord[SessionMemberType];
      if (!empty($this->ST->RawRecord[SessionMemberActingType]))  $this->MemberActingType = $this->ST->RawRecord[SessionMemberActingType];

      if ($this->Admin && ($this->MemberActingType >= 9))         $this->ActingAdmin      = true;
      if ($this->Admin && ($this->MemberActingType > 9))          $this->Debuggable       = true;
      if (!empty($this->ST->RawRecord[SessionHistory]))           $this->History          = $this->ST->RawRecord[SessionHistory];
      else                                                        $this->History          = 0;
      $this->Timing['start_end']  = ($this->Time = microtime(true))-$Time;
      $Time                       = $this->Time;
      $this->Timing['elapsed']    = $this->Time -$this->StartTime;
      return true;
    }

    function AjaxStart()
    { $Time         = $this->Time;
      $this->Timing['start']  = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;

// Find the Member Table

      if (!$this->ID) return false;
      { if (!empty($this->ST->RawRecord[SessionMemberID]))
        { $this->MT->GetMemberById($this->ST->RawRecord[SessionMemberID]);
          $this->MemberID = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberID]:0;
        }
        else if (!empty($this->ST->RawRecord[SessionUserName]))
        { $this->MT->GetMemberByUser($this->ST->RawRecord[SessionUserName]);
          $this->MemberID = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberID]:0;
        }
        else $this->MemberID = 0;
      }

      $this->Admin      = ($this->MemberID && ($this->MT->RawRecord[MemberType] >= 9))?true:false;
      $this->SuperUser  = ($this->MemberID && ($this->MT->RawRecord[MemberType] == 10))?true:false;

      ini_set('session.save_path',"/usr/home/wcard/Sessions");
      ini_set('session.gc_maxlifetime',86400);


      if ($this->Admin)
      { set_exception_handler('CustomErrorHandler');
        ini_set('display_errors', 'On');
        ini_set('html_errors', 0);
        error_reporting(-1);
//        register_shutdown_function('ShutdownHandler');
//        $old_error_handler = set_error_handler("ErrorHandler");
      }

      $this->DynamicIP  = $this->Mobile || $this->ST->GetOption(SessionOptionDynamicIP);

      $_SESSION['Admin'] = $this->Admin;

      $this->Width  = (!empty($this->ST->RawRecord[SessionWidth]))?$this->ST->RawRecord[SessionWidth]:0;
      $this->Height = (!empty($this->ST->RawRecord[SessionHeight]))?$this->ST->RawRecord[SessionHeight]:0;

      $this->SmallScreen = ($this->Width && ($this->Width < 600))?true:false;

      if (!empty($this->MemberID) && !empty($this->MT->RawRecord[MemberFlags]))
      { $Flags = $this->MT->RawRecord[MemberFlags];
        $this->Accredited   = ($Flags&0x1)?true:false;
        $this->NDA          = ($Flags&0x2)?true:false;
        $this->EPCNDA       = ($Flags&0x4)?true:false;
        $this->SiteAcc      = ($Flags&0x8)?true:false;
        $this->EPCAcc       = ($Flags&0x10)?true:false;
        $this->BoardAcc     = ($Flags&0x20)?true:false;
        $this->AutoStart    = ($Flags&0x200)?true:false;
        if ($Flags&0x400) $this->SmallScreen  = true;
        if ($Flags&0x800) $this->Mobile = true;
        $this->TrackLoading = ($Flags&0x1000)?true:false;
      }
      if (!empty($this->ST->RawRecord[SessionMemberType]))        $this->MemberType        = $this->ST->RawRecord[SessionMemberType];
      if (!empty($this->ST->RawRecord[SessionMemberActingType]))  $this->MemberActingType  = $this->ST->RawRecord[SessionMemberActingType];

      if ($this->Admin && ($this->MemberActingType > 9)) $this->Debuggable = true;
      if (!empty($this->ST->RawRecord[SessionHistory])) $this->History = $this->ST->RawRecord[SessionHistory];
      $this->Timing['start_end']  = ($this->Time = microtime(true))-$Time;
      $Time                       = $this->Time;

      return true;
    }

    function DebugStart($Page='',$User='',$ID=0,$Query='')
    { global $Ajax;
      global $MobileRes;
      global $Cypher;
      global $URL;
      global $TrackLoading;

      $Time         = $this->Time;
      $this->Timing['start']  = ($this->Time = microtime(true))-$Time;
      $Time                   = $this->Time;

      $this->Page   = $Page;
      $this->User   = $User;
      $this->ID     = $ID;
      $this->Query  = $Query;

// Setting up Admin Section

      $this->Admin      = (!empty($_POST['admin']) || !empty($_GET['admin']) || (!empty($_SERVER['REQUEST_URI']) && ($_SERVER['REQUEST_URI'] == '/Admin/') && !empty($_SERVER['REDIRECT_REMOTE_USER'])))?true:false;

      if ($this->Admin)
      { echo '<br>Administrative Session<br>';
        $this->SessionCookie    = self::AdminSessionCookie;
        $this->SessionVarCookie = self::AdminSessionVarCookie;

      }
      else
      { echo '<br>Normal Session<br>';
        $this->SessionCookie    = self::SessionCookie;
        $this->SessionVarCookie = self::SessionVarCookie;

      }

      if (empty($this->ID))
        echo 'Session Started with No ID<br>';
      else
      { $this->ID = $Cypher->decrypt($this->ID,true);
        echo 'Supplied ID Decrypted.';

      }


// Find the Session ID


      if (!empty($this->ID))

      { $this->ST->GetSessionByID($this->ID);

        $ID = $this->ST->RawRecord[SessionID];
        if (!empty($ID))  echo 'Session Started with Supplied ID = '.$this->ID.'<br>';
        else      echo 'Supplied Session ID = '.$this->ID.'not Found.<br>';
        $this->ID = $ID;
      }
      if (empty($this->ID) && !empty($this->User))
      { $this->ST->GetSessionByUser($Cypher->encrypt($this->User),$this->Admin,$this->Browser->Agent);
        $this->ID = $this->ST->RawRecord[SessionID];
        if (!empty($this->ID))  echo 'Session Started with Session ID = '.$this->ID.' from User Name = '.$this->User.'.<br>';
        else            echo 'User = '.$this->User.' Session ID not Found.<br>';
      }
      if (empty($this->ID) && !empty($_GET['session']))
      { $this->ID = $Cypher->decrypt($_GET['session'],true);

        $this->ST->GetSessionByID($this->ID);

        $ID = $this->ST->RawRecord[SessionID];
        if (!empty($ID))  echo 'Session Started with GET Session ID = '.$ID.'<br>';
        else      echo 'Session ID = '.$this->ID.' from GET not found.<br>';
        $this->ID = $ID;

      }

      if (empty($this->ID) && !empty($_POST['session']))

      { $this->ID = $Cypher->decrypt($_POST['session'],true);

        $this->ST->GetSessionByID($this->ID);

        $ID = $this->ST->RawRecord[SessionID];
        if (!empty($ID))  echo 'Session Started with POST Session ID = '.$ID.'<br>';
        else      echo 'Session ID = '.$this->ID.' from POST not found.<br>';
        $this->ID = $ID;

      }

      if (empty($this->ID) && !$this->Mobile)

      { $this->ST->GetSessionByIP($_SERVER['REMOTE_ADDR'],$this->Admin,$this->Browser->Agent);
        $this->ID = $this->ST->RawRecord[SessionID];
        if (!empty($this->ID)) echo 'Session ID = '.$this->ID.' from IP Address = '.$_SERVER['REMOTE_ADDR'],'.<br>';
        else           echo 'Session ID from IP Address = '.$_SERVER['REMOTE_ADDR'],' not found.<br>';
      }
      if (empty($this->ID) && !empty($_COOKIE[$this->SessionCookie]))
      { $ID = $Cypher->decrypt($_COOKIE[$this->SessionCookie],true);
        if (!empty($ID))
        { $this->ST->GetSessionByID($ID);

          $this->ID = $this->ST->RawRecord[SessionID];

          if ($this->ID)  echo 'Session ID = '.$this->ID.' from Session Cookie.<br>';
          else            echo 'Session ID = '.$ID.' from Session Cookie not found.<br>';
        }                 echo 'Invalid Cookie.<br>';
      }
      if (empty($this->ID)) echo 'Session ID not found.<br>';


// Session ID Set if Found

      if ($this->ID && ($this->ST->RawRecord[SessionStatus] == SessionBackingUp))
      { if ($this->Page != 'index.php')
        { echo 'Backing Up.<br>';
          echo "<script>\r\n";
          echo "  window.history.go(-1);\r\n";
          echo "</script>\r\n";
          exit();
        }
        else
        { LoggingIn();
          echo 'Logging In.<br>';
        }
      }
      else if ($this->ID && ($this->ST->RawRecord[SessionStatus] == SessionLoggingOut))
      { echo 'Logging Out.<br>';
        $this->ST->RawRecord[SessionID] = $this->ID;
        if ($this->Page == 'index.php')
        { echo 'Closing Session.<br>';
          $this->CloseSession();
          echo 'Reloading Page.<br>';
          echo "<script>\r\n";
          echo "  window.location.reload();\r\n";
          echo "</script>\r\n";
          exit();
        }
        else
        { if ($this->Page == 'iEntrance.php')
          { echo 'Closing Session.<br>';
            $this->CloseSession();
          }
          echo 'Backing Up.<br>';
          echo "<script>\r\n";
          echo "  window.history.go(-1);\r\n";
          echo "</script>\r\n";
          exit();
        }
      }

// Find the Member Table

      if ($this->ID)
      { if (!empty($this->ST->RawRecord[SessionMemberID]))
        { echo 'Loading Member Data by Session Member ID = '.$this->ST->RawRecord[SessionMemberID].'.<br>';
          $this->MT->GetMemberById($this->ST->RawRecord[SessionMemberID]);
          $this->MemberID = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberID]:0;
        }
        else if (!empty($this->ST->RawRecord[SessionUserName]))
        { echo 'Loading Member Data by User Name = '.$this->ST->RawRecord[SessionUserName].'.<br>';
          $this->MT->GetMemberByUser($this->ST->RawRecord[SessionUserName]);
          $this->MemberID = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberID]:0;
        }
        else
        { echo 'Not a Member.<br>';
          $this->MemberID = 0;
        }

        if ($this->MemberID)
        { // Check if really an Administrator
          if ($this->Admin && (!$this->MemberID || ($this->MT->RawRecord[MemberType] < SessionTypeAdmin)))
          { echo 'Not an Administrator.<br>';
            // Not an Administrator Session ID in error
            $this->Admin            = false;
            $this->SessionCookie    = 0;
            $this->SessionVarCookie = 0;

            if (!empty($_COOKIE[self::AdminSessionCookie]))

              setcookie (self::AdminSessionCookie, "", time() - 3600,'/');

            if (!empty($_COOKIE[self::AdminSessionVarCookie]))

              setcookie (self::AdminSessionVarCookie, "", time() - 3600,'/');

            echo 'Clearing Administrative Cookies.<br>';

            $this->ID               = 0;

            $this->MemberID         = 0;

            if (!empty($_COOKIE[self::SessionCookie]))

            { echo 'Trying User Cookie.<br>';

              $this->ID = $Cypher->decrypt($_COOKIE[self::SessionCookie],true);

              if ($this->ID)

              { $this->ST->GetSessionByID($this->ID);

                $this->ID = $this->ST->RawRecord[SessionID];

                if ($this->ID)

                  echo 'Session ID = '.$this->ID.'Record Fetched from User Cookie.<br>';

              }

              if (!$this->ID && !$this->Mobile)

              { $this->ST->GetSessionByIP($_SERVER['REMOTE_ADDR'],$this->Admin,$this->Browser->Agent);

                $this->ID = $this->ST->RawRecord[SessionID];
                if ($this->ID)
                  echo 'Session ID = '.$this->ID.'Record Fetched from IP Address.<br>';

              }
              if ($this->ID)
              { $this->SessionCookie    = self::SessionCookie;
                $this->SessionVarCookie = self::SessionVarCookie;


              // Find the Member Table Again

                if (!empty($this->ST->RawRecord[SessionMemberID]))
                { echo 'Reloading Member Data by Session Member ID.<br>';
                  $this->MT->GetMemberById($this->ST->RawRecord[SessionMemberID]);
                  $this->MemberID = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberID]:0;
                }
                else if (!empty($this->ST->RawRecord[SessionUserName]))
                { echo 'Reloading Member Data by User Name.<br>';
                  $this->MT->GetMemberByUser($this->ST->RawRecord[SessionUserName]);
                  $this->MemberID = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberID]:0;
                }
                else
                { echo 'Not a Member.<br>';
                  $this->MemberID = 0;
                }
              }
            }
          }
          if (!$this->SuperUser)
            $this->SuperUser = ($this->MT->RawRecord[MemberType] == MemberTypeSuper)?true:false;
          if ($this->SuperUser)
            echo 'A Super User.<br>';
        }
      }
      else echo 'Not a Member.<br>';

      if (!empty($this->ID))
      { if (!empty($this->ST->RawRecord[SessionIP]) && ($this->ST->RawRecord[SessionIP] != $_SERVER['REMOTE_ADDR']))
        { $this->ST->SetOption(SessionOptionDynamicIP,true);
          $this->ST->UpdateItem(SessionOptions);
          $this->DynamicIP  = true;
          echo 'IP Address Changed.<br>';
        }
        else if ($this->Mobile)
        { $this->ST->SetOption(SessionOptionDynamicIP,true);
          $this->ST->UpdateItem(SessionOptions);
          $this->DynamicIP  = true;
          echo 'Updated A Mobile Device with a Dynamic IP.<br>';
        }
      }
      else
      { $this->DynamicIP  = true;
        echo 'A Mobile Device.<br>';
      }

      if ($this->DynamicIP)
        echo 'It&apos;s a Dynamic IP Address.<br>';


// Session Setup

      if (!$this->Admin && !empty($_SESSION['Admin']))
      { $this->Admin = true;
        echo 'Administrator set by Session Variable.<br>';
      }

      ini_set('session.save_path',"/usr/home/wcard/Sessions");
      ini_set('session.gc_maxlifetime',86400);
      echo 'PHP Session Set.<br>';

      if ($this->Admin)
      { $this->SessionCookie    = self::AdminSessionCookie;
        $this->SessionVarCookie = self::AdminSessionVarCookie;

      }
      else
      { $this->SessionCookie    = self::SessionCookie;
        $this->SessionVarCookie = self::SessionVarCookie;

      }

      if ($this->Admin)
      { echo 'Enabling Error Reporting.<br>';
        set_exception_handler('CustomErrorHandler');
        ini_set('display_errors', 'On');
        ini_set('html_errors', 0);
        error_reporting(-1);
//        register_shutdown_function('ShutdownHandler');
//        $old_error_handler = set_error_handler("ErrorHandler");
      }

      echo 'Checking Cookies Enabled.<br>';

      if (!empty($this->DynamicIP) && ($this->Page !== 'index.php'))
      { $ID = 0;
        if (!empty($_COOKIE[$this->SessionCookie]))
        { $ID = $Cypher->decrypt($_COOKIE[$this->SessionCookie],true);
        }
        if (empty($ID) || ($this->ID != $ID))
        { if (basename($this->Page) !== 'iCookiesRequired.php')
          { echo 'Going to Cookies Required Page.<br>';
            $dst = "location:".iPageLink('iCookiesRequired.php').'&target='.$Page;
            header($dst);
            exit();
          }
          else
          { echo 'Returning to Cookies Required Page.<br>';
            return;
          }
        }
      }

      echo 'Checking Session Status.<br>';

      if ($this->ST->RawRecord[SessionStatus] == SessionExpired)
      { echo 'Session has Expired.<br>';
        if ($this->Page === 'iEntrance.php')
        { echo 'At the Website Entrance.<br>';
          $user = $this->ST->RawRecord[SessionUserName];
          if (!empty($user))
          { echo 'Setting Session Flags.<br>';
            $Field = $this->ST->Table['fields'][SessionUserName];
            $Flags = $Field['flags'];
            if (((int)$Flags & FE) != 0)
            { $user = $this->ST->Decrypt($user,(((int)$Flags & Fe) != 0));
            }
          }
          echo 'Closing old Session.<br>';
          $this->CloseSession();
          echo 'Creating a New session.<br>';
          $this->NewSession($user);
        }
        else if ($this->Page != 'iExpired.php')
        { echo 'Not on the Expired Page.<br>Backing Up.<br>';
          echo "<script>\r\n";
          echo "  window.history.go(-1);\r\n";
          echo "</script>\r\n";
          exit();
        }
      }
      else if ($this->ID && ($this->ST->RawRecord[SessionStatus] == SessionLoggingIn))
      { echo 'Session Logging In.<br>';
        if ($this->Page === 'iEntrance.php')
        { echo 'At the Entrance Page.<br>';
          if (empty($User))
          { echo 'Getting User from old Session.<br>';
            $User   = $this->ST->RawRecord[SessionUserName];
            $Field  = $this->ST->Table['fields'][SessionUserName];
            $Flags  = $Field['flags'];
            if (((int)$Flags & FE) != 0)
            { $User = $this->ST->Decrypt($User,(((int)$Flags & Fe) != 0));
            }
          }
          echo 'Closing the Old Session.<br>';
          $this->CloseSession();
          echo 'Creating a New Session.<br>';
          $this->NewSession($User);
        }
        else if ($this->Page != 'index.php')
        { echo 'At the Index Page.<br>';
          echo 'Backing Up.<br>';
          echo "<script>\r\n";
          echo "  window.history.go(-1);\r\n";
          echo "</script>\r\n";
          exit();
        }
      }
      else if (!empty($this->ID) && isset($this->ST->RawRecord[SessionStatus]) && ($this->ST->RawRecord[SessionStatus] == SessionOpen))
      { echo 'Session is Open.<br>';
        echo 'Updating Session.<br>';
        $this->UpdateSession();
      }
      else if (!empty($this->ID) && isset($this->ST->RawRecord[SessionStatus]) && ($this->ST->RawRecord[SessionStatus] == SessionClosed))
      { $this->ID = 0;
        echo 'Ignoring Closed Session.<br>';
        echo 'Starting new Session.<br>';
        $this->NewSession($User);
      }
      else
      { $this->ID = 0;
        echo 'Starting new Session.<br>';
        $this->NewSession($User);
      }

      $_SESSION['Admin'] = $this->Admin;

      echo 'Updating the Page Access Count.<br>';
      $this->PageCount();

      if (!empty($this->PT->PageOption(PageOptionNoCache)))
      { echo 'Enable Page Caching.<br>';
        ini_set('session.cache_limiter','public');
        session_cache_limiter(false);
      }

// Setting Cookies if Necessary

      if($this->ID && $this->DynamicIP)
      { echo 'Setting the Session Cookie.<br>';
        setcookie($this->SessionCookie,$Cypher->encrypt($this->ID,true),0,'/','charged-motion.com',false,true);
      }

      echo 'Setting the Screen Dimensions.<br>';
      $this->Width  = (!empty($this->ST->RawRecord[SessionWidth]))?$this->ST->RawRecord[SessionWidth]:0;
      $this->Height = (!empty($this->ST->RawRecord[SessionHeight]))?$this->ST->RawRecord[SessionHeight]:0;

      $this->SmallScreen = ($this->Width && ($this->Width < 600))?true:false;
      if ($this->SmallScreen)
        echo 'Small Screen Formatting.<br>';
      else
        echo 'Regular Screen Formatting.<br>';
      if (!empty($this->MemberID))
      { if (!empty($this->MT->RawRecord[MemberFlags]))
        { echo 'Setting Member Flags.<br>';
          $Flags = $this->MT->RawRecord[MemberFlags];
          $this->Accredited   = ($Flags&0x1)?true:false;
          $this->NDA          = ($Flags&0x2)?true:false;
          $this->EPCNDA       = ($Flags&0x4)?true:false;
          $this->TNDA         = ($Flags&0x10)?true:false;
          $this->TTNDA        = ($Flags&0x11)?true:false;
          $this->TWNDA        = ($Flags&0x12)?true:false;
          $this->SiteAcc      = ($Flags&0x8)?true:false;
          $this->EPCAcc       = ($Flags&0x10)?true:false;
          $this->TCMAcc       = ($Flags&0x13)?true:false;
          $this->TTCMAcc      = ($Flags&0x14)?true:false;
          $this->TWCMAcc      = ($Flags&0x15)?true:false;
          $this->BoardAcc     = ($Flags&0x20)?true:false;
          $this->AutoStart    = ($Flags&0x200)?true:false;
          if ($Flags&0x400) $this->SmallScreen  = true;
          if ($Flags&0x800) $this->Mobile = true;
          $this->TrackLoading = ($Flags&0x1000)?true:false;
        }
        if (!empty($this->MT->RawRecord[MemberActingType]))
        { echo 'Member Acting Type not Set.<br>';
          $this->MemberActingType = $this->MT->RawRecord[MemberActingType];
        }
        else
        { echo 'Getting the Member Acting Type.<br>';
          $this->MemberActingType = $this->MT->RawRecord[MemberType];
        }
      }
      echo 'Updating the Session Record.<br>';
      if (!empty($this->ST->RawRecord[SessionMemberType]))        $this->MemberType       = $this->ST->RawRecord[SessionMemberType];
      if (!empty($this->ST->RawRecord[SessionMemberActingType]))  $this->MemberActingType = $this->ST->RawRecord[SessionMemberActingType];

      if ($this->Admin && ($this->MemberActingType >= 9))         $this->ActingAdmin      = true;
      if ($this->Admin && ($this->MemberActingType > 9))          $this->Debuggable       = true;
      if (!empty($this->ST->RawRecord[SessionHistory]))           $this->History          = $this->ST->RawRecord[SessionHistory];
      else                                                        $this->History          = 0;
      $this->Timing['start_end']  = ($this->Time = microtime(true))-$Time;
      $Time                       = $this->Time;
      $this->Timing['elapsed']    = $this->Time -$this->StartTime;
      echo 'Start up Complete.<br>';
      return true;
    }

    function GetSessionByID($ID,$Page=null)
    { if (!$ID) return false;
      if (isset($Page))
      { $this->Page   = $Page;
        if (!empty($this->PT->PageOption(PageOptionNoCache)))
        { ini_set('session.cache_limiter','public');
          session_cache_limiter(false);
        }
      }
      $this->ST->GetSessionByID($this->Cypher->decrypt($ID,true));
      if (!$this->ST->RawRecord[SessionID]) return false;

// Session Setup

      ini_set('session.save_path',"/usr/home/wcard/Sessions");
      ini_set('session.gc_maxlifetime',86400);

      if ($this->SCT->LogOption(8))
      { set_error_handler('LogPHPErrorHandler',E_ALL);
        error_reporting(E_ALL);
      }

// Session is Active.

      $this->ID  = $ID;
      return true;
    }

    function GetSessionWithMemberID($ID,$Page=null)
    { if (!$this->GetSessionByID($ID,$Page)) return false;
      $this->MemberID = (!empty($this->ST->RawRecord[SessionMemberID]))?$this->ST->RawRecord[SessionMemberID]:0;
      return true;
    }

// 	Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1
//-----------------------------------------------------------------
//                                          New Session
//-----------------------------------------------------------------
    function NewSession($User='')
    { if (empty($User) && $this->Admin)
        $User = ((!empty($_SERVER['REDIRECT_REMOTE_USER']))?$_SERVER['REDIRECT_REMOTE_USER']:((!empty($_SERVER['REMOTE_USER']))?$_SERVER['REMOTE_USER']:''));

      if ($User)
      { $this->MT->GetMemberByUser($User);
        if (!empty($this->MT->RawRecord[MemberID]))
          $this->MemberID = $this->MT->Record[MemberID];
      }

// Initializing the Session Record
      $this->ST->NewSession();
      $this->ST->RawRecord[SessionStatus]               = SessionOpen;
      $this->ST->RawRecord[SessionAccessID]             = $this->ACT->RawRecord[AccessID];
      $this->ST->RawRecord[SessionUserName]             = $this->Cypher->encrypt($User);
      $this->ST->RawRecord[SessionBrowser]              = $this->Browser->Id;
      $this->ST->RawRecord[SessionAgent]                = $this->Browser->Agent;
      $this->ST->RawRecord[SessionThreat]               = $this->ACT->RawRecord[AccessThreat];
      $this->ST->RawRecord[SessionThreatSeverity]       = $this->ACT->RawRecord[AccessThreatSeverity];
      $this->ST->RawRecord[SessionWhoIsID]              = $this->ACT->RawRecord[AccessWhoIsID];
      $this->ST->RawRecord[SessionSite]                 = DB::SiteSite();
      $this->ST->RawRecord[SessionDatabase]             = $this->ST->No;
      $this->ST->RawRecord[SessionAuthenticated]        = $this->ACT->RawRecord[AccessAuthenticated];
      $this->ST->RawRecord[SessionAdminSessionID]       = 0;
      $this->ST->RawRecord[SessionMonitor]              = 0;
      $this->ST->RawRecord[SessionSiteStatus]           = $this->SCT->RawRecord[SiteStatus];
      $this->ST->RawRecord[SessionReq]                  = $_SERVER['REQUEST_METHOD'];
      $this->ST->RawRecord[SessionTrack]                = $this->SCT->RawRecord[SiteTrackOptions];
      $this->ST->RawRecord[SessionLog]                  = $this->SCT->RawRecord[SiteLogOptions];
      $this->ST->RawRecord[SessionArchive]              = $this->SCT->RawRecord[SiteArchiveOptions];
      $this->ST->RawRecord[SessionOptions]              = $this->SCT->RawRecord[SiteSessionOptions];
      $this->ST->RawRecord[SessionMemberOptions]        = $this->SCT->RawRecord[SiteMemberOptions];
      $this->ST->RawRecord[SessionTimeout]              = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberTimeout]:1800;
      if ($this->Admin)
        $this->ST->RawRecord[SessionType] = SessionTypeAdmin;
      else if ($this->Browser->Robot)
        $this->ST->RawRecord[SessionType] = SessionTypeRobot;
      else if ($this->Browser->Validator)
        $this->ST->RawRecord[SessionType] = SessionTypeValidator;
      else if ($this->MemberID)
        $this->ST->RawRecord[SessionType] = SessionTypeMember;
      else
        $this->ST->RawRecord[SessionType] = SessionTypeGuest;
      if ($this->Browser->Mobile) $this->ST->RawRecord[SessionType] |= 0x8;
      $str  = '';
//      foreach($_SERVER as $key => $val) $str .= $key.' => '.$val."\r\n";
//      $this->ST->RawRecord[SessionRef]                   = $str;
// Entering Session in Database
      $this->ST->NRecords                                 = 0;
      $this->ChkSession();
      if (!$this->ST->AddRecord())
      { session_regenerate_id ();
        $this->ST->RawRecord[SessionVariable] = session_id();
        if (!$this->ST->AddRecord() && $this->Admin)  echo $this->ST->error,'<br>';
      }

      $this->ID         = $this->ST->RawRecord[SessionID];
      $this->NewSession = true;
      if (!empty($this->MT->RawRecord[MemberID]))
      { $this->MT->RawRecord[MemberVisits]++;
        $this->MT->RawRecord[MemberAccesses]++;
        $this->MT->RawRecord[MemberLastLogin] = time();
        $this->MT->RawRecord[MemberLastAcc]   = time();
        $this->MT->RawRecord[MemberSessionID] = $this->ID;
        $this->MT->UpdateItems(MemberID,MemberSessionID,MemberVisits,MemberAccesses,MemberLastLogin,MemberLastAcc,MemberActingType);
        $this->MemberID = $this->MT->RawRecord[MemberID];
      }
      return true;
    }


//-----------------------------------------------------------------
//                          Update Session
//-----------------------------------------------------------------

    function UpdateSession($New=false)
    { global $Root;
    
      include_once $Root.'Host/DB/Tables/SiteLogOptionTableConstants.inc';

// Setup Member Options

      if ($this->Admin)
        $this->ST->RawRecord[SessionType] = SessionTypeAdmin;
      else if ($this->Browser->Robot)
        $this->ST->RawRecord[SessionType] = SessionTypeRobot;
      else if ($this->Browser->Validator)
        $this->ST->RawRecord[SessionType] = SessionTypeValidator;
      else if ($this->MemberID)
        $this->ST->RawRecord[SessionType] = SessionTypeMember;
      else
        $this->ST->RawRecord[SessionType] = SessionTypeGuest;
      if ($this->Browser->Mobile) $this->ST->RawRecord[SessionType] |= 0x8;

      if (empty($this->ST->RawRecord[SessionMemberFlags]))
      { if ($this->MemberID)
        { $this->ST->RawRecord[SessionMemberID]             = $this->MT->RawRecord[MemberID];
          $this->ST->RawRecord[SessionMemberType]           = $this->MT->RawRecord[MemberType];
          $this->ST->RawRecord[SessionMemberActingType]     = $this->MT->RawRecord[MemberActingType];
          $this->ST->RawRecord[SessionMemberLevel]          = $this->MT->RawRecord[MemberLevel];
          $this->ST->RawRecord[SessionMemberSecurityLevel]  = $this->MT->RawRecord[MemberSecurityLevel];
          $this->ST->RawRecord[SessionMemberTrustLevel]     = $this->MT->RawRecord[MemberTrustLevel];
          $this->ST->RawRecord[SessionMemberFlags]          = $this->MT->RawRecord[MemberFlags]|0x80000000;
          $this->ST->RawRecord[SessionReq]                  = $_SERVER['REQUEST_METHOD'];
          $this->ST->UpdateItems(SessionMemberID,SessionMemberType,SessionMemberActingType,SessionMemberLevel,SessionTimeout,SessionMemberSecurityLevel,SessionMemberTrustLevel,SessionMemberFlags,SessionReq);
        }
      }


// Setup Site Options

      if (!isset($this->ST->RawRecord['SessionAccessID'])) $this->ST->RawRecord['SessionAccessID'] = 1;
//      $this->SCT->GetRecord('SiteControlID',$this->ST->RawRecord['SessionAccessID']);
//      echo 'Boogedy<br>';

// Setup Session PHP Error Logging
      if ($this->SCT->LogOption(SiteLogPHPErrors))
      { set_error_handler('LogPHPErrorHandler',E_ALL);
        error_reporting(E_ALL);
      }
      else
      { restore_error_handler();
        if (($this->SessionType & 8) == SessionTypeAdmin) error_reporting(E_ALL);
        else  error_reporting(0);
      }
// Final Session Table Updates

      $this->ST->RawRecord[SessionCount]  = (!empty($this->ST->RawRecord[SessionCount]))?$this->ST->RawRecord[SessionCount]+1:1;

      if ($New || !$this->SCT->SessionOption(SiteSessionOptionNoACCUpdate))
      { $this->ST->RawRecord[SessionAcc]         = time();
        $this->ST->RawRecord[SessionSiteStatus]  = (!empty($this->SCT->RawRecord[SiteStatus]))?$this->SCT->RawRecord[SiteStatus]:0;
      }

      $this->ChkSession();

      $this->ST->RawRecord[SessionAccessID]              = (!empty($this->ACT->RawRecord[AccessID]))?$this->ACT->RawRecord[AccessID]:0;
      $this->ST->RawRecord[SessionStatus]                = SessionOpen;
      $this->ST->RawRecord[SessionTimeout]               = (!empty($this->MT->RawRecord[MemberID]))?$this->MT->RawRecord[MemberTimeout]:1800;

      if (!empty($this->ST->RawRecord[SessionStart]))
        $this->ST->UpdateItems(SessionID,SessionStatus,SessionTimeout,SessionSiteStatus,SessionCount,SessionAccessID,SessionAcc);
      else
      { $this->ST->RawRecord[SessionStart] = time();
        $this->ST->UpdateItems(SessionID,SessionStatus,SessionTimeout,SessionSiteStatus,SessionCount,SessionType,SessionAccessID,SessionAcc,SessionStart);
      }
      if (!empty($this->MT->RawRecord[MemberID]))
      { $this->MT->RawRecord[MemberAccesses]++;
        $this->MT->RawRecord[MemberLastAcc]   = time();
        $this->MT->RawRecord[MemberSessionID] = $this->ID;
        $this->MT->UpdateItems(MemberID,MemberSessionID,MemberAccesses,MemberLastAcc,MemberActingType);
        $this->MemberID = $this->MT->RawRecord[MemberID];
      }
    }
//-----------------------------------------------------------------
//                        Resume Session
//-----------------------------------------------------------------
    function ResumeSession($ID=0)
    { if ($ID) $this->ST->RawRecord[SessionID] = $ID;
      if (!$this->ST->RawRecord[SessionID]) return false;
      $this->ST->RawRecord[SessionAcc]         = time();
      $this->ST->RawRecord[SessionStatus]      = SessionOpen;
      $this->ST->UpdateItems(SessionAcc,SessionStatus);
    }

//-----------------------------------------------------------------
//                        Timeout
//-----------------------------------------------------------------
    function TimeOutSession($ID=0)
    { if ($ID) $this->ST->RawRecord[SessionID] = $ID;
      $this->ST->RawRecord[SessionStatus]  = SessionTimedOut;
      if (!$this->ST->RawRecord[SessionID]) return false;
      $this->ST->RawRecord[SessionAcc]     = time();
      $this->ST->UpdateItems(SessionAcc,SessionStatus);
      echo  " <script>\r\n";
      echo  "   var dst = '",iPageLink('iTimeOut.php'),"';\r\n";
      echo  "   location.replace(dst);\r\n";
      echo  "  </script>\r\n";
    }

//-----------------------------------------------------------------
//                        Expire Session
//-----------------------------------------------------------------
    function ExpireSession($ID=0)
    { if ($ID) $this->ST->RawRecord[SessionID] = $ID;
      $this->ST->RawRecord[SessionStatus]  = SessionExpired;
      if (!$this->ST->RawRecord[SessionID]) return false;
      $this->ST->RawRecord[SessionAcc]     = time();
      $this->ST->UpdateItems(SessionAcc,SessionStatus);
      echo  " <script>\r\n";
      echo  "   var dst = '",iPageLink('iExpired.php'),"';\r\n";
      echo  "   location.replace(dst);\r\n";
      echo  "  </script>\r\n";
    }

//-----------------------------------------------------------------
//                        CloseSession
//-----------------------------------------------------------------
    function CloseSession()
    { if (empty($this->ST->RawRecord[SessionID])) return false;
      $this->EndAccess();
      $this->ST->RawRecord[SessionEnd]      = time();
      $this->ST->RawRecord[SessionStatus]   = SessionClosed;
      if (!$this->ST->UpdateItems(SessionEnd,SessionStatus)) return false;
      if ($this->ST->RawRecord[SessionType] == SessionTypeAdmin)
      { $this->SessionCookie    = self::AdminSessionCookie;
        $this->SessionVarCookie = self::AdminSessionVarCookie;

      }
      else
      { $this->SessionCookie    = self::SessionCookie;
        $this->SessionVarCookie = self::SessionVarCookie;

      }
      if (!empty($_COOKIE[$this->SessionVarCookie]) && ($_COOKIE[$this->SessionVarCookie]==session_id()))
      { session_write_close();
        if (!empty($_COOKIE[$this->SessionVarCookie]))
        { setcookie ($this->SessionVarCookie, "", time() - 3600,'/');
        }
        if (!empty($_COOKIE[$this->SessionCookie]))
        { setcookie ($this->SessionCookie, "", time() - 3600,'/');
        }
      }
      // Archive Session
      return true;
    }


//-----------------------------------------------------------------
//                              Check Open Sessions
//-----------------------------------------------------------------

//  Check Open Sessions

    function ChkOpenSessions()
    { $open;
      echo 'Checking Open Sessions<br>';
      $Records = $this->ST->GetRawItemsList(array(SessionID,SessionStatus,SessionAcc,SessionTimeout),'SessionStatus != 0');
      $Count = count($Records);
      if ($Count)
      { echo 'There are ',$Count,' Open Sessions<br>';
        for ($i=0;$i<$Count;$i++)
        { echo 'Checking Session ',$Records[$i][SessionID],'<br>';
          echo 'Session Status',$Records[$i][1],'<br>';
          if (!$Records[$i][0]) continue;  // Skip Bad Record
          if (($Records[$i][1] == 1) && (basename($this->Page) == 'index.php'))  // Close Index Page
          { echo 'Closing Session ',$Records[$i][0],'<br>';
            $this->CloseSession($Records[$i][0]);
            $open = false;
          }
          else
          { $ElapsedTime  = ($Records[$i][2])?time() - $Records[$i][2]:0;
            $Expired      = (($Records[$i][3]) && (($Records[$i][3]-$ElapsedTime) <= -1800))?true:false;
            if ($Expired)
            { echo 'Session ',$Records[$i][0],' Expired<br>';
              $this->CloseSession($Records[$i][0]);
            }
          }
        }
      }
      else echo $this->ST->error,'<br>';
      return $open;
    }

//-----------------------------------------------------------------
//                              Check Session
//-----------------------------------------------------------------

//  Check Session

    function ChkSession()
    {

// Session Found if it Exists or a New Session is being created

      if (!empty($this->ST->RawRecord[SessionStatus]) && ($this->ST->RawRecord[SessionStatus] > SessionOpen)) $this->ST->RawRecord[SessionStatus] = SessionOpen;

      if ($this->DynamicIP)
      { ini_set('session.use_cookies',1);                   // Must use Cookies.
        session_name (($this->Admin)?self::AdminSessionVarCookie:self::SessionVarCookie);
      }
      else ini_set('session.use_cookies',0);              // Don't use Cookies.

      if (!empty($this->ST->RawRecord[SessionVariable]))
        session_id($this->ST->RawRecord[SessionVariable]);   // Resume this Session.

      if (empty(session_id()))  session_start();                                    // Start the session.
      $this->ST->RawRecord[SessionVariable] = session_id();
      $this->BeginAccess();
      return true;
    }


//-----------------------------------------------------------------

//                        Login
//-----------------------------------------------------------------
    function Login($UserName,$Password,$SessionType,$Target='')
    { $temp = $this->ST->RawRecord;
      $this->ST->GetSessionByUser($UserName);
      if ($this->ST->RawRecord[SessionID]) return 1;
      $this->ST->RawRecord = $temp;
      $this->ST->RawRecord[SessionUserName]  = $UserName;
      $this->ST->RawRecord[SessionPassword]  = $Password;
      $this->ST->RawRecord[SessionType]      = $SessionType;
      $this->ST->RawRecord[SessionStatus]    = SessionOpen;
      $this->ST->UpdateItems(SessionUserName,SessionPassword,SessionType,SessionStatus);
      $this->SessionType                  = $SessionType;
      $this->Admin                        = (($SessionType & 7) >= SessionTypeAdmin);
      echo  " <script>\r\n";
      if (!empty($Target))
        echo  "   var dst = '",iPageLink($Target),"';\r\n";
      else
        echo  "   var dst = '",iPageLink('Info/index.php'),"';\r\n";
      echo  "   location.replace(dst);\r\n";
      echo  "  </script>\r\n";
      return 0;
    }

//-----------------------------------------------------------------
//                        Logging In
//-----------------------------------------------------------------
    function LoggingIn()
    { $this->ST->RawRecord[SessionStatus]     = SessionLoggingIn;
      if (!$this->ST->RawRecord[SessionID]) return false;
      $this->ST->RawRecord[SessionAcc]        = time();
      $this->ST->UpdateItems(SessionAcc,SessionStatus);
      return 0;
    }

//-----------------------------------------------------------------
//                        Logging In
//-----------------------------------------------------------------
    function Resume()
    { $this->ST->RawRecord[SessionStatus]     = SessionOpen;
      if (!$this->ST->RawRecord[SessionID]) return false;
      $this->ST->RawRecord[SessionAcc]        = time();
      $this->ST->UpdateItems(SessionAcc,SessionStatus);
      return 0;
    }

//-----------------------------------------------------------------
//                        Logging Out
//-----------------------------------------------------------------
    function LoggingOut()
    { $this->ST->RawRecord[SessionStatus]     = SessionLoggingOut;
      if (!$this->ST->RawRecord[SessionID]) return false;
      $this->ST->RawRecord[SessionAcc]        = time();
      $this->ST->UpdateItems(SessionAcc,SessionStatus);
      return 0;
    }

//-----------------------------------------------------------------
//                        Timed Out
//-----------------------------------------------------------------
    function TimedOut()
    { $this->ST->RawRecord[SessionStatus]     = SessionTimedOut;
      if (!$this->ST->RawRecord[SessionID]) return false;
      $this->ST->RawRecord[SessionAcc]        = time();
      $this->ST->UpdateItems(SessionAcc,SessionStatus);
      return 0;
    }

//-----------------------------------------------------------------
//                        Expired
//-----------------------------------------------------------------
    function Expired()
    { $this->ST->RawRecord[SessionStatus]   = SessionExpired;
      if (!$this->ST->RawRecord[SessionID]) return false;
      $this->ST->RawRecord[SessionAcc]      = time();
      $this->ST->UpdateItems(SessionAcc,SessionStatus);
      return 0;
    }

//-----------------------------------------------------------------
//                        Print Variables (Diagnostic)
//-----------------------------------------------------------------

    function PrintParameters()
    { echo 'Session ID = ',$this->ID,"<br>\r\n";
      echo 'Member ID = ',$this->MemberID,"<br>\r\n";

      echo 'Member Type = ',$this->MemberType,"<br>\r\n";

      echo 'Member Acting Type = ',$this->MemberActingType,"<br>\r\n";

      echo 'Width = ',$this->Width,"<br>\r\n";

      echo 'Height = ',$this->Height,"<br>\r\n";

      echo 'History = ',$this->History,"<br>\r\n";

      echo 'New Session = ',($this->NewSession)?'true':'false',"<br>\r\n";

      echo 'Super User = ',($this->SuperUser)?'true':'false',"<br>\r\n";

      echo 'Portrait = ',($this->Portrait)?'true':'false',"<br>\r\n";
      echo 'Mobile = ',($this->Mobile)?'true':'false',"<br>\r\n";
      echo 'Dynamic IP = ',($this->DynamicIP)?'true':'false',"<br>\r\n";
      echo 'Track = ',($this->Track)?'true':'false',"<br>\r\n";
      echo 'Admin = ',($this->Admin)?'true':'false',"<br>\r\n";
      echo 'Bot Flag = ',($this->BotFlag)?'true':'false',"<br>\r\n";
      echo 'No Terms = ',($this->NoTerms)?'true':'false',"<br>\r\n";
      echo 'No Sessions = ',($this->NoSessions)?'true':'false',"<br>\r\n";
      echo 'No Status Chk = ',($this->NoStatusChk)?'true':'false',"<br>\r\n";
      echo 'No Cookie Chk = ',($this->NoCookieChk)?'true':'false',"<br>\r\n";
      echo 'No Timer = ',($this->NoTimer)?'true':'false',"<br>\r\n";
      echo 'Terms Warning = ',($this->TermsWarning)?'true':'false',"<br>\r\n";
      echo 'Monitored = ',($this->Monitored)?'true':'false',"<br>\r\n";
      echo 'Debugging = ',($this->Debugging)?'true':'false',"<br>\r\n";
      echo 'Debuggable = ',($this->Debuggable)?'true':'false',"<br>\r\n";
      echo 'Accredited = ',($this->Accredited)?'true':'false',"<br>\r\n";
      echo 'NDA = ',($this->NDA)?'true':'false',"<br>\r\n";
      echo 'EPCNDA = ',($this->EPCNDA)?'true':'false',"<br>\r\n";
      echo 'Site Acc = ',($this->SiteAcc)?'true':'false',"<br>\r\n";
      echo 'EPC Acc = ',($this->EPCAcc)?'true':'false',"<br>\r\n";
      echo 'Board Acc = ',($this->BoardAcc)?'true':'false',"<br>\r\n";
      echo 'Auto Start = ',($this->AutoStart)?'true':'false',"<br>\r\n";
      echo 'Small Screen = ',($this->SmallScreen)?'true':'false',"<br>\r\n";
      echo 'SSL = ',($this->SSL)?'true':'false',"<br>\r\n";
      echo 'Page = ',$this->Page,"<br>\r\n";
      echo 'Query = ',$this->Query,"<br>\r\n";
    }

    function PrintTiming()
    { foreach ($this->Timing as $key => $Timing)
      { echo $key,': ',$this->Timing[$key],'<br>';
      }
    }
  }
//-----------------------------------------------------------------
//                        PHP Error Handlers
//-----------------------------------------------------------------

  function CustomErrorHandler()
  { if(@is_array($error = @error_get_last()))
    { return(@call_user_func_array('ErrorHandler', $error));
    }

    return(false);
  }

  function ErrorHandler($type, $message, $file, $line)
  { $_ERRORS = Array(
    0x0001 => 'E_ERROR',
    0x0002 => 'E_WARNING',
    0x0004 => 'E_PARSE',
    0x0008 => 'E_NOTICE',
    0x0010 => 'E_CORE_ERROR',
    0x0020 => 'E_CORE_WARNING',
    0x0040 => 'E_COMPILE_ERROR',
    0x0080 => 'E_COMPILE_WARNING',
    0x0100 => 'E_USER_ERROR',
    0x0200 => 'E_USER_WARNING',
    0x0400 => 'E_USER_NOTICE',
    0x0800 => 'E_STRICT',
    0x1000 => 'E_RECOVERABLE_ERROR',
    0x2000 => 'E_DEPRECATED',
    0x4000 => 'E_USER_DEPRECATED'
    );

    if(!@is_string($name = @array_search($type, @array_flip($_ERRORS))))
    { $name = 'E_UNKNOWN';
    }

    print(@sprintf("%s Error in file &raquo;%s&laquo; at line %d: %s\n", $name, @basename($file), $line, $message));
    echo '<br>';
    echo '<br>';
//    debug_print_backtrace();
/*    $f = file_get_contents($file);
    $file = explode("\r\n",$f);

    foreach ($file as $key => $line) echo $key,':  ',$line,'<br>';

    echo $file[$line-2],'<br>';
    echo $file[$line-1],'<br>';
    echo '&raquo;',$file[$line],'<br>';
    echo $file[$line+1],'<br>';
    echo $file[$line+2],'<br>';
*/
    return false;
  }

  function ShutdownHandler()
  { if(@is_array($error = @error_get_last()))
    { return(@call_user_func_array('ShutdownErrorHandler', $error));
    }

    return(TRUE);
  }

  function ShutdownErrorHandler($type, $message, $file, $line)
  { $_ERRORS = Array(
    0x0001 => 'E_ERROR',
    0x0002 => 'E_WARNING',
    0x0004 => 'E_PARSE',
    0x0008 => 'E_NOTICE',
    0x0010 => 'E_CORE_ERROR',
    0x0020 => 'E_CORE_WARNING',
    0x0040 => 'E_COMPILE_ERROR',
    0x0080 => 'E_COMPILE_WARNING',
    0x0100 => 'E_USER_ERROR',
    0x0200 => 'E_USER_WARNING',
    0x0400 => 'E_USER_NOTICE',
    0x0800 => 'E_STRICT',
    0x1000 => 'E_RECOVERABLE_ERROR',
    0x2000 => 'E_DEPRECATED',
    0x4000 => 'E_USER_DEPRECATED'
    );

    if(!@is_string($name = @array_search($type, @array_flip($_ERRORS))))
    { $name = 'E_UNKNOWN';
    }

    print(@sprintf("Shutdown %s Error in file &raquo;%s&laquo; at line %d: %s\n", $name, @basename($file), $line, $message));
    echo '<br>';
    echo '<br>';
//    debug_print_backtrace();
/*    $f = file_get_contents($file);
    $file = explode("\r\n",$f);

    foreach ($file as $key => $line) echo $key,':  ',$line,'<br>';

    echo $file[$line-2],'<br>';
    echo $file[$line-1],'<br>';
    echo '&raquo;',$file[$line],'<br>';
    echo $file[$line+1],'<br>';
    echo $file[$line+2],'<br>';
*/
    return false;
  }

  $Session = new Session();
  $Stop;
?>
