sfCacheSessionStorage.class.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. /**
  3. * sfCacheSessionStorage manages session storage via a signed cookie and cache backend.
  4. *
  5. * This class stores the session data in via sfCache instance and with an id issued in a
  6. * signed cookie. Useful when you don't want to store the session.
  7. *
  8. * @package symfony
  9. * @subpackage storage
  10. * @author Dustin Whittle <dustin.whittle@symfony-project.com>
  11. */
  12. class sfCacheSessionStorage extends sfStorage
  13. {
  14. protected
  15. $context = null,
  16. $request = null,
  17. $response = null,
  18. $cache = null,
  19. $data = array(),
  20. $dataChanged = false;
  21. /**
  22. * Initialize this Storage.
  23. *
  24. * @param array An associative array of initialization parameters.
  25. * session_name [required] name of session to use
  26. * session_cookie_path [required] cookie path
  27. * session_cookie_domain [required] cookie domain
  28. * session_cookie_lifetime [required] liftime of cookie
  29. * session_cookie_secure [required] send only if secure connection
  30. * session_cookie_http_only [required] accessible only via http protocol
  31. *
  32. * @return bool true, if initialization completes successfully, otherwise false.
  33. *
  34. * @throws <b>sfInitializationException</b> If an error occurs while initializing this Storage.
  35. */
  36. public function initialize($options = array())
  37. {
  38. // initialize parent
  39. parent::initialize(array_merge(array('session_name' => 'sfproject',
  40. 'session_cookie_lifetime' => '+30 days',
  41. 'session_cookie_path' => '/',
  42. 'session_cookie_domain' => null,
  43. 'session_cookie_secure' => false,
  44. 'session_cookie_http_only' => true,
  45. 'session_cookie_secret' => 'sf$ecret'), $options));
  46. // create cache instance
  47. if (isset($this->options['cache']) && $this->options['cache']['class'])
  48. {
  49. $this->cache = new $this->options['cache']['class'](is_array($this->options['cache']['param']) ? $this->options['cache']['param'] : array());
  50. }
  51. else
  52. {
  53. throw new InvalidArgumentException('sfCacheSessionStorage requires cache option.');
  54. }
  55. $this->context = sfContext::getInstance();
  56. $this->dispatcher = $this->context->getEventDispatcher();
  57. $this->request = $this->context->getRequest();
  58. $this->response = $this->context->getResponse();
  59. $cookie = $this->request->getCookie($this->options['session_name']);
  60. if(strpos($cookie, ':') !== false)
  61. {
  62. // split cookie data id:signature(id+secret)
  63. list($id, $signature) = explode(':', $cookie, 2);
  64. if($signature == sha1($id.':'.$this->options['session_cookie_secret']))
  65. {
  66. // cookie is valid
  67. $this->id = $id;
  68. }
  69. else
  70. {
  71. // cookie signature broken
  72. $this->id = null;
  73. }
  74. }
  75. else
  76. {
  77. // cookie format wrong
  78. $this->id = null;
  79. }
  80. if(empty($this->id))
  81. {
  82. $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'localhost';
  83. $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'ua';
  84. // generate new id based on random # / ip / user agent / secret
  85. $this->id = md5(rand(0, 999999).$ip.$ua.$this->options['session_cookie_secret']);
  86. if(sfConfig::get('sf_logging_enabled'))
  87. {
  88. $this->dispatcher->notify(new sfEvent($this, 'application.log', array('New session created')));
  89. }
  90. // only send cookie when id is issued
  91. $this->response->setCookie($this->options['session_name'],
  92. $this->id.':'.sha1($this->id.':'.$this->options['session_cookie_secret']),
  93. $this->options['session_cookie_lifetime'],
  94. $this->options['session_cookie_path'],
  95. $this->options['session_cookie_domain'],
  96. $this->options['session_cookie_secure'],
  97. $this->options['session_cookie_http_only']);
  98. $this->data = array();
  99. }
  100. else
  101. {
  102. // load data from cache
  103. $this->data = $this->cache->get($this->id, array());
  104. if(sfConfig::get('sf_logging_enabled'))
  105. {
  106. $this->dispatcher->notify(new sfEvent($this, 'application.log', array('Restored previous session')));
  107. }
  108. }
  109. return true;
  110. }
  111. /**
  112. * Write data to this storage.
  113. *
  114. * The preferred format for a key is directory style so naming conflicts can be avoided.
  115. *
  116. * @param string A unique key identifying your data.
  117. * @param mixed Data associated with your key.
  118. *
  119. * @return void
  120. */
  121. public function write($key, $data)
  122. {
  123. $this->dataChanged = true;
  124. $this->data[$key] =& $data;
  125. }
  126. /**
  127. * Read data from this storage.
  128. *
  129. * The preferred format for a key is directory style so naming conflicts can be avoided.
  130. *
  131. * @param string A unique key identifying your data.
  132. *
  133. * @return mixed Data associated with the key.
  134. */
  135. public function read($key)
  136. {
  137. $retval = null;
  138. if (isset($this->data[$key]))
  139. {
  140. $retval =& $this->data[$key];
  141. }
  142. return $retval;
  143. }
  144. /**
  145. * Remove data from this storage.
  146. *
  147. * The preferred format for a key is directory style so naming conflicts can be avoided.
  148. *
  149. * @param string A unique key identifying your data.
  150. *
  151. * @return mixed Data associated with the key.
  152. */
  153. public function remove($key)
  154. {
  155. $retval = null;
  156. if (isset($this->data[$key]))
  157. {
  158. $this->dataChanged = true;
  159. $retval =& $this->data[$key];
  160. unset($this->data[$key]);
  161. }
  162. return $retval;
  163. }
  164. /**
  165. * Regenerates id that represents this storage.
  166. *
  167. * @param boolean Destroy session when regenerating?
  168. *
  169. * @return boolean True if session regenerated, false if error
  170. *
  171. * @throws <b>sfStorageException</b> If an error occurs while regenerating this storage
  172. */
  173. public function regenerate($destroy = false)
  174. {
  175. if($destroy)
  176. {
  177. $this->data = array();
  178. $this->cache->remove($this->id);
  179. }
  180. // generate session id
  181. $this->id = md5(rand(0, 999999).$_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT'].$this->options['session_cookie_secret']);
  182. // save data to cache
  183. $this->cache->set($this->id, $this->data);
  184. // update session id in signed cookie
  185. $this->response->setCookie($this->options['session_name'],
  186. $this->id.':'.sha1($this->id.':'.$this->options['session_cookie_secret']),
  187. $this->options['session_cookie_lifetime'],
  188. $this->options['session_cookie_path'],
  189. $this->options['session_cookie_domain'],
  190. $this->options['session_cookie_secure'],
  191. $this->options['session_cookie_http_only']);
  192. return true;
  193. }
  194. /**
  195. * Expires the session storage instance.
  196. */
  197. public function expire()
  198. {
  199. // destroy data and regenerate id
  200. $this->regenerate(true);
  201. if(sfConfig::get('sf_logging_enabled'))
  202. {
  203. $this->dispatcher->notify(new sfEvent($this, 'application.log', array('new session created due to expiraton')));
  204. }
  205. }
  206. /**
  207. * Executes the shutdown procedure.
  208. *
  209. * @throws <b>sfStorageException</b> If an error occurs while shutting down this storage
  210. */
  211. public function shutdown()
  212. {
  213. // only update cache if session has changed
  214. if($this->dataChanged === true)
  215. {
  216. $this->cache->set($this->id, $this->data);
  217. if(sfConfig::get('sf_logging_enabled'))
  218. {
  219. $this->dispatcher->notify(new sfEvent($this, 'application.log', array('Storing session to cache')));
  220. // $this->dispatcher->notify(new sfEvent($this, 'application.log', array(var_export($this->data, true))));
  221. }
  222. }
  223. }
  224. }