Zikula_Core
[ class tree: Zikula_Core ] [ index: Zikula_Core ] [ all elements ]

Source for file SessionUtil.class.php

Documentation is available at SessionUtil.class.php

  1. <?php
  2. /**
  3.  * Zikula Application Framework
  4.  *
  5.  * @copyright (c) 2001, Zikula Development Team
  6.  * @link http://www.zikula.org
  7.  * @version $Id: SessionUtil.class.php 24342 2008-06-06 12:03:14Z markwest $
  8.  * @license GNU/GPL - http://www.gnu.org/copyleft/gpl.html
  9.  * @package Zikula_Core
  10.  * @subpackage SessionUtil
  11. */
  12.  
  13.  
  14. /**
  15.  * SessionUtil
  16.  *
  17.  * @package Zikula_Core
  18.  * @subpackage SessionUtil
  19.  */
  20. {
  21.     /**
  22.      * Set up session handling
  23.      * Set all PHP options for Zikula session handling
  24.      *
  25.      * @return void 
  26.      */
  27.     function _setup()
  28.     {
  29.         $path pnGetBaseURI();
  30.         if (empty($path)) {
  31.             $path '/';
  32.         elseif (substr($path-11!= '/'{
  33.             $path .= '/';
  34.         }
  35.  
  36.         $host pnServerGetVar('HTTP_HOST');
  37.  
  38.         if (($pos=strpos($host':')) !== false{
  39.             $host substr($host0$pos);
  40.         }
  41.  
  42.         // PHP configuration variables
  43.         ini_set('session.use_trans_sid'0);         // Stop adding SID to URLs
  44.         @ini_set('url_rewriter.tags''');           // some environments dont allow this value to be set causing an error that prevents installation
  45.         ini_set('session.serialize_handler''php')// How to store data
  46.         ini_set('session.use_cookies'1);           // Use cookie to store the session ID
  47.         ini_set('session.auto_start'1)// Auto-start session
  48.  
  49.         ini_set('session.name'SessionUtil::getCookieName());      // Name of our cookie
  50.  
  51.         // Set lifetime of session cookie
  52.         $seclevel pnConfigGetVar('seclevel');
  53.         switch ($seclevel{
  54.             case 'High':
  55.                 // Session lasts duration of browser
  56.                 $lifetime 0;
  57.                 // Referer check
  58.                 // ini_set('session.referer_check', $host.$path);
  59.                 ini_set('session.referer_check'$host);
  60.                 break;
  61.             case 'Medium':
  62.                 // Session lasts set number of days
  63.                 $lifetime pnConfigGetVar('secmeddays'86400;
  64.                 break;
  65.             case 'Low':
  66.             default :
  67.                 // Session lasts unlimited number of days (well, lots, anyway)
  68.                 // (Currently set to 25 years)
  69.                 $lifetime 788940000;
  70.                 break;
  71.         }
  72.         ini_set('session.cookie_lifetime'$lifetime);
  73.  
  74.         // domain and path settings for session cookie
  75.         // if (pnConfigGetVar('intranet') == false) {
  76.         // Cookie path
  77.         ini_set('session.cookie_path'$path);
  78.  
  79.         // Garbage collection
  80.         ini_set('session.gc_probability'pnConfigGetVar('gc_probability'));
  81.         ini_set('session.gc_divisor'10000);
  82.         ini_set('session.gc_maxlifetime'pnConfigGetVar('secinactivemins'60)// Inactivity timeout for user sessions
  83.  
  84.         // change session hash length according to PHP version
  85.         // (uncommend this line after 0.8.0.0 is released - ini_set('session.hash_function', (((float)phpversion() >= 5) ? 1 : 0));
  86.         ini_set('session.hash_function'0);
  87.  
  88.         // Set custom session handlers
  89.         ini_set('session.save_handler''user');
  90.         if (pnConfigGetVar('sessionstoretofile')) {
  91.             ini_set('session.save_path'pnConfigGetVar('sessionsavepath'));
  92.         }
  93.         // PHP 5.2 workaround
  94.         if (version_compare(phpversion()'5.2.0''>=')) {
  95.             register_shutdown_function('session_write_close');
  96.         }
  97.         // Do not call any of these functions directly.  Marked as private with _
  98.         session_set_save_handler('_SessionUtil__Start',
  99.                                  '_SessionUtil__Close',
  100.                                  '_SessionUtil__Read',
  101.                                  '_SessionUtil__Write',   /* use session_write_close(); */
  102.                                  '_SessionUtil__Destroy'/* use session_destroy(); */
  103.                                  '_SessionUtil__GC');
  104.     }
  105.  
  106.  
  107.     /**
  108.      * Initialise session
  109.      *
  110.      * @return bool 
  111.      */
  112.     function initialize()
  113.     {
  114.         SessionUtil::_setup();
  115.  
  116.         // First thing we do is ensure that there is no attempted pollution
  117.         // of the session namespace
  118.         if (ini_get('register_globals')) {
  119.             foreach($GLOBALS as $k => $v{
  120.                 if (substr($k04== 'PNSV'{
  121.                     return false;
  122.                 }
  123.             }
  124.         }
  125.  
  126.         // create IP finger print
  127.         $current_ipaddr '';
  128.         $_REMOTE_ADDR pnServerGetVar('REMOTE_ADDR');
  129.         $_HTTP_X_FORWARDED_FOR pnServerGetVar('HTTP_X_FORWARDED_FOR');
  130.  
  131.         if (pnConfigGetVar('sessionipcheck')) {
  132.             /* -- feature for after 0.8 release - drak
  133.             // todo - add dropdown option for sessionipcheckmask for /32, /24, /16 CIDR
  134.  
  135.             $ipmask = pnConfigGetVar('sessionipcheckmask');
  136.             if ($ipmask <> 32) {
  137.                 // since we're not a /32 we need to handle in case multiple ips returned
  138.                 if ($_HTTP_X_FORWARDED_FOR && strstr($_HTTP_X_FORWARDED_FOR, ', ')) {
  139.                     $_ips = explode(', ', $_HTTP_X_FORWARDED_FOR);
  140.                     $_HTTP_X_FORWARDED_FOR = $_ips[0];
  141.                 }
  142.  
  143.                 // apply CIDR mask to allow IP checks on clients assigned
  144.                 // dynamic IP addresses - e.g. A O *cough* L
  145.                 if ($ipmask == 24) {
  146.                     $_REMOTE_ADDR = preg_replace('/[^.]+.$/', '*', $_REMOTE_ADDR);
  147.                     $_HTTP_X_FORWARDED_FOR = ($_HTTP_X_FORWARDED_FOR ? preg_replace('/[^.]+.$/', '*', $_HTTP_X_FORWARDED_FOR) : '');
  148.                 } else if ($ipmask == 16) {
  149.                     $_REMOTE_ADDR = preg_replace('/[0-9]*.\.[^.]+.$/', '*', $_REMOTE_ADDR);
  150.                     $_HTTP_X_FORWARDED_FOR = ($_HTTP_X_FORWARDED_FOR ? preg_replace('/[0-9]*.\.[^.]+.$/', '*', $fullhost) : '');
  151.                 } else { // must be a /32 CIDR
  152.                     null; // nothing to do
  153.                 }
  154.             }
  155.             */
  156.         }
  157.  
  158.         // create the ip fingerprint
  159.         $current_ipaddr md5($_REMOTE_ADDR.$_HTTP_X_FORWARDED_FOR);
  160.  
  161.         // start session check expiry and ip fingerprint if required
  162.         if (session_start(&& isset($GLOBALS['_PNSession']['obj']&& $GLOBALS['_PNSession']['obj']{
  163.             // check if session has expired or not
  164.             $now time();
  165.             $inactive ($now - (int)(pnConfigGetVar('secinactivemins'60));
  166.             $daysold  ($now - (int)(pnConfigGetVar('secmeddays'86400));
  167.             $lastused strtotime ($GLOBALS['_PNSession']['obj']['lastused']);
  168.             $rememberme SessionUtil::getVar('rememberme');
  169.             $uid $GLOBALS['_PNSession']['obj']['uid'];
  170.             $ipaddr $GLOBALS['_PNSession']['obj']['ipaddr'];
  171.  
  172.             // IP check
  173.             if (pnConfigGetVar('sessionipcheck'false)) {
  174.                 if ($ipaddr !== $current_ipaddr{
  175.                     session_destroy();
  176.                     return false;
  177.                 }
  178.             }
  179.  
  180.             switch (pnConfigGetVar('seclevel')) {
  181.                 case 'Low':
  182.                     // Low security - users stay logged in permanently
  183.                     //                no special check necessary
  184.                     break;
  185.                 case 'Medium':
  186.                     // Medium security - delete session info if session cookie has
  187.                     // expired or user decided not to remember themself and inactivity timeout
  188.                     // OR max number of days have elapsed without logging back in
  189.                     if ((!$rememberme && $lastused $inactive|| ($lastused $daysold|| ($uid == '0' && $lastused $inactive))
  190.                     {
  191.                         SessionUtil::expire();
  192.                     }
  193.                     break;
  194.                 case 'High':
  195.                 default:
  196.                     // High security - delete session info if user is inactive
  197.                     if ($rememberme && ($lastused $inactive)) {
  198.                         SessionUtil::expire();
  199.                     }
  200.                     break;
  201.             }
  202.         else {
  203.             // *must* regenerate new session otherwise the default sessid will be
  204.             // taken from any session cookie that was submitted (bad bad bad)
  205.             SessionUtil::regenerate(true);
  206.             SessionUtil::_createNew(session_id()$current_ipaddr);
  207.         }
  208.  
  209.         if (isset($_SESSION['_PNSession']['obj'])) {
  210.             unset($_SESSION['_PNSession']['obj']);
  211.         }
  212.  
  213.         return true;
  214.     }
  215.  
  216.  
  217.     /**
  218.      * Create a new session
  219.      *
  220.      * @access private
  221.      * @param sessid the session ID
  222.      * @param ipaddr the IP address of the host with this session
  223.      *
  224.      * @return bool 
  225.      */
  226.     function _createNew($sessid$ipaddr)
  227.     {
  228.         $now date('Y-m-d H:i:s'time());
  229.         $obj array('sessid'    => $sessid,
  230.                      'ipaddr'    => $ipaddr,
  231.                      'uid'       => 0,
  232.                      'lastused'  => $now);
  233.         $GLOBALS['_PNSession']['obj'$obj;
  234.         $GLOBALS['_PNSession']['new'true;
  235.         // Generate a random number, used for some authentication (using prime numer bounds)
  236.         SessionUtil::setVar('rand'RandomUtil::getString(3240falsetruetruefalsetruetruetrue));
  237.         // write hash of useragent into the session for later validation
  238.         SessionUtil::setVar('useragent'sha1(pnServerGetVar('HTTP_USER_AGENT')));
  239.  
  240.         // init status & error message arrays
  241.         SessionUtil::setVar('_PNErrorMsg'array());
  242.         SessionUtil::setVar('_PNStatusMsg'array());
  243.  
  244.         return true;
  245.     }
  246.  
  247.  
  248.     /**
  249.      * Get a session variable
  250.      *
  251.      * @param sring $name of the session variable to get
  252.      * @param string $default the default value to return if the requested session variable is not set
  253.      * @param autocreate $autocreate whether or not to autocreate the supplied path (optional) (default=true)
  254.      * @param overwriteExistingVar $overwriteExistingVar whether or not to overwrite existing/set variable entries which the given path requires to be arrays (optional) (default=false)
  255.      * @return string session variable requested
  256.      */
  257.     function getVar($name$default=false$path='/'$autocreate=true$overwriteExistingVar=false)
  258.     {
  259.         if ($path == '/' || $path === ''{
  260.             if (isset($_SESSION['PNSV' $name])) {
  261.                 return $_SESSION['PNSV' $name];
  262.             }
  263.         else {
  264.             $parent =SessionUtil::_resolvePath ($path$autocreate$overwriteExistingVar);
  265.             if ($parent === false// path + autocreate or overwriteExistingVar Error
  266.                 return false;
  267.             }
  268.  
  269.             if (isset($parent[$name])) {
  270.                 return $parent[$name];
  271.             }
  272.             else
  273.             if ($autocreate{
  274.                 $parent[$name$default;
  275.             }
  276.         }
  277.  
  278.         return $default;
  279.     }
  280.  
  281.  
  282.     /**
  283.      * Set a session variable
  284.      *
  285.      * @param string $name of the session variable to set
  286.      * @param value $value to set the named session variable
  287.      * @param path $path to traverse to reach the element we wish to return (optional) (default='/')
  288.      * @param autocreate $autocreate whether or not to autocreate the supplied path (optional) (default=true)
  289.      * @param overwriteExistingVar $overwriteExistingVar whether or not to overwrite existing/set variable entries which the given path requires to be arrays (optional) (default=false)
  290.      * @return bool true upon success, false upon failure
  291.      */
  292.     function setVar($name$value$path='/'$autocreate=true$overwriteExistingVar=false)
  293.     {
  294.         global $PNConfig;
  295.  
  296.         if (($name == 'errormsg' || $name == 'statusmsg' || $name == '_PNErrorMsg' || $name == '_PNStatusMsg'&& !is_array($value)) {
  297.             if ($PNConfig['System']['development']{
  298.                 LogUtil::log ('This use of SessionUtil::setVar() is no longer valid ... please use the LogUtil API to manipulate status/error messages');
  299.             }
  300.             if ($name == '_PNErrorMsg' || $name == 'errormsg'{
  301.                 return LogUtil::registerError ($value);
  302.             }
  303.             if ($name == '_PNStatusMsg' || $name == 'statusmsg'{
  304.                 return LogUtil::registerStatus ($value);
  305.             }
  306.         }
  307.  
  308.         // temporary fix for bug #3770
  309.         // $value = str_replace('\\', '/', $value);
  310.  
  311.         // cause session on regeration on uid change
  312.         if ($name == 'uid'{
  313.             SessionUtil::regenerate();
  314.         }
  315.  
  316.         if ($path == '/' || $path === ''{
  317.             $_SESSION['PNSV' $name$value;
  318.         else {
  319.             $parent =SessionUtil::_resolvePath ($path$autocreate$overwriteExistingVar);
  320.             if ($parent === false// path + autocreate or overwriteExistingVar Error
  321.                 return false;
  322.             }
  323.  
  324.             $parent[$name$value;
  325.         }
  326.  
  327.         return true;
  328.     }
  329.  
  330.  
  331.     /**
  332.      * Delete a session variable
  333.      *
  334.      * @param string $name of the session variable to delete
  335.      * @param string $default the default value to return if the requested session variable is not set
  336.      * @param path $path to traverse to reach the element we wish to return (optional) (default='/')
  337.      * @return bool true
  338.      */
  339.     function delVar($name$default=false$path='/')
  340.     {
  341.         $value false;
  342.  
  343.         if ($path == '/' || $path === ''{
  344.             if (isset($_SESSION['PNSV' $name])) {
  345.                 $value $_SESSION['PNSV' $name];
  346.                 unset($_SESSION['PNSV' $name]);
  347.             else {
  348.                 $value $default;
  349.             }
  350.         else {
  351.             $parent =SessionUtil::_resolvePath ($pathfalsefalse);
  352.             if ($parent === false// path + autocreate or overwriteExistingVar Error
  353.                 return false;
  354.             }
  355.  
  356.             if (isset($parent[$name])) {
  357.                 $value $parent[$name];
  358.                 unset($parent[$name]);
  359.             else {
  360.                 $value $default;
  361.             }
  362.         }
  363.  
  364.         // unset if registerglobals are on
  365.         unset($GLOBALS['PNSV' $name]);
  366.  
  367.         return $value;
  368.     }
  369.  
  370.  
  371.     /**
  372.      * Traverse the session data structure according to the path given and return a reference to last object in the path
  373.      *
  374.      * @access private
  375.      * @param path $path to traverse to reach the element we wish to return
  376.      * @param autocreate $autocreate whether or not to autocreate the supplied path (optional) (default=true)
  377.      * @param overwriteExistingVar $overwriteExistingVar whether or not to overwrite existing/set variable entries which the given path requires to be arrays (optional) (default=false)
  378.      * @return mixed array upon successful location/creation of path element(s), false upon failure
  379.      */
  380.     function &_resolvePath ($path$autocreate=true$overwriteExistingVar=false)
  381.     {
  382.         // now traverse down the path and set the var
  383.         if ($path == '/' || !$path{
  384.             return LogUtil::registerError ('Invalid Path received');
  385.         }
  386.  
  387.         // remove leading '/' so that explode doesn't deliver an empty 1st element
  388.         if (strpos($path'/'=== 0{
  389.             $path substr ($path1);
  390.         }
  391.  
  392.         $c 0;
  393.         $parent =$_SESSION;
  394.         $paths explode ('/'$path);
  395.         foreach ($paths as $p{
  396.             $pFixed ($c==?  'PNSV' $p $p);
  397.             if (!isset($parent[$pFixed])) {
  398.                 if ($autocreate{
  399.                     $parent[$pFixedarray();
  400.                     $parent =$parent[$pFixed];
  401.                 }
  402.                 else {
  403.                     return false;
  404.                 }
  405.             else {
  406.                 if (!is_array($parent[$pFixed])) {
  407.                     if ($overwriteExistingVar{
  408.                         $parent[$pFixedarray();
  409.                     else {
  410.                         return false;
  411.                     }
  412.                 }
  413.                 $parent =$parent[$pFixed];
  414.             }
  415.             $c++;
  416.         }
  417.  
  418.         return $parent;
  419.     }
  420.  
  421.     /**
  422.      * Session required
  423.      * Starts a session or terminates loading.
  424.      *
  425.      */
  426.     function requireSession()
  427.     {
  428.         // check if we need to create a session
  429.         if (!session_id()) {
  430.             // Start session
  431.             if (!SessionUtil::initialize()) {
  432.                 // session initialization failed so display templated error
  433.                 header('HTTP/1.1 503 Service Unavailable');
  434.                 if (file_exists('config/templates/sessionfailed.htm')) {
  435.                     Loader::requireOnce('config/templates/sessionfailed.htm');
  436.                 else {
  437.                     Loader::requireOnce('includes/templates/sessionfailed.htm');
  438.                 }
  439.                 // terminate execution
  440.                 pnShutDown();
  441.             }
  442.         }
  443.     }
  444.  
  445.     /**
  446.      * Let session expire nicely
  447.      *
  448.      * @return void 
  449.      */
  450.     function expire()
  451.     {
  452.         if (SessionUtil::getVar('uid'== '0'{
  453.             // no need to do anything for guests without sessions
  454.             if (pnConfigGetVar('anonymoussessions'== '0'return;
  455.  
  456.             // no need to display expiry for anon users with sessions since it's invisible anyway
  457.             // handle expired sessions differently
  458.             SessionUtil::_createNew(session_id()$GLOBALS['_PNSession']['obj']['ipaddr']);
  459.             // session is not new, remove flag
  460.             unset($GLOBALS['_PNSession']['new']);
  461.             SessionUtil::regenerate(true);
  462.             return;
  463.         }
  464.  
  465.         // for all logged in users with session destroy session and set flag
  466.         session_destroy();
  467.         $GLOBALS['_PNSession']['expired'true;
  468.     }
  469.  
  470.  
  471.     /**
  472.      * Check if a session has expired or not
  473.      *
  474.      * @return bool 
  475.      */
  476.     function hasExpired()
  477.     {
  478.         if (isset($GLOBALS['_PNSession']['expired']&& $GLOBALS['_PNSession']['expired']{
  479.             unset($GLOBALS['_PNSession']);
  480.             return true;
  481.         }
  482.  
  483.         return false;
  484.     }
  485.  
  486.  
  487.     /**
  488.      * regerate session id
  489.      *
  490.      * @param bool $force default false force regeneration
  491.      * @return void 
  492.      *
  493.      */
  494.     function regenerate($force=false)
  495.     {
  496.         // only regenerate if set in admin
  497.         if ($force == false{
  498.             if (!pnConfigGetVar('sessionregenerate'|| pnConfigGetVar('sessionregenerate'== 0{
  499.                 // there is no point changing a newly generated session.
  500.                 if (isset($GLOBALS['_PNSession']['new']&& $GLOBALS['_PNSession']['new'== true{
  501.                     return;
  502.                 }
  503.                 return;
  504.             }
  505.         }
  506.  
  507.         // dont allow multiple regerations
  508.         if (isset($GLOBALS['_PNSession']['regenerated']&& $GLOBALS['_PNSession']['regenerated'== true{
  509.             return;
  510.         }
  511.  
  512.         $GLOBALS['_PNSession']['sessid_old'session_id();    // save old session id
  513.  
  514.         if (session_regenerate_id()) {
  515.             // need to handle php < 4.3.3 bug that doesnt issue
  516.             // session cookie to browser after regeneration [drak]
  517.             if (!version_compare(phpversion()'4.3.3''>=')) {
  518.                 setcookie(session_name()session_id()time(ini_get('session.cookie_lifetime')ini_get('session.cookie_path')ini_get('session.cookie_domain')(pnServerGetProtocol(== 'https' true false));
  519.             }
  520.         }
  521.  
  522.         $GLOBALS['_PNSession']['obj']['sessid'session_id()// commit new sessid
  523.         $GLOBALS['_PNSession']['regenerated'true;           // flag regeneration
  524.         return;
  525.     }
  526.  
  527.  
  528.     /**
  529.      * Regenerate session according to probability set by admin
  530.      *
  531.      */
  532.     function random_regenerate()
  533.     {
  534.         if (!pnConfigGetVar('sessionrandregenerate')) {
  535.             return;
  536.         }
  537.  
  538.         $chance 100 pnConfigGetVar('sessionregeneratefreq');
  539.         $a rand(0$chance);
  540.         $b rand(0$chance);
  541.         if ($a == $b{
  542.             SessionUtil::regenerate();
  543.         }
  544.     }
  545.  
  546.  
  547.     /**
  548.      * Define the name of our session cookie
  549.      *
  550.      * @access private
  551.      */
  552.     function getCookieName()
  553.     {
  554.         // Include number of dots in session name such that we use a different session for
  555.         // www.domain.xx and domain.xx. Otherwise we run into problems with both cookies for
  556.         // www.domain.xx as well as domain.xx being sent to www.domain.xx simultaneously!
  557.         $hostNameDotCount substr_count(pnGetHost()'.');
  558.         return pnConfigGetVar('sessionname').$hostNameDotCount;
  559.     }
  560. }
  561.  
  562.  
  563. // emulate session_regenerate_id function if missing
  564. if (!function_exists('session_regenerate_id')) {
  565.     /**
  566.      * Regenerate session
  567.      *
  568.      * @return string session_id
  569.      */
  570.     function session_regenerate_id({
  571.         $len (ini_get('session.hash_function'== 032 40;
  572.         return (bool)session_id(RandomUtil::getString($len$lenfalsefalsetruefalsetruefalsefalse));
  573.     }
  574. }
  575.  
  576.  
  577. /* Following _Session__* API are for internal class use.  Do not call directly */
  578.  
  579. /**
  580.  * PHP function to start the session
  581.  *
  582.  * @access private
  583.  * @return bool true
  584.  */
  585. function _SessionUtil__Start($path$name)
  586. {
  587.     // Nothing to do
  588.     return true;
  589. }
  590.  
  591. /**
  592.  * PHP function to close the session
  593.  *
  594.  * @access private
  595.  * @return bool true
  596.  */
  597. function _SessionUtil__Close()
  598. {
  599.     // nothing to do
  600.     return true;
  601. }
  602.  
  603. /**
  604.  * PHP function to read a set of session variables
  605.  *
  606.  * @access private
  607.  * @param string $sessid session id
  608.  * @return mixed bool of false or string session variable if true
  609.  */
  610. function _SessionUtil__Read($sessid)
  611. {
  612.     // if (pnConfigGetVar('anonymoussessions') == '0') {
  613.     if (pnConfigGetVar('sessionstoretofile')) {
  614.         $path DataUtil::formatForOS(session_save_path());
  615.         if (file_exists("$path/$sessid")) {
  616.             $result file_get_contents("$path/$sessid");
  617.             if ($result{
  618.                 $result unserialize($result);
  619.             }
  620.         }
  621.     else {
  622.         $result DBUtil::selectObjectByID('session_info'$sessid'sessid');
  623.         if (!$result{
  624.             return false;
  625.         }
  626.     }
  627.  
  628.     if (is_array($result&& isset($result['sessid'])) {
  629.         $GLOBALS['_PNSession']['obj'array('sessid'    => $result['sessid'],
  630.                                               'ipaddr'    => $result['ipaddr'],
  631.                                               'uid'       => $result['uid'],
  632.                                               'lastused'  => $result['lastused']);
  633.     }
  634.  
  635.     // security feature to change session id's periodically
  636.  
  637.     return (isset($result['vars']$result['vars''');
  638. }
  639.  
  640. /**
  641.  * PHP function to write a set of session variables
  642.  *
  643.  * DO NOT CALL THIS DIRECTLY use session_write_close()
  644.  *
  645.  * @access private
  646.  * @param string $sessid session id
  647.  * @param string $vars session variables
  648.  * @return bool 
  649.  */
  650. function _SessionUtil__Write($sessid$vars)
  651. {
  652.     $obj $GLOBALS['_PNSession']['obj'];
  653.     $obj['vars'$vars;
  654.     $obj['remember'(SessionUtil::getVar('rememberme'SessionUtil::getVar('rememberme'0);
  655.     $obj['uid'(SessionUtil::getVar('uid'SessionUtil::getVar('uid'0);
  656.     $obj['lastused'date('Y-m-d H:i:s'time());
  657.  
  658.     if (pnConfigGetVar('sessionstoretofile')) {
  659.         $path DataUtil::formatForOS(session_save_path());
  660.  
  661.         // if session was regenerate, delete it first
  662.         if (isset($GLOBALS['_PNSession']['regenerated']&& $GLOBALS['_PNSession']['regenerated'== true{
  663.             unlink("$path/$sessid");
  664.         }
  665.  
  666.         // now write session
  667.         if ($fp @fopen("$path/$sessid""w")) {
  668.             $res fwrite($fpserialize($obj));
  669.             fclose($fp);
  670.         else {
  671.             return false;
  672.         }
  673.     else {
  674.         if (isset($GLOBALS['_PNSession']['new']&& $GLOBALS['_PNSession']['new'== true{
  675.             $res DBUtil::insertObject($obj'session_info''sessid'true);
  676.             unset($GLOBALS['_PNSession']['new']);
  677.         else {
  678.             // check for regenerated session and update ID in database
  679.             if (isset($GLOBALS['_PNSession']['regenerated']&& $GLOBALS['_PNSession']['regenerated'== true{
  680.                 $sessiontable pnDBGetTables();
  681.                 $columns $sessiontable['session_info_column'];
  682.                 $where "WHERE $columns[sessid] = 'DataUtil::formatForStore($GLOBALS['_PNSession']['sessid_old']"'";
  683.                 $res DBUtil::updateObject($obj'session_info'$where'sessid'truetrue);
  684.             else {
  685.                 $res DBUtil::updateObject($obj'session_info''''sessid'true);
  686.             }
  687.         }
  688.     }
  689.  
  690.     return (bool)$res;
  691. }
  692.  
  693. /**
  694.  * PHP function to destroy a session
  695.  *
  696.  * DO NOT CALL THIS FUNCTION DIRECTLY use session_destory();
  697.  *
  698.  * @access private
  699.  * @param string $sessid session id
  700.  * @return bool 
  701.  */
  702. function _SessionUtil__Destroy($sessid)
  703. {
  704.     if (isset($GLOBALS['_PNSession'])) {
  705.         unset($GLOBALS['_PNSession']);
  706.     }
  707.  
  708.     // expire the cookie
  709.     setcookie(session_name(,''0ini_get('session.cookie_path'));
  710.  
  711.     // can exit if anon user and anon session disabled
  712.     if (pnConfigGetVar('anonymoussessions'== '0' && SessionUtil::getVar('uid'== '0'{
  713.         return true;
  714.     }
  715.  
  716.     // ensure we delete the stored session (not a regenerated one)
  717.     if (isset($GLOBALS['_PNSession']['regenerated']&& $GLOBALS['_PNSession']['regenerated'== true{
  718.         $sessid $GLOBALS['_PNSession']['sessid_old'];
  719.     else {
  720.         $sessid session_id();
  721.     }
  722.  
  723.     if (pnConfigGetVar('sessionstoretofile')) {
  724.         $path DataUtil::formatForOS(session_save_path()true);
  725.         return unlink("$path/$sessid");
  726.     else {
  727.         $res DBUtil::deleteObjectByID('session_info'$sessid'sessid');
  728.         return (bool)$res;
  729.     }
  730. }
  731.  
  732. /**
  733.  * PHP function to garbage collect session information
  734.  *
  735.  * @access private
  736.  * @param int $maxlifetime maxlifetime of the session
  737.  * @return bool 
  738.  */
  739. function _SessionUtil__GC($maxlifetime)
  740. {
  741.     $now time();
  742.     $inactive ($now - (int)(pnConfigGetVar('secinactivemins'60));
  743.     $daysold  ($now - (int)(pnConfigGetVar('secmeddays'86400));
  744.  
  745.     // find the hash length dynamically
  746.     $hash ini_get('session.hash_function');
  747.     if (empty($hash|| $hash == 0{
  748.         $sessionlength 32;
  749.     else {
  750.         $sessionlength 40;
  751.     }
  752.  
  753.     if (pnConfigGetVar('sessionstoretofile')) {
  754.         // file based GC
  755.         $path DataUtil::formatForOS(session_save_path()true);
  756.         // get files
  757.         $files array();
  758.         if ($handle opendir($path)) {
  759.             while (false !== ($file readdir($handle))) {
  760.                 if ($file != '.' && $file != '..' && strlen($file== $sessionlength{
  761.                     // filename, created, last modified
  762.                     $file "$path/$file";
  763.                     $files[array('name'     => $file,
  764.                     'lastused' => filemtime($file));
  765.                 }
  766.             }
  767.         }
  768.  
  769.         // check we have something to do
  770.         if (count($files== 0{
  771.             return true;
  772.         }
  773.  
  774.         // do GC
  775.         switch (pnConfigGetVar('seclevel')) {
  776.             case 'Low':
  777.                 // Low security - delete session info if user decided not to
  778.                 //                remember themself and session is inactive
  779.                 foreach ($files as $file{
  780.                     $name $file['name'];
  781.                     $lastused $file['lastused'];
  782.                     $session unserialize(file_get_contents($name));
  783.                     if ($lastused $inactive && !isset($session['PNSVrememberme'])) {
  784.                         unlink($name);
  785.                     }
  786.                 }
  787.                 break;
  788.             case 'Medium':
  789.                 // Medium security - delete session info if session cookie has
  790.                 // expired or user decided not to remember themself and inactivity timeout
  791.                 // OR max number of days have elapsed without logging back in
  792.                 foreach ($files as $file{
  793.                     $name $file['name'];
  794.                     $lastused $file['lastused'];
  795.                     $session unserialize(file_get_contents($name));
  796.                     if ($lastused $inactive && !isset($session['PNSVrememberme'])) {
  797.                         unlink($name);
  798.                     }
  799.                     else
  800.                     if (($lastused $daysold)) {
  801.                         unlink($name);
  802.                     }
  803.                 }
  804.                 break;
  805.             case 'High':
  806.                 // High security - delete session info if user is inactive
  807.                 foreach ($files as $file{
  808.                     $name $file['name'];
  809.                     $lastused $file['lastused'];
  810.                     if ($lastused $inactive{
  811.                         unlink($name);
  812.                     }
  813.                 }
  814.                 break;
  815.         }
  816.         return true;
  817.  
  818.     else {
  819.         // DB based GC
  820.         $pntable pnDBGetTables();
  821.         $sessioninfocolumn $pntable['session_info_column'];
  822.         $inactive DataUtil::formatForStore(date('Y-m-d H:i:s'$inactive));
  823.         $daysold  DataUtil::formatForStore(date('Y-m-d H:i:s'$daysold));
  824.  
  825.         switch (pnConfigGetVar('seclevel')) {
  826.             case 'Low':
  827.                 // Low security - delete session info if user decided not to
  828.                 //                remember themself and inactivity timeout
  829.                 $where "WHERE $sessioninfocolumn[remember] = 0
  830.                           AND $sessioninfocolumn[lastused] < '$inactive'";
  831.                 break;
  832.             case 'Medium':
  833.                 // Medium security - delete session info if session cookie has
  834.                 // expired or user decided not to remember themself and inactivity timeout
  835.                 // OR max number of days have elapsed without logging back in
  836.                 $where "WHERE ($sessioninfocolumn[remember] = 0
  837.                           AND $sessioninfocolumn[lastused] < '$inactive')
  838.                           OR ($sessioninfocolumn[lastused] < '$daysold')
  839.                           OR ($sessioninfocolumn[uid] = 0 AND $sessioninfocolumn[lastused] < '$inactive')";
  840.                 break;
  841.             case 'High':
  842.             default:
  843.                 // High security - delete session info if user is inactive
  844.                 $where "WHERE $sessioninfocolumn[lastused] < '$inactive'";
  845.                 break;
  846.         }
  847.  
  848.         $res DBUtil::deleteWhere('session_info'$where);
  849.         return (bool)$res;
  850.     }
  851. }
  852.  
  853.  
  854. /* Legacy APIs to be removed at a later date */
  855.  
  856. /**
  857.  * Get a session variable
  858.  *
  859.  * @deprecated
  860.  * @see SessionUtil::getVar
  861.  * @param sring $name of the session variable to get
  862.  * @param string $default the default value to return if the requested session variable is not set
  863.  * @return string session variable requested
  864.  */
  865. function pnSessionGetVar($name$default=false)
  866. {
  867.     return SessionUtil::getVar($name$default);
  868. }
  869.  
  870.  
  871. /**
  872.  * Set a session variable
  873.  *
  874.  * @deprecated
  875.  * @see SessionUtil::setVar
  876.  * @param string $name of the session variable to set
  877.  * @param value $value to set the named session variable
  878.  * @return bool true
  879.  */
  880. function pnSessionSetVar($name$value)
  881. {
  882.     return SessionUtil::setVar($name$value);
  883. }
  884.  
  885.  
  886. /**
  887.  * Delete a session variable
  888.  *
  889.  * @deprecated
  890.  * @see SessionUtil::delVar
  891.  * @param string $name of the session variable to delete
  892.  * @return bool true
  893.  */
  894. function pnSessionDelVar($name)
  895. {
  896.     return SessionUtil::delVar($name);
  897. }

Documentation generated on Fri, 18 Jul 2008 21:56:50 +0200 by phpDocumentor 1.4.1