Advertisement
Guest User

unzend.com_248

a guest
Oct 1st, 2017
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 27.44 KB | None | 0 0
  1. <?php
  2. // ionCube version 9 Decoder unzend.com - Email: unzend@gmail.com
  3. // http://www.unzend.com
  4. /**
  5.  * CWebUser class file
  6.  *
  7.  * @author Qiang Xue <qiang.xue@gmail.com>
  8.  * @link http://www.yiiframework.com/
  9.  * @copyright 2008-2013 Yii Software LLC
  10.  * @license http://www.yiiframework.com/license/
  11.  */
  12.  
  13. /**
  14.  * CWebUser represents the persistent state for a Web application user.
  15.  *
  16.  * CWebUser is used as an application component whose ID is 'user'.
  17.  * Therefore, at any place one can access the user state via
  18.  * <code>Yii::app()->user</code>.
  19.  *
  20.  * CWebUser should be used together with an {@link IUserIdentity identity}
  21.  * which implements the actual authentication algorithm.
  22.  *
  23.  * A typical authentication process using CWebUser is as follows:
  24.  * <ol>
  25.  * <li>The user provides information needed for authentication.</li>
  26.  * <li>An {@link IUserIdentity identity instance} is created with the user-provided information.</li>
  27.  * <li>Call {@link IUserIdentity::authenticate} to check if the identity is valid.</li>
  28.  * <li>If valid, call {@link CWebUser::login} to login the user, and
  29.  *     Redirect the user browser to {@link returnUrl}.</li>
  30.  * <li>If not valid, retrieve the error code or message from the identity
  31.  * instance and display it.</li>
  32.  * </ol>
  33.  *
  34.  * The property {@link id} and {@link name} are both identifiers
  35.  * for the user. The former is mainly used internally (e.g. primary key), while
  36.  * the latter is for display purpose (e.g. username). The {@link id} property
  37.  * is a unique identifier for a user that is persistent
  38.  * during the whole user session. It can be a username, or something else,
  39.  * depending on the implementation of the {@link IUserIdentity identity class}.
  40.  *
  41.  * Both {@link id} and {@link name} are persistent during the user session.
  42.  * Besides, an identity may have additional persistent data which can
  43.  * be accessed by calling {@link getState}.
  44.  * Note, when {@link allowAutoLogin cookie-based authentication} is enabled,
  45.  * all these persistent data will be stored in cookie. Therefore, do not
  46.  * store password or other sensitive data in the persistent storage. Instead,
  47.  * you should store them directly in session on the server side if needed.
  48.  *
  49.  * @property boolean $isGuest Whether the current application user is a guest.
  50.  * @property mixed $id The unique identifier for the user. If null, it means the user is a guest.
  51.  * @property string $name The user name. If the user is not logged in, this will be {@link guestName}.
  52.  * @property string $returnUrl The URL that the user should be redirected to after login.
  53.  * @property string $stateKeyPrefix A prefix for the name of the session variables storing user session data.
  54.  * @property array $flashes Flash messages (key => message).
  55.  *
  56.  * @author Qiang Xue <qiang.xue@gmail.com>
  57.  * @package system.web.auth
  58.  * @since 1.0
  59.  */
  60. class CWebUser extends CApplicationComponent implements IWebUser
  61. {
  62.     const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  63.     const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  64.     const STATES_VAR='__states';
  65.     const AUTH_TIMEOUT_VAR='__timeout';
  66.     const AUTH_ABSOLUTE_TIMEOUT_VAR='__absolute_timeout';
  67.  
  68.     /**
  69.      * @var boolean whether to enable cookie-based login. Defaults to false.
  70.      */
  71.     public $allowAutoLogin=false;
  72.     /**
  73.      * @var string the name for a guest user. Defaults to 'Guest'.
  74.      * This is used by {@link getName} when the current user is a guest (not authenticated).
  75.      */
  76.     public $guestName='Guest';
  77.     /**
  78.      * @var string|array the URL for login. If using array, the first element should be
  79.      * the route to the login action, and the rest name-value pairs are GET parameters
  80.      * to construct the login URL (e.g. array('/site/login')). If this property is null,
  81.      * a 403 HTTP exception will be raised instead.
  82.      * @see CController::createUrl
  83.      */
  84.     public $loginUrl=array('/site/login');
  85.     /**
  86.      * @var array the property values (in name-value pairs) used to initialize the identity cookie.
  87.      * Any property of {@link CHttpCookie} may be initialized.
  88.      * This property is effective only when {@link allowAutoLogin} is true.
  89.      */
  90.     public $identityCookie;
  91.     /**
  92.      * @var integer timeout in seconds after which user is logged out if inactive.
  93.      * If this property is not set, the user will be logged out after the current session expires
  94.      * (c.f. {@link CHttpSession::timeout}).
  95.      * @since 1.1.7
  96.      */
  97.     public $authTimeout;
  98.     /**
  99.      * @var integer timeout in seconds after which user is logged out regardless of activity.
  100.      * @since 1.1.14
  101.      */
  102.     public $absoluteAuthTimeout;
  103.     /**
  104.      * @var boolean whether to automatically renew the identity cookie each time a page is requested.
  105.      * Defaults to false. This property is effective only when {@link allowAutoLogin} is true.
  106.      * When this is false, the identity cookie will expire after the specified duration since the user
  107.      * is initially logged in. When this is true, the identity cookie will expire after the specified duration
  108.      * since the user visits the site the last time.
  109.      * @see allowAutoLogin
  110.      * @since 1.1.0
  111.      */
  112.     public $autoRenewCookie=false;
  113.     /**
  114.      * @var boolean whether to automatically update the validity of flash messages.
  115.      * Defaults to true, meaning flash messages will be valid only in the current and the next requests.
  116.      * If this is set false, you will be responsible for ensuring a flash message is deleted after usage.
  117.      * (This can be achieved by calling {@link getFlash} with the 3rd parameter being true).
  118.      * @since 1.1.7
  119.      */
  120.     public $autoUpdateFlash=true;
  121.     /**
  122.      * @var string value that will be echoed in case that user session has expired during an ajax call.
  123.      * When a request is made and user session has expired, {@link loginRequired} redirects to {@link loginUrl} for login.
  124.      * If that happens during an ajax call, the complete HTML login page is returned as the result of that ajax call. That could be
  125.      * a problem if the ajax call expects the result to be a json array or a predefined string, as the login page is ignored in that case.
  126.      * To solve this, set this property to the desired return value.
  127.      *
  128.      * If this property is set, this value will be returned as the result of the ajax call in case that the user session has expired.
  129.      * @since 1.1.9
  130.      * @see loginRequired
  131.      */
  132.     public $loginRequiredAjaxResponse;
  133.  
  134.     private $_keyPrefix;
  135.     private $_access=array();
  136.  
  137.     /**
  138.      * PHP magic method.
  139.      * This method is overriden so that persistent states can be accessed like properties.
  140.      * @param string $name property name
  141.      * @return mixed property value
  142.      */
  143.     public function __get($name)
  144.     {
  145.         if($this->hasState($name))
  146.             return $this->getState($name);
  147.         else
  148.             return parent::__get($name);
  149.     }
  150.  
  151.     /**
  152.      * PHP magic method.
  153.      * This method is overriden so that persistent states can be set like properties.
  154.      * @param string $name property name
  155.      * @param mixed $value property value
  156.      */
  157.     public function __set($name,$value)
  158.     {
  159.         if($this->hasState($name))
  160.             $this->setState($name,$value);
  161.         else
  162.             parent::__set($name,$value);
  163.     }
  164.  
  165.     /**
  166.      * PHP magic method.
  167.      * This method is overriden so that persistent states can also be checked for null value.
  168.      * @param string $name property name
  169.      * @return boolean
  170.      */
  171.     public function __isset($name)
  172.     {
  173.         if($this->hasState($name))
  174.             return $this->getState($name)!==null;
  175.         else
  176.             return parent::__isset($name);
  177.     }
  178.  
  179.     /**
  180.      * PHP magic method.
  181.      * This method is overriden so that persistent states can also be unset.
  182.      * @param string $name property name
  183.      * @throws CException if the property is read only.
  184.      */
  185.     public function __unset($name)
  186.     {
  187.         if($this->hasState($name))
  188.             $this->setState($name,null);
  189.         else
  190.             parent::__unset($name);
  191.     }
  192.  
  193.     /**
  194.      * Initializes the application component.
  195.      * This method overrides the parent implementation by starting session,
  196.      * performing cookie-based authentication if enabled, and updating the flash variables.
  197.      */
  198.     public function init()
  199.     {
  200.         parent::init();
  201.         Yii::app()->getSession()->open();
  202.         if($this->getIsGuest() && $this->allowAutoLogin)
  203.             $this->restoreFromCookie();
  204.         elseif($this->autoRenewCookie && $this->allowAutoLogin)
  205.             $this->renewCookie();
  206.         if($this->autoUpdateFlash)
  207.             $this->updateFlash();
  208.  
  209.         $this->updateAuthStatus();
  210.     }
  211.  
  212.     /**
  213.      * Logs in a user.
  214.      *
  215.      * The user identity information will be saved in storage that is
  216.      * persistent during the user session. By default, the storage is simply
  217.      * the session storage. If the duration parameter is greater than 0,
  218.      * a cookie will be sent to prepare for cookie-based login in future.
  219.      *
  220.      * Note, you have to set {@link allowAutoLogin} to true
  221.      * if you want to allow user to be authenticated based on the cookie information.
  222.      *
  223.      * @param IUserIdentity $identity the user identity (which should already be authenticated)
  224.      * @param integer $duration number of seconds that the user can remain in logged-in status. Defaults to 0, meaning login till the user closes the browser.
  225.      * If greater than 0, cookie-based login will be used. In this case, {@link allowAutoLogin}
  226.      * must be set true, otherwise an exception will be thrown.
  227.      * @return boolean whether the user is logged in
  228.      */
  229.     public function login($identity,$duration=0)
  230.     {
  231.         $id=$identity->getId();
  232.         $states=$identity->getPersistentStates();
  233.         if($this->beforeLogin($id,$states,false))
  234.         {
  235.             $this->changeIdentity($id,$identity->getName(),$states);
  236.  
  237.             if($duration>0)
  238.             {
  239.                 if($this->allowAutoLogin)
  240.                     $this->saveToCookie($duration);
  241.                 else
  242.                     throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  243.                         array('{class}'=>get_class($this))));
  244.             }
  245.  
  246.             if ($this->absoluteAuthTimeout)
  247.                 $this->setState(self::AUTH_ABSOLUTE_TIMEOUT_VAR, time()+$this->absoluteAuthTimeout);
  248.             $this->afterLogin(false);
  249.         }
  250.         return !$this->getIsGuest();
  251.     }
  252.  
  253.     /**
  254.      * Logs out the current user.
  255.      * This will remove authentication-related session data.
  256.      * If the parameter is true, the whole session will be destroyed as well.
  257.      * @param boolean $destroySession whether to destroy the whole session. Defaults to true. If false,
  258.      * then {@link clearStates} will be called, which removes only the data stored via {@link setState}.
  259.      */
  260.     public function logout($destroySession=true)
  261.     {
  262.         if($this->beforeLogout())
  263.         {
  264.             if($this->allowAutoLogin)
  265.             {
  266.                 Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  267.                 if($this->identityCookie!==null)
  268.                 {
  269.                     $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  270.                     $cookie->value=null;
  271.                     $cookie->expire=0;
  272.                     Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  273.                 }
  274.             }
  275.             if($destroySession)
  276.                 Yii::app()->getSession()->destroy();
  277.             else
  278.                 $this->clearStates();
  279.             $this->_access=array();
  280.             $this->afterLogout();
  281.         }
  282.     }
  283.  
  284.     /**
  285.      * Returns a value indicating whether the user is a guest (not authenticated).
  286.      * @return boolean whether the current application user is a guest.
  287.      */
  288.     public function getIsGuest()
  289.     {
  290.         return $this->getState('__id')===null;
  291.     }
  292.  
  293.     /**
  294.      * Returns a value that uniquely represents the user.
  295.      * @return mixed the unique identifier for the user. If null, it means the user is a guest.
  296.      */
  297.     public function getId()
  298.     {
  299.         return $this->getState('__id');
  300.     }
  301.  
  302.     /**
  303.      * @param mixed $value the unique identifier for the user. If null, it means the user is a guest.
  304.      */
  305.     public function setId($value)
  306.     {
  307.         $this->setState('__id',$value);
  308.     }
  309.  
  310.     /**
  311.      * Returns the unique identifier for the user (e.g. username).
  312.      * This is the unique identifier that is mainly used for display purpose.
  313.      * @return string the user name. If the user is not logged in, this will be {@link guestName}.
  314.      */
  315.     public function getName()
  316.     {
  317.         if(($name=$this->getState('__name'))!==null)
  318.             return $name;
  319.         else
  320.             return $this->guestName;
  321.     }
  322.  
  323.     /**
  324.      * Sets the unique identifier for the user (e.g. username).
  325.      * @param string $value the user name.
  326.      * @see getName
  327.      */
  328.     public function setName($value)
  329.     {
  330.         $this->setState('__name',$value);
  331.     }
  332.  
  333.     /**
  334.      * Returns the URL that the user should be redirected to after successful login.
  335.      * This property is usually used by the login action. If the login is successful,
  336.      * the action should read this property and use it to redirect the user browser.
  337.      * @param string $defaultUrl the default return URL in case it was not set previously. If this is null,
  338.      * the application entry URL will be considered as the default return URL.
  339.      * @return string the URL that the user should be redirected to after login.
  340.      * @see loginRequired
  341.      */
  342.     public function getReturnUrl($defaultUrl=null)
  343.     {
  344.         if($defaultUrl===null)
  345.         {
  346.             $defaultReturnUrl=Yii::app()->getUrlManager()->showScriptName ? Yii::app()->getRequest()->getScriptUrl() : Yii::app()->getRequest()->getBaseUrl().'/';
  347.         }
  348.         else
  349.         {
  350.             $defaultReturnUrl=CHtml::normalizeUrl($defaultUrl);
  351.         }
  352.         return $this->getState('__returnUrl',$defaultReturnUrl);
  353.     }
  354.  
  355.     /**
  356.      * @param string $value the URL that the user should be redirected to after login.
  357.      */
  358.     public function setReturnUrl($value)
  359.     {
  360.         $this->setState('__returnUrl',$value);
  361.     }
  362.  
  363.     /**
  364.      * Redirects the user browser to the login page.
  365.      * Before the redirection, the current URL (if it's not an AJAX url) will be
  366.      * kept in {@link returnUrl} so that the user browser may be redirected back
  367.      * to the current page after successful login. Make sure you set {@link loginUrl}
  368.      * so that the user browser can be redirected to the specified login URL after
  369.      * calling this method.
  370.      * After calling this method, the current request processing will be terminated.
  371.      */
  372.     public function loginRequired()
  373.     {
  374.         $app=Yii::app();
  375.         $request=$app->getRequest();
  376.  
  377.         if(!$request->getIsAjaxRequest())
  378.         {
  379.             $this->setReturnUrl($request->getUrl());
  380.             if(($url=$this->loginUrl)!==null)
  381.             {
  382.                 if(is_array($url))
  383.                 {
  384.                     $route=isset($url[0]) ? $url[0] : $app->defaultController;
  385.                     $url=$app->createUrl($route,array_splice($url,1));
  386.                 }
  387.                 $request->redirect($url);
  388.             }
  389.         }
  390.         elseif(isset($this->loginRequiredAjaxResponse))
  391.         {
  392.             echo $this->loginRequiredAjaxResponse;
  393.             Yii::app()->end();
  394.         }
  395.  
  396.         throw new CHttpException(403,Yii::t('yii','Login Required'));
  397.     }
  398.  
  399.     /**
  400.      * This method is called before logging in a user.
  401.      * You may override this method to provide additional security check.
  402.      * For example, when the login is cookie-based, you may want to verify
  403.      * that the user ID together with a random token in the states can be found
  404.      * in the database. This will prevent hackers from faking arbitrary
  405.      * identity cookies even if they crack down the server private key.
  406.      * @param mixed $id the user ID. This is the same as returned by {@link getId()}.
  407.      * @param array $states a set of name-value pairs that are provided by the user identity.
  408.      * @param boolean $fromCookie whether the login is based on cookie
  409.      * @return boolean whether the user should be logged in
  410.      * @since 1.1.3
  411.      */
  412.     protected function beforeLogin($id,$states,$fromCookie)
  413.     {
  414.         return true;
  415.     }
  416.  
  417.     /**
  418.      * This method is called after the user is successfully logged in.
  419.      * You may override this method to do some postprocessing (e.g. log the user
  420.      * login IP and time; load the user permission information).
  421.      * @param boolean $fromCookie whether the login is based on cookie.
  422.      * @since 1.1.3
  423.      */
  424.     protected function afterLogin($fromCookie)
  425.     {
  426.     }
  427.  
  428.     /**
  429.      * This method is invoked when calling {@link logout} to log out a user.
  430.      * If this method return false, the logout action will be cancelled.
  431.      * You may override this method to provide additional check before
  432.      * logging out a user.
  433.      * @return boolean whether to log out the user
  434.      * @since 1.1.3
  435.      */
  436.     protected function beforeLogout()
  437.     {
  438.         return true;
  439.     }
  440.  
  441.     /**
  442.      * This method is invoked right after a user is logged out.
  443.      * You may override this method to do some extra cleanup work for the user.
  444.      * @since 1.1.3
  445.      */
  446.     protected function afterLogout()
  447.     {
  448.     }
  449.  
  450.     /**
  451.      * Populates the current user object with the information obtained from cookie.
  452.      * This method is used when automatic login ({@link allowAutoLogin}) is enabled.
  453.      * The user identity information is recovered from cookie.
  454.      * Sufficient security measures are used to prevent cookie data from being tampered.
  455.      * @see saveToCookie
  456.      */
  457.     protected function restoreFromCookie()
  458.     {
  459.         $app=Yii::app();
  460.         $request=$app->getRequest();
  461.         $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  462.         if($cookie && !empty($cookie->value) && is_string($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  463.         {
  464.             $data=@unserialize($data);
  465.             if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  466.             {
  467.                 list($id,$name,$duration,$states)=$data;
  468.                 if($this->beforeLogin($id,$states,true))
  469.                 {
  470.                     $this->changeIdentity($id,$name,$states);
  471.                     if($this->autoRenewCookie)
  472.                     {
  473.                         $this->saveToCookie($duration);
  474.                     }
  475.                     $this->afterLogin(true);
  476.                 }
  477.             }
  478.         }
  479.     }
  480.  
  481.     /**
  482.      * Renews the identity cookie.
  483.      * This method will set the expiration time of the identity cookie to be the current time
  484.      * plus the originally specified cookie duration.
  485.      * @since 1.1.3
  486.      */
  487.     protected function renewCookie()
  488.     {
  489.         $request=Yii::app()->getRequest();
  490.         $cookies=$request->getCookies();
  491.         $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  492.         if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  493.         {
  494.             $data=@unserialize($data);
  495.             if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  496.             {
  497.                 $this->saveToCookie($data[2]);
  498.             }
  499.         }
  500.     }
  501.  
  502.     /**
  503.      * Saves necessary user data into a cookie.
  504.      * This method is used when automatic login ({@link allowAutoLogin}) is enabled.
  505.      * This method saves user ID, username, other identity states and a validation key to cookie.
  506.      * These information are used to do authentication next time when user visits the application.
  507.      * @param integer $duration number of seconds that the user can remain in logged-in status. Defaults to 0, meaning login till the user closes the browser.
  508.      * @see restoreFromCookie
  509.      */
  510.     protected function saveToCookie($duration)
  511.     {
  512.         $app=Yii::app();
  513.         $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  514.         $cookie->expire=time()+$duration;
  515.         $data=array(
  516.             $this->getId(),
  517.             $this->getName(),
  518.             $duration,
  519.             $this->saveIdentityStates(),
  520.         );
  521.         $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  522.         $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  523.     }
  524.  
  525.     /**
  526.      * Creates a cookie to store identity information.
  527.      * @param string $name the cookie name
  528.      * @return CHttpCookie the cookie used to store identity information
  529.      */
  530.     protected function createIdentityCookie($name)
  531.     {
  532.         $cookie=new CHttpCookie($name,'');
  533.         if(is_array($this->identityCookie))
  534.         {
  535.             foreach($this->identityCookie as $name=>$value)
  536.                 $cookie->$name=$value;
  537.         }
  538.         return $cookie;
  539.     }
  540.  
  541.     /**
  542.      * @return string a prefix for the name of the session variables storing user session data.
  543.      */
  544.     public function getStateKeyPrefix()
  545.     {
  546.         if($this->_keyPrefix!==null)
  547.             return $this->_keyPrefix;
  548.         else
  549.             return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  550.     }
  551.  
  552.     /**
  553.      * @param string $value a prefix for the name of the session variables storing user session data.
  554.      */
  555.     public function setStateKeyPrefix($value)
  556.     {
  557.         $this->_keyPrefix=$value;
  558.     }
  559.  
  560.     /**
  561.      * Returns the value of a variable that is stored in user session.
  562.      *
  563.      * This function is designed to be used by CWebUser descendant classes
  564.      * who want to store additional user information in user session.
  565.      * A variable, if stored in user session using {@link setState} can be
  566.      * retrieved back using this function.
  567.      *
  568.      * @param string $key variable name
  569.      * @param mixed $defaultValue default value
  570.      * @return mixed the value of the variable. If it doesn't exist in the session,
  571.      * the provided default value will be returned
  572.      * @see setState
  573.      */
  574.     public function getState($key,$defaultValue=null)
  575.     {
  576.         $key=$this->getStateKeyPrefix().$key;
  577.         return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  578.     }
  579.  
  580.     /**
  581.      * Stores a variable in user session.
  582.      *
  583.      * This function is designed to be used by CWebUser descendant classes
  584.      * who want to store additional user information in user session.
  585.      * By storing a variable using this function, the variable may be retrieved
  586.      * back later using {@link getState}. The variable will be persistent
  587.      * across page requests during a user session.
  588.      *
  589.      * @param string $key variable name
  590.      * @param mixed $value variable value
  591.      * @param mixed $defaultValue default value. If $value===$defaultValue, the variable will be
  592.      * removed from the session
  593.      * @see getState
  594.      */
  595.     public function setState($key,$value,$defaultValue=null)
  596.     {
  597.         $key=$this->getStateKeyPrefix().$key;
  598.         if($value===$defaultValue)
  599.             unset($_SESSION[$key]);
  600.         else
  601.             $_SESSION[$key]=$value;
  602.     }
  603.  
  604.     /**
  605.      * Returns a value indicating whether there is a state of the specified name.
  606.      * @param string $key state name
  607.      * @return boolean whether there is a state of the specified name.
  608.      */
  609.     public function hasState($key)
  610.     {
  611.         $key=$this->getStateKeyPrefix().$key;
  612.         return isset($_SESSION[$key]);
  613.     }
  614.  
  615.     /**
  616.      * Clears all user identity information from persistent storage.
  617.      * This will remove the data stored via {@link setState}.
  618.      */
  619.     public function clearStates()
  620.     {
  621.         $keys=array_keys($_SESSION);
  622.         $prefix=$this->getStateKeyPrefix();
  623.         $n=strlen($prefix);
  624.         foreach($keys as $key)
  625.         {
  626.             if(!strncmp($key,$prefix,$n))
  627.                 unset($_SESSION[$key]);
  628.         }
  629.     }
  630.  
  631.     /**
  632.      * Returns all flash messages.
  633.      * This method is similar to {@link getFlash} except that it returns all
  634.      * currently available flash messages.
  635.      * @param boolean $delete whether to delete the flash messages after calling this method.
  636.      * @return array flash messages (key => message).
  637.      * @since 1.1.3
  638.      */
  639.     public function getFlashes($delete=true)
  640.     {
  641.         $flashes=array();
  642.         $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  643.         $keys=array_keys($_SESSION);
  644.         $n=strlen($prefix);
  645.         foreach($keys as $key)
  646.         {
  647.             if(!strncmp($key,$prefix,$n))
  648.             {
  649.                 $flashes[substr($key,$n)]=$_SESSION[$key];
  650.                 if($delete)
  651.                     unset($_SESSION[$key]);
  652.             }
  653.         }
  654.         if($delete)
  655.             $this->setState(self::FLASH_COUNTERS,array());
  656.         return $flashes;
  657.     }
  658.  
  659.     /**
  660.      * Returns a flash message.
  661.      * A flash message is available only in the current and the next requests.
  662.      * @param string $key key identifying the flash message
  663.      * @param mixed $defaultValue value to be returned if the flash message is not available.
  664.      * @param boolean $delete whether to delete this flash message after accessing it.
  665.      * Defaults to true.
  666.      * @return mixed the message message
  667.      */
  668.     public function getFlash($key,$defaultValue=null,$delete=true)
  669.     {
  670.         $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  671.         if($delete)
  672.             $this->setFlash($key,null);
  673.         return $value;
  674.     }
  675.  
  676.     /**
  677.      * Stores a flash message.
  678.      * A flash message is available only in the current and the next requests.
  679.      * @param string $key key identifying the flash message
  680.      * @param mixed $value flash message
  681.      * @param mixed $defaultValue if this value is the same as the flash message, the flash message
  682.      * will be removed. (Therefore, you can use setFlash('key',null) to remove a flash message.)
  683.      */
  684.     public function setFlash($key,$value,$defaultValue=null)
  685.     {
  686.         $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  687.         $counters=$this->getState(self::FLASH_COUNTERS,array());
  688.         if($value===$defaultValue)
  689.             unset($counters[$key]);
  690.         else
  691.             $counters[$key]=0;
  692.         $this->setState(self::FLASH_COUNTERS,$counters,array());
  693.     }
  694.  
  695.     /**
  696.      * @param string $key key identifying the flash message
  697.      * @return boolean whether the specified flash message exists
  698.      */
  699.     public function hasFlash($key)
  700.     {
  701.         return $this->getFlash($key, null, false)!==null;
  702.     }
  703.  
  704.     /**
  705.      * Changes the current user with the specified identity information.
  706.      * This method is called by {@link login} and {@link restoreFromCookie}
  707.      * when the current user needs to be populated with the corresponding
  708.      * identity information. Derived classes may override this method
  709.      * by retrieving additional user-related information. Make sure the
  710.      * parent implementation is called first.
  711.      * @param mixed $id a unique identifier for the user
  712.      * @param string $name the display name for the user
  713.      * @param array $states identity states
  714.      */
  715.     protected function changeIdentity($id,$name,$states)
  716.     {
  717.         Yii::app()->getSession()->regenerateID(true);
  718.         $this->setId($id);
  719.         $this->setName($name);
  720.         $this->loadIdentityStates($states);
  721.     }
  722.  
  723.     /**
  724.      * Retrieves identity states from persistent storage and saves them as an array.
  725.      * @return array the identity states
  726.      */
  727.     protected function saveIdentityStates()
  728.     {
  729.         $states=array();
  730.         foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  731.             $states[$name]=$this->getState($name);
  732.         return $states;
  733.     }
  734.  
  735.     /**
  736.      * Loads identity states from an array and saves them to persistent storage.
  737.      * @param array $states the identity states
  738.      */
  739.     protected function loadIdentityStates($states)
  740.     {
  741.         $names=array();
  742.         if(is_array($states))
  743.         {
  744.             foreach($states as $name=>$value)
  745.             {
  746.                 $this->setState($name,$value);
  747.                 $names[$name]=true;
  748.             }
  749.         }
  750.         $this->setState(self::STATES_VAR,$names);
  751.     }
  752.  
  753.     /**
  754.      * Updates the internal counters for flash messages.
  755.      * This method is internally used by {@link CWebApplication}
  756.      * to maintain the availability of flash messages.
  757.      */
  758.     protected function updateFlash()
  759.     {
  760.         $counters=$this->getState(self::FLASH_COUNTERS);
  761.         if(!is_array($counters))
  762.             return;
  763.         foreach($counters as $key=>$count)
  764.         {
  765.             if($count)
  766.             {
  767.                 unset($counters[$key]);
  768.                 $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  769.             }
  770.             else
  771.                 $counters[$key]++;
  772.         }
  773.         $this->setState(self::FLASH_COUNTERS,$counters,array());
  774.     }
  775.  
  776.     /**
  777.      * Updates the authentication status according to {@link authTimeout}.
  778.      * If the user has been inactive for {@link authTimeout} seconds, or {link absoluteAuthTimeout} has passed,
  779.      * he will be automatically logged out.
  780.      * @since 1.1.7
  781.      */
  782.     protected function updateAuthStatus()
  783.     {
  784.         if(($this->authTimeout!==null || $this->absoluteAuthTimeout!==null) && !$this->getIsGuest())
  785.         {
  786.             $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  787.             $expiresAbsolute=$this->getState(self::AUTH_ABSOLUTE_TIMEOUT_VAR);
  788.  
  789.             if ($expires!==null && $expires < time() || $expiresAbsolute!==null && $expiresAbsolute < time())
  790.                 $this->logout(false);
  791.             else
  792.                 $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  793.         }
  794.     }
  795.  
  796.     /**
  797.      * Performs access check for this user.
  798.      * @param string $operation the name of the operation that need access check.
  799.      * @param array $params name-value pairs that would be passed to business rules associated
  800.      * with the tasks and roles assigned to the user.
  801.      * Since version 1.1.11 a param with name 'userId' is added to this array, which holds the value of
  802.      * {@link getId()} when {@link CDbAuthManager} or {@link CPhpAuthManager} is used.
  803.      * @param boolean $allowCaching whether to allow caching the result of access check.
  804.      * When this parameter
  805.      * is true (default), if the access check of an operation was performed before,
  806.      * its result will be directly returned when calling this method to check the same operation.
  807.      * If this parameter is false, this method will always call {@link CAuthManager::checkAccess}
  808.      * to obtain the up-to-date access result. Note that this caching is effective
  809.      * only within the same request and only works when <code>$params=array()</code>.
  810.      * @return boolean whether the operations can be performed by this user.
  811.      */
  812.     public function checkAccess($operation,$params=array(),$allowCaching=true)
  813.     {
  814.         if($allowCaching && $params===array() && isset($this->_access[$operation]))
  815.             return $this->_access[$operation];
  816.  
  817.         $access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  818.         if($allowCaching && $params===array())
  819.             $this->_access[$operation]=$access;
  820.  
  821.         return $access;
  822.     }
  823. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement