[ Index ]
 

Code source de PRADO 3.0.6

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/framework/Web/ -> THttpSession.php (source)

   1  <?php
   2  /**
   3   * THttpSession class
   4   *
   5   * @author Qiang Xue <qiang.xue@gmail.com>
   6   * @link http://www.pradosoft.com/
   7   * @copyright Copyright &copy; 2005 PradoSoft
   8   * @license http://www.pradosoft.com/license/
   9   * @version $Id: THttpSession.php 1397 2006-09-07 07:55:53Z wei $
  10   * @package System.Web
  11   */
  12  
  13  /**
  14   * THttpSession class
  15   *
  16   * THttpSession provides session-level data management and the related configurations.
  17   * To start the session, call {@open}; to complete and send out session data, call {@close};
  18   * to destroy the session, call {@destroy}. If AutoStart is true, then the session
  19   * will be started once the session module is loaded and initialized.
  20   *
  21   * To access data stored in session, use THttpSession like an associative array. For example,
  22   * <code>
  23   *   $session=new THttpSession;
  24   *   $session->open();
  25   *   $value1=$session['name1'];  // get session variable 'name1'
  26   *   $value2=$session['name2'];  // get session variable 'name2'
  27   *   foreach($session as $name=>$value) // traverse all session variables
  28   *   $session['name3']=$value3;  // set session variable 'name3'
  29   * </code>
  30   *
  31   * The following configurations are available for session:
  32   * {@link setAutoStart AutoStart}, {@link setCookie Cookie},
  33   * {@link setCacheLimiter, {@link setSavePath SavePath},
  34   * {@link setUseCustomStorage UseCustomStorage}, {@link setGCProbability GCProbability},
  35   * {@link setCookieUsage CookieUsage}, {@link setTimeout Timeout}.
  36   * See the corresponding setter and getter documentation for more information.
  37   * Note, these properties must be set before the session is started.
  38   *
  39   * THttpSession can be inherited with customized session storage method.
  40   * Override {@link _open}, {@link _close}, {@link _read}, {@link _write}, {@link _destroy} and {@link _gc}
  41   * and set {@link setUseCustomStorage UseCustomStorage} to true.
  42   * Then, the session data will be stored using the above methods.
  43   *
  44   * By default, THttpSession is registered with {@link TApplication} as the
  45   * request module. It can be accessed via {@link TApplication::getSession()}.
  46   *
  47   * THttpSession may be configured in application configuration file as follows,
  48   * <code>
  49   * <module id="session" class="THttpSession" SessionName="SSID" SavePath="/tmp"
  50   *         CookieMode="Allow" UseCustomStorage="false" AutoStart="true" GCProbability="1"
  51   *         UseTransparentSessionID="true" TimeOut="3600" />
  52   * </code>
  53   * where {@link getSessionName SessionName}, {@link getSavePath SavePath},
  54   * {@link getCookieMode CookieMode}, {@link getUseCustomStorage
  55   * UseCustomStorage}, {@link getAutoStart AutoStart}, {@link getGCProbability
  56   * GCProbability}, {@link getUseTransparentSessionID UseTransparentSessionID}
  57   * and {@link getTimeOut TimeOut} are configurable properties of THttpSession.
  58   *
  59   * @author Qiang Xue <qiang.xue@gmail.com>
  60   * @version $Id: THttpSession.php 1397 2006-09-07 07:55:53Z wei $
  61   * @package System.Web
  62   * @since 3.0
  63   */
  64  class THttpSession extends TApplicationComponent implements IteratorAggregate,ArrayAccess,Countable,IModule
  65  {
  66      /**
  67       * @var boolean whether this module has been initialized
  68       */
  69      private $_initialized=false;
  70      /**
  71       * @var boolean whether the session has started
  72       */
  73      private $_started=false;
  74      /**
  75       * @var boolean whether the session should be started when the module is initialized
  76       */
  77      private $_autoStart=false;
  78      /**
  79       * @var THttpCookie cookie to be used to store session ID and other data
  80       */
  81      private $_cookie=null;
  82      /**
  83       * @var string module id
  84       */
  85      private $_id;
  86      /**
  87       * @var boolean
  88       */
  89      private $_customStorage=false;
  90  
  91      /**
  92       * Destructor.
  93       * Closes session.
  94       */
  95  	public function __destruct()
  96      {
  97          if($this->_started)
  98              $this->close();
  99      }
 100  
 101      /**
 102       * @return string id of this module
 103       */
 104  	public function getID()
 105      {
 106          return $this->_id;
 107      }
 108  
 109      /**
 110       * @param string id of this module
 111       */
 112  	public function setID($value)
 113      {
 114          $this->_id=$value;
 115      }
 116  
 117      /**
 118       * Initializes the module.
 119       * This method is required by IModule.
 120       * If AutoStart is true, the session will be started.
 121       * @param TXmlElement module configuration
 122       */
 123  	public function init($config)
 124      {
 125          if($this->_autoStart)
 126              $this->open();
 127          $this->_initialized=true;
 128          $this->getApplication()->setSession($this);
 129      }
 130  
 131      /**
 132       * Starts the session if it has not started yet.
 133       */
 134  	public function open()
 135      {
 136          if(!$this->_started)
 137          {
 138              if($this->_customStorage)
 139                  session_set_save_handler(array($this,'_open'),array($this,'_close'),array($this,'_read'),array($this,'_write'),array($this,'_destroy'),array($this,'_gc'));
 140              if($this->_cookie!==null)
 141                  session_set_cookie_params($this->_cookie->getExpire(),$this->_cookie->getPath(),$this->_cookie->getDomain(),$this->_cookie->getSecure());
 142              if(ini_get('session.auto_start')!=='1')
 143                  session_start();
 144              $this->_started=true;
 145          }
 146      }
 147  
 148      /**
 149       * Ends the current session and store session data.
 150       */
 151  	public function close()
 152      {
 153          if($this->_started)
 154          {
 155              session_write_close();
 156              $this->_started=false;
 157          }
 158      }
 159  
 160      /**
 161       * Destroys all data registered to a session.
 162       */
 163  	public function destroy()
 164      {
 165          if($this->_started)
 166          {
 167              session_destroy();
 168              $this->_started=false;
 169          }
 170      }
 171  
 172      /**
 173       * @return boolean whether the session has started
 174       */
 175  	public function getIsStarted()
 176      {
 177          return $this->_started;
 178      }
 179  
 180      /**
 181       * @return string the current session ID
 182       */
 183  	public function getSessionID()
 184      {
 185          return session_id();
 186      }
 187  
 188      /**
 189       * @param string the session ID for the current session
 190       * @throws TInvalidOperationException if session is started already
 191       */
 192  	public function setSessionID($value)
 193      {
 194          if($this->_started)
 195              throw new TInvalidOperationException('httpsession_sessionid_unchangeable');
 196          else
 197              session_id($value);
 198      }
 199  
 200      /**
 201       * @return string the current session name
 202       */
 203  	public function getSessionName()
 204      {
 205          return session_name();
 206      }
 207  
 208      /**
 209       * @param string the session name for the current session, must be an alphanumeric string, defaults to PHPSESSID
 210       * @throws TInvalidOperationException if session is started already
 211       */
 212  	public function setSessionName($value)
 213      {
 214          if($this->_started)
 215              throw new TInvalidOperationException('httpsession_sessionname_unchangeable');
 216          else if(ctype_alnum($value))
 217              session_name($value);
 218          else
 219              throw new TInvalidDataValueException('httpsession_sessionname_invalid',$value);
 220      }
 221  
 222      /**
 223       * @return string the current session save path, defaults to '/tmp'.
 224       */
 225  	public function getSavePath()
 226      {
 227          return session_save_path();
 228      }
 229  
 230      /**
 231       * @param string the current session save path
 232       * @throws TInvalidOperationException if session is started already
 233       */
 234  	public function setSavePath($value)
 235      {
 236          if($this->_started)
 237              throw new TInvalidOperationException('httpsession_savepath_unchangeable');
 238          else if(is_dir($value))
 239              session_save_path($value);
 240          else
 241              throw new TInvalidDataValueException('httpsession_savepath_invalid',$value);
 242      }
 243  
 244      /**
 245       * @return boolean whether to use user-specified handlers to store session data. Defaults to false.
 246       */
 247  	public function getUseCustomStorage()
 248      {
 249          return $this->_customStorage;
 250      }
 251  
 252      /**
 253       * @param boolean whether to use user-specified handlers to store session data.
 254       * If true, make sure the methods {@link _open}, {@link _close}, {@link _read},
 255       * {@link _write}, {@link _destroy}, and {@link _gc} are overridden in child
 256       * class, because they will be used as the callback handlers.
 257       */
 258  	public function setUseCustomStorage($value)
 259      {
 260          $this->_customStorage=TPropertyValue::ensureBoolean($value);
 261      }
 262  
 263      /**
 264       * @return THttpCookie cookie that will be used to store session ID
 265       */
 266  	public function getCookie()
 267      {
 268          if($this->_cookie===null)
 269              $this->_cookie=new THttpCookie($this->getSessionName(),$this->getSessionID());
 270          return $this->_cookie;
 271      }
 272  
 273      /**
 274       * @return THttpSessionCookieMode how to use cookie to store session ID. Defaults to THttpSessionCookieMode::Allow.
 275       */
 276  	public function getCookieMode()
 277      {
 278          if(ini_get('session.use_cookies')==='0')
 279              return THttpSessionCookieMode::None;
 280          else if(ini_get('session.use_only_cookies')==='0')
 281              return THttpSessionCookieMode::Allow;
 282          else
 283              return THttpSessionCookieMode::Only;
 284      }
 285  
 286      /**
 287       * @param THttpSessionCookieMode how to use cookie to store session ID
 288       * @throws TInvalidOperationException if session is started already
 289       */
 290  	public function setCookieMode($value)
 291      {
 292          if($this->_started)
 293              throw new TInvalidOperationException('httpsession_cookiemode_unchangeable');
 294          else
 295          {
 296              $value=TPropertyValue::ensureEnum($value,'THttpSessionCookieMode');
 297              if($value===THttpSessionCookieMode::None)
 298                  ini_set('session.use_cookies','0');
 299              else if($value===THttpSessionCookieMode::Allow)
 300              {
 301                  ini_set('session.use_cookies','1');
 302                  ini_set('session.use_only_cookies','0');
 303              }
 304              else
 305              {
 306                  ini_set('session.use_cookies','1');
 307                  ini_set('session.use_only_cookies','1');
 308              }
 309          }
 310      }
 311  
 312      /**
 313       * @return boolean whether the session should be automatically started when the session module is initialized, defaults to false.
 314       */
 315  	public function getAutoStart()
 316      {
 317          return $this->_autoStart;
 318      }
 319  
 320      /**
 321       * @param boolean whether the session should be automatically started when the session module is initialized, defaults to false.
 322       * @throws TInvalidOperationException if session is started already
 323       */
 324  	public function setAutoStart($value)
 325      {
 326          if($this->_initialized)
 327              throw new TInvalidOperationException('httpsession_autostart_unchangeable');
 328          else
 329              $this->_autoStart=TPropertyValue::ensureBoolean($value);
 330      }
 331  
 332      /**
 333       * @return integer the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.
 334       */
 335  	public function getGCProbability()
 336      {
 337          return TPropertyValue::ensureInteger(ini_get('session.gc_probability'));
 338      }
 339  
 340      /**
 341       * @param integer the probability (percentage) that the gc (garbage collection) process is started on every session initialization.
 342       * @throws TInvalidOperationException if session is started already
 343       * @throws TInvalidDataValueException if the value is beyond [0,100].
 344       */
 345  	public function setGCProbability($value)
 346      {
 347          if($this->_started)
 348              throw new TInvalidOperationException('httpsession_gcprobability_unchangeable');
 349          else
 350          {
 351              $value=TPropertyValue::ensureInteger($value);
 352              if($value>=0 && $value<=100)
 353              {
 354                  ini_set('session.gc_probability',$value);
 355                  ini_set('session.gc_divisor','100');
 356              }
 357              else
 358                  throw new TInvalidDataValueException('httpsession_gcprobability_invalid',$value);
 359          }
 360      }
 361  
 362      /**
 363       * @return boolean whether transparent sid support is enabled or not, defaults to false.
 364       */
 365  	public function getUseTransparentSessionID()
 366      {
 367          return ini_get('session.use_trans_sid')==='1';
 368      }
 369  
 370      /**
 371       * @param boolean whether transparent sid support is enabled or not.
 372       */
 373  	public function setUseTransparentSessionID($value)
 374      {
 375          if($this->_started)
 376              throw new TInvalidOperationException('httpsession_transid_unchangeable');
 377          else
 378              ini_set('session.use_trans_sid',TPropertyValue::ensureBoolean($value)?'1':'0');
 379      }
 380  
 381      /**
 382       * @return integer the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.
 383       */
 384  	public function getTimeout()
 385      {
 386          return TPropertyValue::ensureInteger(ini_get('session.gc_maxlifetime'));
 387      }
 388  
 389      /**
 390       * @param integer the number of seconds after which data will be seen as 'garbage' and cleaned up
 391       * @throws TInvalidOperationException if session is started already
 392       */
 393  	public function setTimeout($value)
 394      {
 395          if($this->_started)
 396              throw new TInvalidOperationException('httpsession_maxlifetime_unchangeable');
 397          else
 398              ini_set('session.gc_maxlifetime',$value);
 399      }
 400  
 401      /**
 402       * Session open handler.
 403       * This method should be overriden if {@link setUseCustomStorage UseCustomStorage} is set true.
 404       * @param string session save path
 405       * @param string session name
 406       * @return boolean whether session is opened successfully
 407       */
 408  	public function _open($savePath,$sessionName)
 409      {
 410          return true;
 411      }
 412  
 413      /**
 414       * Session close handler.
 415       * This method should be overriden if {@link setUseCustomStorage UseCustomStorage} is set true.
 416       * @return boolean whether session is closed successfully
 417       */
 418  	public function _close()
 419      {
 420          return true;
 421      }
 422  
 423      /**
 424       * Session read handler.
 425       * This method should be overriden if {@link setUseCustomStorage UseCustomStorage} is set true.
 426       * @param string session ID
 427       * @return string the session data
 428       */
 429  	public function _read($id)
 430      {
 431          return '';
 432      }
 433  
 434      /**
 435       * Session write handler.
 436       * This method should be overriden if {@link setUseCustomStorage UseCustomStorage} is set true.
 437       * @param string session ID
 438       * @param string session data
 439       * @return boolean whether session write is successful
 440       */
 441  	public function _write($id,$data)
 442      {
 443          return true;
 444      }
 445  
 446      /**
 447       * Session destroy handler.
 448       * This method should be overriden if {@link setUseCustomStorage UseCustomStorage} is set true.
 449       * @param string session ID
 450       * @return boolean whether session is destroyed successfully
 451       */
 452  	public function _destroy($id)
 453      {
 454          return true;
 455      }
 456  
 457      /**
 458       * Session GC (garbage collection) handler.
 459       * This method should be overriden if {@link setUseCustomStorage UseCustomStorage} is set true.
 460       * @param integer the number of seconds after which data will be seen as 'garbage' and cleaned up.
 461       * @return boolean whether session is GCed successfully
 462       */
 463  	public function _gc($maxLifetime)
 464      {
 465          return true;
 466      }
 467  
 468      //------ The following methods enable THttpSession to be TMap-like -----
 469  
 470      /**
 471       * Returns an iterator for traversing the session variables.
 472       * This method is required by the interface IteratorAggregate.
 473       * @return TSessionIterator an iterator for traversing the session variables.
 474       */
 475  	public function getIterator()
 476      {
 477          return new TSessionIterator;
 478      }
 479  
 480      /**
 481       * @return integer the number of session variables
 482       */
 483  	public function getCount()
 484      {
 485          return count($_SESSION);
 486      }
 487  
 488      /**
 489       * Returns the number of items in the session.
 490       * This method is required by Countable interface.
 491       * @return integer number of items in the session.
 492       */
 493  	public function count()
 494      {
 495          return $this->getCount();
 496      }
 497  
 498      /**
 499       * @return array the list of session variable names
 500       */
 501  	public function getKeys()
 502      {
 503          return array_keys($_SESSION);
 504      }
 505  
 506      /**
 507       * Returns the session variable value with the session variable name.
 508       * This method is exactly the same as {@link offsetGet}.
 509       * @param mixed the session variable name
 510       * @return mixed the session variable value, null if no such variable exists
 511       */
 512  	public function itemAt($key)
 513      {
 514          return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
 515      }
 516  
 517      /**
 518       * Adds a session variable.
 519       * Note, if the specified name already exists, the old value will be removed first.
 520       * @param mixed session variable name
 521       * @param mixed session variable value
 522       */
 523  	public function add($key,$value)
 524      {
 525          $_SESSION[$key]=$value;
 526      }
 527  
 528      /**
 529       * Removes a session variable.
 530       * @param mixed the name of the session variable to be removed
 531       * @return mixed the removed value, null if no such session variable.
 532       */
 533  	public function remove($key)
 534      {
 535          if(isset($_SESSION[$key]))
 536          {
 537              $value=$_SESSION[$key];
 538              unset($_SESSION[$key]);
 539              return $value;
 540          }
 541          else
 542              return null;
 543      }
 544  
 545      /**
 546       * Removes all session variables
 547       */
 548  	public function clear()
 549      {
 550          foreach(array_keys($_SESSION) as $key)
 551              unset($_SESSION[$key]);
 552      }
 553  
 554      /**
 555       * @param mixed session variable name
 556       * @return boolean whether there is the named session variable
 557       */
 558  	public function contains($key)
 559      {
 560          return isset($_SESSION[$key]);
 561      }
 562  
 563      /**
 564       * @return array the list of all session variables in array
 565       */
 566  	public function toArray()
 567      {
 568          return $_SESSION;
 569      }
 570  
 571      /**
 572       * This method is required by the interface ArrayAccess.
 573       * @param mixed the offset to check on
 574       * @return boolean
 575       */
 576  	public function offsetExists($offset)
 577      {
 578          return isset($_SESSION[$offset]);
 579      }
 580  
 581      /**
 582       * This method is required by the interface ArrayAccess.
 583       * @param integer the offset to retrieve element.
 584       * @return mixed the element at the offset, null if no element is found at the offset
 585       */
 586  	public function offsetGet($offset)
 587      {
 588          return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
 589      }
 590  
 591      /**
 592       * This method is required by the interface ArrayAccess.
 593       * @param integer the offset to set element
 594       * @param mixed the element value
 595       */
 596  	public function offsetSet($offset,$item)
 597      {
 598          $_SESSION[$offset]=$item;
 599      }
 600  
 601      /**
 602       * This method is required by the interface ArrayAccess.
 603       * @param mixed the offset to unset element
 604       */
 605  	public function offsetUnset($offset)
 606      {
 607          unset($_SESSION[$offset]);
 608      }
 609  }
 610  
 611  /**
 612   * TSessionIterator class
 613   *
 614   * TSessionIterator implements Iterator interface.
 615   *
 616   * TSessionIterator is used by THttpSession. It allows THttpSession to return a new iterator
 617   * for traversing the session variables.
 618   *
 619   * @author Qiang Xue <qiang.xue@gmail.com>
 620   * @version $Id: THttpSession.php 1397 2006-09-07 07:55:53Z wei $
 621   * @package System.Web
 622   * @since 3.0
 623   */
 624  class TSessionIterator implements Iterator
 625  {
 626      /**
 627       * @var array list of keys in the map
 628       */
 629      private $_keys;
 630      /**
 631       * @var mixed current key
 632       */
 633      private $_key;
 634  
 635      /**
 636       * Constructor.
 637       * @param array the data to be iterated through
 638       */
 639  	public function __construct()
 640      {
 641          $this->_keys=array_keys($_SESSION);
 642      }
 643  
 644      /**
 645       * Rewinds internal array pointer.
 646       * This method is required by the interface Iterator.
 647       */
 648  	public function rewind()
 649      {
 650          $this->_key=reset($this->_keys);
 651      }
 652  
 653      /**
 654       * Returns the key of the current array element.
 655       * This method is required by the interface Iterator.
 656       * @return mixed the key of the current array element
 657       */
 658  	public function key()
 659      {
 660          return $this->_key;
 661      }
 662  
 663      /**
 664       * Returns the current array element.
 665       * This method is required by the interface Iterator.
 666       * @return mixed the current array element
 667       */
 668  	public function current()
 669      {
 670          return isset($_SESSION[$this->_key])?$_SESSION[$this->_key]:null;
 671      }
 672  
 673      /**
 674       * Moves the internal pointer to the next array element.
 675       * This method is required by the interface Iterator.
 676       */
 677  	public function next()
 678      {
 679          do
 680          {
 681              $this->_key=next($this->_keys);
 682          }
 683          while(!isset($_SESSION[$this->_key]) && $this->_key!==false);
 684      }
 685  
 686      /**
 687       * Returns whether there is an element at current position.
 688       * This method is required by the interface Iterator.
 689       * @return boolean
 690       */
 691  	public function valid()
 692      {
 693          return $this->_key!==false;
 694      }
 695  }
 696  
 697  
 698  /**
 699   * THttpSessionCookieMode class.
 700   * THttpSessionCookieMode defines the enumerable type for the possible methods of
 701   * using cookies to store session ID.
 702   *
 703   * The following enumerable values are defined:
 704   * - None: not using cookie.
 705   * - Allow: using cookie.
 706   * - Only: using cookie only.
 707   *
 708   * @author Qiang Xue <qiang.xue@gmail.com>
 709   * @version $Id: THttpSession.php 1397 2006-09-07 07:55:53Z wei $
 710   * @package System.Web
 711   * @since 3.0.4
 712   */
 713  class THttpSessionCookieMode extends TEnumerable
 714  {
 715      const None='None';
 716      const Allow='Allow';
 717      const Only='Only';
 718  }
 719  
 720  ?>


Généré le : Sun Feb 25 21:07:04 2007 par Balluche grâce à PHPXref 0.7