Location: PHPKode > projects > Slashster > slashster/html/PageClass.php
<?

# Slashster: Open Source Friend of a Friend Software
# Copyright 2004 Mark El-Wakil
# Contact: hide@address.com
# http://seventhcycle.net
#
# This file is part of Slashster.
#
# Slashster is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Slashster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Slashster; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA





class PageClass
{
   var $svr;
   var $IdNum;
   var $Admin;
   var $LoggedIn;
   var $Username;
   var $CSS;

   var $stdurl;
   var $sstdurl;

   var $adm = array();
   var $sql = array();

   var $BadPassword;
   var $Verified;
   var $SessionId;
   var $user;        // SG equivalent of nfo

   var $newsnumperpage = 5;

   var $Friend = array(); // your friend / foe   list
   var $NetworkSize;

   var $exec_arr = array();
   var $var_arr;      

   var $popuparr = array(); // popup messages.

   var $UsersOnSite = array();

   var $initvar = 0;
   var $TitleTag;

   var $t1;
   var $t2;


   // All QueryClass integrated stuff

   var $svr_msconnect;
   var $svr_numq;
   var $svr_qustore  = array();
   var $svr_tmestore = array();
   var $svr_debug;


   function PageClass($nl = "sc_standard")
   {

       $this->t1 = $this->getmicrotime();
       $this->Initialize($nl);
   }

   function getmicrotime()
   {
       // now *this* is something from PHP.net 

       list($usec, $sec) = explode(" ",microtime());
       return ((float)$usec + (float)$sec);
   }

   function InitVars()
   {
          $this->initvar = 1;

          $sqldbg = 0;

          $this->exec_arr["sc_standard"] = array();
          $this->exec_arr["sc_standard"]["makesession"]  = 1;
          $this->exec_arr["sc_standard"]["openpage"]     = 1;
          $this->exec_arr["sc_standard"]["closepage"]    = 1;
          $this->exec_arr["sc_standard"]["sqldebug"]     = $sqldbg;
          $this->exec_arr["sc_standard"]["inifile"]      = "siteinfo.php";
          $this->exec_arr["sc_standard"]["authorize"]    = 1;
          $this->exec_arr["sc_standard"]["friendfoe"]    = 1;


          $this->exec_arr["sessiononly"] = array();
          $this->exec_arr["sessiononly"]["makesession"]  = 1;
          $this->exec_arr["sessiononly"]["inifile"]      = "siteinfo.php";

          $this->exec_arr["sqlonly"] = array();
          $this->exec_arr["sqlonly"]["sqlsetup"]  = 1;
          $this->exec_arr["sqlonly"]["inifile"]  = "siteinfo.php";


          $this->exec_arr["authonly"] = array();
          $this->exec_arr["authonly"]["makesession"]  = 1;
          $this->exec_arr["authonly"]["sqldebug"]     = $sqldbg;
          $this->exec_arr["authonly"]["inifile"]      = "siteinfo.php";
          $this->exec_arr["authonly"]["authorize"]    = 1;
          $this->exec_arr["authonly"]["friendfoe"]    = 1;

          $this->exec_arr["authremainder"] = array();
          $this->exec_arr["authremainder"]["openpage"]  = 1;   
          $this->exec_arr["authremainder"]["closepage"] = 1;
          $this->exec_arr["authremainder"]["inifile"]   = "siteinfo.php";
          $this->exec_arr["authremainder"]["sqldebug"]  = $sqldbg;


   }


   function Initialize($nl)
   {
       if (!$this->initvar) $this->InitVars();  // always called
       $this->var_arr = $this->exec_arr[$nl];

       require_once($this->var_arr["inifile"]);

       $this->sys[SSL] = ($this->sys[UseSSL] && function_exists("openssl_pkey_new"))
                       ? 1 : 0;


       $this->stdurl  = $this->sys[normalurl];
       $this->sstdurl = $this->sys[secureurl];    


       if ($this->var_arr["makesession"]) $this->SessionSetup();
       if ($this->var_arr["authorize"])   $this->SetupInfo();


       if ($this->LoggedIn)
       {
           $sql = "update UserTable set LastSeen = NOW() where Id = $this->IdNum";
           $this->DoQuery($sql);

           if ($this->var_arr["friendfoe"])    $this->GetFanList();

           if ($_SESSION[lgpost])
           {
                $_POST = $_SESSION[lgpost];
                $_SESSION[lgpost] = "";
           }

           if (!$this->user[SessionAES]) $_SESSION[AES] = "";

       }
       else
       {
           $_SESSION["flv-1"]  = array();
           $_SESSION["flv-2"]  = array();
           $_SESSION["flv-3"]  = array();
           $_SESSION["flv-4"]  = array();
           $_SESSION[lastread] = "";
       }


       $_SESSION[LoggedIn] = ($this->LoggedIn) ? 1 : 0;

       if ($this->var_arr["openpage"])     $this->OpenPage();
   }

   function UserDistance($v)
   {
       $level = -1;
       foreach ($this->Friend as $k => $f)
          if ($f[$v]) $level = $k;

       return $level;
   }

   function GetFanList()
   {
       $tarr = array($this->IdNum);

       $this->Friend[0] = array();
       $this->Friend[1] = array();
       $this->Friend[2] = array();
       $this->Friend[3] = array();
       $this->Friend[4] = array();

       $this->Friend[0][$this->IdNum] = $this->IdNum;
       $tarr = array($this->IdNum);

       $slr = $_SESSION[lastread];
       $qgg = filemtime($this->sys[siteroot] . "friendlist/" . $this->IdNum . ".txt");

       $cn = 1;
       $this->NetworkSize = 0;


       if (!$slr || ($slr < $qgg))
       {
            $fl = file($this->sys[siteroot] . "friendlist/" . $this->IdNum . ".txt");
              
            foreach ($fl as $f)
            {
                $f = trim($f);
                $exp = explode(",",$f);
       
                foreach ($exp as $e)
                    if (is_numeric($e)) $this->Friend[$cn][$e] = $e;
   
                $_SESSION["flv-" . $cn] = $this->Friend[$cn];
    
                $this->NetworkSize += sizeof($this->Friend[$cn]);
       
                $cn++;
            }

            $_SESSION[lastread] = time();       
            return;
       }


       while ( sizeof( $_SESSION["flv-" . $cn] ) )
       {
           $this->Friend[$cn] = $_SESSION["flv-" . $cn];
           $this->NetworkSize += sizeof($this->Friend[$cn]);
           $cn++;
       }

   }




   function PrintSnippit($keyname, $arr=array())
   {
       ob_start();
       @readfile($this->sys[siteroot] . "html/snippits/$keyname.txt");
       $sn = ob_get_contents();
       ob_end_clean();

       foreach ($this->sys as $k=>$v)
       {
           $sn = str_replace("#sys_$k#", $v, $sn); 
       }

       foreach ($arr as $k => $v)
       {
           $sn = str_replace("#$k#", $v, $sn);
       }
       return $sn;
   }

   function PrintForm($keyname)
   {
      $body  = $this->PrintSnippit($keyname);
      $body = str_replace("\n", "<BR>", $body);

     ?>
      <table width=100%>
          <tr><td><?= $body ?></td></tr>
      </table>

   <? }





   function SetupInfo()
   {
      if (!$_SESSION[userid])
      {
          $this->IdNum = 0;
          $this->Admin = 0;
          $this->LoggedIn = 0;

          if ($_GET[key])
          {
              $sql = "select * from Keyword where KeyN = \"$_GET[key]\" ";
              $keyw= $this->DoQuery($sql,1);

              if (sizeof($keyw))
              {
                  $sql = "update Keyword set Count=Count+1 where Id=" . $keyw[0][Id];
                  $this->DoQuery($sql);

                  $_SESSION[CSS] = $keyw[0][CSS];
              }
          }

          $_SESSION[CSS] = ($_SESSION[CSS]) ? $_SESSION[CSS] 
                         : $this->sys[cssarr][array_rand($this->sys[cssarr])];
          $this->CSS = $_SESSION[CSS];                 

          $this->Username = "ANONYMOUS";
          return;
      }

      $sql = "select * from UserTable where Id = " . $_SESSION[userid];
      $this->user = $this->DoQuery($sql,1);

      $this->user = $this->user[0];

      $_SESSION[CSS]  = $this->user[CSS];
      $this->CSS      = $this->user[CSS];            
      $this->Username = $this->user[Login];
      $this->IdNum    = $this->user[Id];
      $this->Admin    = $this->user[Admin];
      $this->Verified = $this->user[Verified];
      $this->LoggedIn = 1;      

      return;
   }


   function SQLinit($debug = 0)
   {
        $numq =0;
        $this->svr_debug = $this->var_arr["sqldebug"];
        
if ($_SERVER[REMOTE_ADDR] == "64.81.83.205")
{
   //print_r($this->sql);
}


        $this->svr_msconnect = @mysql_connect($this->sql[db_host], $this->sql[db_login], $this->sql[db_pass]);

        @mysql_select_db($this->sql[db_data]);

        if (!$this->svr_msconnect)
        {
           echo mysql_error();
           exit;
        }
   }

   function DoQuery($sql, $assoc=0)
   {
        if (!$this->svr_msconnect) $this->SQLinit();


        if ($this->svr_debug)
        {
          array_push($this->svr_qustore, $sql);
          $t1 = $this->getmicrotime();
        }

        $result = mysql_query($sql, $this->svr_msconnect);

        if ($this->svr_debug)
        {
          $t2 = $this->getmicrotime(); 
          array_push($this->svr_tmestore, $t2 - $t1);
        }

        if (mysql_errno())
        {
            $errl = debug_backtrace();
            $line = $errl[0][line];
            $fle  = $errl[0][file];

            ?>

           <table align=center border=1 cellspacing=0 width=500>
              <tr><td colspan=2 align=center><B>Error in MySQL</b></td></tr>
              <tr><td><B>Query</b></td>
                  <td><?= $sql ?></td>
              </tr>
              <tr><td><B>MySQL Error</b></td>
                  <td><?= mysql_error() ?></td>
              </tr>
              <tr><td><B>File</b></td>
                  <td><?= $fle ?></td>
              </tr>
              <tr><td><B>Line</b></td>
                  <td><?= $line ?></td>
              </tr>   
           </table>

           <?

            $sq  = mysql_escape_string($sql);
            $err = mysql_escape_string(mysql_error()); 

            $sql = "insert into ErrorLog set Sql = '$sq', Error = '$err', Sname='$_SERVER[SCRIPT_NAME]',
                    LineNum=\"$line\"";
            mysql_query($sql);

            exit;
        }

        $this->svr_numq++;
         
        if ($result === TRUE) return array();
        
        $res = array();

        
        if ($assoc)
            while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
                array_push($res, $row);
        else
            while ($row = mysql_fetch_row($result)  ) 
                array_push($res, $row);

        return $res;
   }

   function SQL_Stats()
   {
        if (!$this->svr_msconnect) return;

        $cnt = 0;
        ?>       
             <table border = 1>
             <tr><th colspan = 2>SeventhCycle's SQL debug table
             <BR> (Ignore this, he's doing tests on this page right now)
             </th></tr>
             <? for ($x = 0; $x < sizeof($this->svr_qustore); $x++) {
                $cnt += $this->svr_tmestore[$x];
             ?>
             <tr><td><?= $this->svr_tmestore[$x] ?></td><td><?= $this->svr_qustore[$x] ?></td></tr>
             <? } ?>  
             <tr><td><B>Total in SQL</b></td><td>
             <?= $cnt ?> 
             </td></tr>
             </table>
        <?
   }


   function SessionSetup()
   {
//       header("Pragma: no-cache");

       if ($_COOKIE['PHPSESSID'])
          $idins = $_COOKIE['PHPSESSID'];
       elseif ($_GET['PHPSESSID'])
          $idins = $_GET['PHPSESSID'];
       elseif ($_POST['PHPSESSID'])
          $idins = $_POST['PHPSESSID'];
       else
          $idins = md5(microtime() . $_SERVER['REMOTE_ADDR']);

       if (!$_COOKIE['PHPSESSID']) session_id($idins);
          session_start();

       $this->SessionId = $idins;
   }


   function OpenPage()
   {
       if (!$this->TitleTag)
       {
           $this->TitleTag = $this->sys[sitename];
       }

       require("top.php");
   }

   function ClosePage()
   {
       if ($this->var_arr["closepage"]) require("bot.php");
       if ($this->var_arr["sqldebug"] && $this->Admin) $this->SQL_Stats();

       if ($this->var_arr["closepage"])
       {
          if ( function_exists("memory_get_usage") )
          {
             echo "<!-- " . memory_get_usage() . " Bytes memory. -->\n";
          }
          $this->t2 = $this->getmicrotime();
          $t3 = $this->t2 - $this->t1;
          echo "<!-- $t3 seconds -->";
       }

       exit;
   }



   function FileUpload($filename, $filetype, $allow = array())
   {
       if (sizeof($allow) > 0)
       {
          $keep = 0;
          foreach ($allow as $a)
          {
             if ($filetype == $a) $keep = 1;
          }

          if (!$keep)
          {
              $this->PrintForm("WrongFileType");
              @unlink($filename);
              $this->ClosePage();
          }
       }

       return fread(fopen($filename, "r"), filesize($filename));
   }

   function MailSchedule($from, $to, $subject, $body, $expires=0, $now=0, $pbox=1, $encrypt=0)
   {
       $subject = addslashes($subject);   
   
       $body = stripslashes($body);
       $body = $this->bbc($body);
       $body = addslashes($body);
             
       $subject = strip_tags($subject); 
       $subject = addslashes($subject);

       $encrypt = ($this->sys[SSL]) ? $encrypt : 0;

       if ($encrypt)
       {
           $sql = "select * from UserTable where Id = $to AND AES != \"\"";
           $r = $this->DoQuery($sql,1);

           if (sizeof($r))
           {
                $ke = $r[0][PublicKey];
                $body = stripslashes($body);
                openssl_public_encrypt($body, $body, $ke);
                $body = base64_encode($body);
                $encrypt = 1;
           }
           else
           {
                $encrypt = 0;
           }
       }


       $sql = "insert into Scheduler set
                  MailFrom  = \"$from\",    MailTo = \"$to\",
                  Subject   = \"$subject\", Body   = \"$body\",
                  Expire    = \"$expires\", DeliverNow = \"$now\", Pbox=$pbox,
                  Encrypted=\"$encrypt\"  ";
       $this->DoQuery($sql);

       touch($this->sys[siteroot] . "cron/tmp/ismail.txt");
   }


   function OldNews($cnt)
   {
       $r = ceil($cnt / $this->newsnumperpage);

       if ($r < 2) return;
  
       $pge = ($_GET[pge] >= 1) ? floor($_GET[pge]) : 1;


?>

<BR>
    <table border=1 width=100% cellspacing=0 cellpadding=0>
<tr><td align=center class="stdtable">
<B>News Page <?= $pge ?></b>
</td></tr>

<form method=get>
<tr><td align=center class="stdaltfilling">
<select name=pge>
<? for ($x = 1; $x <= $r; $x++) { ?>
  <? if ($x != $pge) { ?>
  <option value="<?= $x ?>">Page <?= $x ?>
  <? } ?>
<? } ?>
</select>
<BR>
<input class="submit" type="submit" value="Make It So!">
</td></tr>
</form>
</table>

<?


   }


   function SideBar($cnt)
   {
      $this->OldNews($cnt); 
      require_once("rssmodule.php"); 
   }



   function CapsPercentage($o)
   {
       $len = strlen($o);
       $lgn = 0;

       if ($len == 0) return 0;

       $gt = preg_split('//', $o, -1, PREG_SPLIT_NO_EMPTY);

       foreach ($gt as $g)
       {
           if ((ord($g) >= 65) && (ord($g) <= 90)) $lgn++;
       }

       return $lgn / $len * 100;
   }



function GetOptions($sel)
{
   $arr = array();
   
   $sql = "select * from BoardSections order by Head asc, BoardName asc";
   $r = $this->DoQuery($sql,1);

   foreach ($r as $s)
   {
       if ($s[Head] == 0)
       {
           $arr[$s[Id]] = array();
           $arr[$s[Id]][Name] = $s[BoardName];
           $arr[$s[Id]][Sub] = array();
       }
       else
       {
           array_push($arr[$s[Head]][Sub], $s);
       }
   }

   foreach ($arr as $k=>$v)
   {
       echo "<option value=$k ";
       if ($sel == $k) echo "selected";
       echo ">$v[Name]</option>";
       foreach ($v[Sub] as $u)
       {
           echo "<option value=$u[Id] ";
           if ($sel == $u[Id]) echo "selected";
           echo ">&nbsp;&nbsp;&nbsp;&nbsp;$u[BoardName]</option>";
       }
   }

}


   function PrintBio($bio)
   {
      $txt2 = stripslashes($bio);
      $txt2 = $this->bbc($txt2);
      return $txt2;
   }

   function MembersOnly()
   {

       if (!$this->LoggedIn)
       {
           $_SESSION[lgdest] = $_SERVER[SCRIPT_NAME];
           $_SESSION[lgqstr] = $_SERVER[QUERY_STRING];

           $_SESSION[lgpost] = $_POST;

           header("Location: login.php");
           exit;
       }
   }

   function VerifiedOnly()
   {
       if (!$this->user[Verified])
       {
           header("Location: verify.php?warn=1&" . sid);
           exit;
       }
   }


   function FriendRequest($start, $end)
   {
        $sql = "select * from UserTable where Id = \"$start\" ";
        $s = $this->DoQuery($sql,1);
        $s = $s[0];

        $sql = "select * from UserTable where Id = \"$end\" ";
        $e = $this->DoQuery($sql,1);
        $e = $e[0];

        $txt = $this->PrintSnippit("FriendRequest");

        foreach ($s as $k=>$v) 
           $txt = str_replace("#f$k#", $v, $txt);

        foreach ($e as $k=>$v)
           $txt = str_replace("#t$k#", $v, $txt);

        $this->MailSchedule($s[Id], $e[Id], "New Friend Request", $txt, 1,0);

        $sql = "insert into FriendRequest set Start=$s[Id], End=$e[Id]";
        $this->DoQuery($sql);


   }

   function TestimonialRequest($start, $end, $tt)
   {
        $sql = "select * from UserTable where Id = \"$start\" ";
        $s = $this->DoQuery($sql,1);
        $s = $s[0];

        $sql = "select * from UserTable where Id = \"$end\" ";
        $e = $this->DoQuery($sql,1);
        $e = $e[0];

        $txt = $this->PrintSnippit("TestimonialRequest");

        foreach ($s as $k=>$v) 
           $txt = str_replace("#f$k#", $v, $txt);

        foreach ($e as $k=>$v)
           $txt = str_replace("#t$k#", $v, $txt);


        $this->MailSchedule($s[Id], $e[Id], "New Testimonial", $txt, 1,0);

        $sql = "insert into Testimonials set Start=$s[Id], End=$e[Id], Txt=\"$tt\", Dte=NOW()";
        $this->DoQuery($sql);
   }


   function AddFriend($start, $end, $confdeny)
   {
        $sql = "select * from UserTable where Id = \"$start\" ";
        $s = $this->DoQuery($sql,1);
        $s = $s[0];

        $sql = "select * from UserTable where Id = \"$end\" ";
        $e = $this->DoQuery($sql,1);
        $e = $e[0];

        $nme = ($confdeny) ? "ConfirmFriend" : "DenyFriend";
        $eml = ($confdeny) ? "Confirmed" : "Denied";

        $txt = $this->PrintSnippit($nme);

        foreach ($s as $k=>$v)
           $txt = str_replace("#f$k#", $v, $txt);

        foreach ($e as $k=>$v)
           $txt = str_replace("#t$k#", $v, $txt);

        $this->MailSchedule($s[Id], $e[Id], "Friendship $eml", $txt, 1,0);

        if ($confdeny)
        {
           $sql = "replace into FriendTable set Start=$s[Id], End=$e[Id]";
           $this->DoQuery($sql);

           $sql = "replace into FriendTable set Start=$e[Id], End=$s[Id]";
           $this->DoQuery($sql);
        }

        $sql = "update UserTable set UpdNow=1 where Id = \"$s[Id]\" ";
        $this->DoQuery($sql);

        $sql = "update UserTable set UpdNow=1 where Id = \"$e[Id]\" ";
        $this->DoQuery($sql);

        $sql = "delete from FriendRequest where End=$start AND Start=$end";
        $this->DoQuery($sql);

   }

   function CalcKarma($a, $b)
   {
       $numdays = floor( (time() - $b) / (24 * 3600) );
       return floor($a / ($numdays+1 * .9));
   }
   
   function PicPr($a, $b="0")
   {
       if (!$a) return "$a-".$this->CSS;

       return "$a-$b";
   }

   function RandomChars($number)
   {
        list($usec, $sec) = explode(' ', microtime());
        $sdnum = (float) $sec + ((float) $usec * 100000);
        mt_srand($sdnum);

        while (strlen($ret) < $number)
        {
           $letter = chr(  mt_rand(48, 123) );
           if (preg_match("/\w/", $letter) && $letter != "_") $ret .= $letter;
        }

        return $ret;
   }


   function bbc($string) 
   {
        $string = trim($string);
        if (is_null($string) || empty($string)) return ("");
        $result = "";

        // Iterate over lines
        foreach( explode("\n", $string) as $line) 
        {
            $styles = array( "b" => "strong", "i" => "em", "u" => "u" );

            // preserve B, I, U
            foreach( $styles as $code => $html) 
            {
                $line = preg_replace("/\[" . $code . "\]/i", "<" . $html .">", $line);
                $line = preg_replace("/\[\/" . $code . "\]/i", "</" . $html .">", $line);
            }

            // URL
            $line = preg_replace("/\[URL\]([^\[]+?)\[\/URL\]/i",   "<a href=\"\\1\">\\1</a>", $line);
            $line = preg_replace("/\[URL=(.*?)\](.+?)\[\/URL\]/i", "<a href=\"\\1\">\\2</a>", $line);

            // IMG
            $line = preg_replace("/\[IMG=(.*?)\]/i", "<img src=\"\\1\" />", $line);
            
            $result .= sprintf("%s<br />\n", $line);
        }

        return ($result);
   }


   function MakeCert($id, $passwd)
   {
      if (!$this->sys[SSL]) return;


      $dn = array(
                "countryName"            => $this->adm[country],
                "stateOrProvinceName"    => $this->adm[state],
                "localityName"           => $this->adm[city],
                "organizationName"       => $this->adm[orgname],
                "organizationalUnitName" => $this->adm[orgunitname],
                "commonName"             => $this->adm[name],
                "emailAddress"           => $this->adm[email]
      );

      $privkey = openssl_pkey_new();
      $csr = openssl_csr_new($dn, $privkey);

      $sscert = openssl_csr_sign($csr, null, $privkey, 365*20);

      openssl_csr_export($csr, $csrout);
      openssl_x509_export($sscert, $certout);
      openssl_pkey_export($privkey, $pkeyout);

      $aes = "VALIDAESKEY" . $this->RandomChars(100);

      $sql = "lock tables UserTable write";
      $this->DoQuery($sql);

      $sql = "update UserTable set 
                  AES = AES_ENCRYPT('$aes', '$passwd'),
                  PrivateKey = AES_ENCRYPT('$pkeyout', '$aes'),
                  PublicKey = \"$certout\" where Id = \"$id\" ";

      $this->DoQuery($sql);

      $sql = "select * from UserTable where Id = $id";
      $r = $this->DoQuery($sql,1);
      $r = $r[0];

      $aes = base64_encode($r[AES]);
      $pri = base64_encode($r[PrivateKey]);

      $sql = "update UserTable set AES=\"$aes\", PrivateKey=\"$pri\" where Id = $id";
      $this->DoQuery($sql);           

      $sql = "unlock tables";
      $this->DoQuery($sql);

   }




}

/* end of class */



?>
Return current item: Slashster