PageRenderTime 187ms CodeModel.GetById 22ms RepoModel.GetById 11ms app.codeStats 1ms

/yii/framework/web/auth/CWebUser.php

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