PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/fuel/core/classes/session/db.php

https://bitbucket.org/codeyash/bootstrap
PHP | 297 lines | 162 code | 45 blank | 90 comment | 19 complexity | ea71dc4f5863a7eabc4296af8a28fc6e MD5 | raw file
Possible License(s): MIT, Apache-2.0
  1. <?php
  2. /**
  3. * Part of the Fuel framework.
  4. *
  5. * @package Fuel
  6. * @version 1.5
  7. * @author Fuel Development Team
  8. * @license MIT License
  9. * @copyright 2010 - 2013 Fuel Development Team
  10. * @link http://fuelphp.com
  11. */
  12. namespace Fuel\Core;
  13. // --------------------------------------------------------------------
  14. class Session_Db extends \Session_Driver
  15. {
  16. /*
  17. * @var session database result object
  18. */
  19. protected $record = null;
  20. /**
  21. * array of driver config defaults
  22. */
  23. protected static $_defaults = array(
  24. 'cookie_name' => 'fueldid', // name of the session cookie for database based sessions
  25. 'table' => 'sessions', // name of the sessions table
  26. 'gc_probability' => 5 // probability % (between 0 and 100) for garbage collection
  27. );
  28. // --------------------------------------------------------------------
  29. public function __construct($config = array())
  30. {
  31. // merge the driver config with the global config
  32. $this->config = array_merge($config, is_array($config['db']) ? $config['db'] : static::$_defaults);
  33. $this->config = $this->_validate_config($this->config);
  34. }
  35. // --------------------------------------------------------------------
  36. /**
  37. * create a new session
  38. *
  39. * @access public
  40. * @return Fuel\Core\Session_Db
  41. */
  42. public function create($payload = '')
  43. {
  44. // create a new session
  45. $this->keys['session_id'] = $this->_new_session_id();
  46. $this->keys['previous_id'] = $this->keys['session_id']; // prevents errors if previous_id has a unique index
  47. $this->keys['ip_hash'] = md5(\Input::ip().\Input::real_ip());
  48. $this->keys['user_agent'] = \Input::user_agent();
  49. $this->keys['created'] = $this->time->get_timestamp();
  50. $this->keys['updated'] = $this->keys['created'];
  51. // add the payload
  52. $this->keys['payload'] = $payload;
  53. return $this;
  54. }
  55. // --------------------------------------------------------------------
  56. /**
  57. * read the session
  58. *
  59. * @access public
  60. * @param boolean, set to true if we want to force a new session to be created
  61. * @return Fuel\Core\Session_Driver
  62. */
  63. public function read($force = false)
  64. {
  65. // initialize the session
  66. $this->data = array();
  67. $this->keys = array();
  68. $this->flash = array();
  69. $this->record = null;
  70. // get the session cookie
  71. $cookie = $this->_get_cookie();
  72. // if a cookie was present, find the session record
  73. if ($cookie and ! $force and isset($cookie[0]))
  74. {
  75. // read the session record
  76. $this->record = \DB::select()->where('session_id', '=', $cookie[0])->from($this->config['table'])->execute($this->config['database']);
  77. // record found?
  78. if ($this->record->count())
  79. {
  80. $payload = $this->_unserialize($this->record->get('payload'));
  81. }
  82. else
  83. {
  84. // try to find the session on previous id
  85. $this->record = \DB::select()->where('previous_id', '=', $cookie[0])->from($this->config['table'])->execute($this->config['database']);
  86. // record found?
  87. if ($this->record->count())
  88. {
  89. $payload = $this->_unserialize($this->record->get('payload'));
  90. }
  91. else
  92. {
  93. // cookie present, but session record missing. force creation of a new session
  94. return $this->read(true);
  95. }
  96. }
  97. if ( ! isset($payload[0]) or ! is_array($payload[0]))
  98. {
  99. // not a valid cookie payload
  100. }
  101. elseif ($payload[0]['updated'] + $this->config['expiration_time'] <= $this->time->get_timestamp())
  102. {
  103. // session has expired
  104. }
  105. elseif ($this->config['match_ip'] and $payload[0]['ip_hash'] !== md5(\Input::ip().\Input::real_ip()))
  106. {
  107. // IP address doesn't match
  108. }
  109. elseif ($this->config['match_ua'] and $payload[0]['user_agent'] !== \Input::user_agent())
  110. {
  111. // user agent doesn't match
  112. }
  113. else
  114. {
  115. // session is valid, retrieve the payload
  116. if (isset($payload[0]) and is_array($payload[0])) $this->keys = $payload[0];
  117. if (isset($payload[1]) and is_array($payload[1])) $this->data = $payload[1];
  118. if (isset($payload[2]) and is_array($payload[2])) $this->flash = $payload[2];
  119. }
  120. }
  121. return parent::read();
  122. }
  123. // --------------------------------------------------------------------
  124. /**
  125. * write the current session
  126. *
  127. * @access public
  128. * @return Fuel\Core\Session_Db
  129. */
  130. public function write()
  131. {
  132. // do we have something to write?
  133. if ( ! empty($this->keys) or ! empty($this->data) or ! empty($this->flash))
  134. {
  135. parent::write();
  136. // rotate the session id if needed
  137. $this->rotate(false);
  138. // create the session record, and add the session payload
  139. $session = $this->keys;
  140. $session['payload'] = $this->_serialize(array($this->keys, $this->data, $this->flash));
  141. // do we need to create a new session?
  142. if (is_null($this->record))
  143. {
  144. // create the new session record
  145. $result = \DB::insert($this->config['table'], array_keys($session))->values($session)->execute($this->config['database']);
  146. }
  147. else
  148. {
  149. // update the database
  150. $result = \DB::update($this->config['table'])->set($session)->where('session_id', '=', $this->record->get('session_id'))->execute($this->config['database']);
  151. }
  152. // update went well?
  153. if ($result !== false)
  154. {
  155. // then update the cookie
  156. $this->_set_cookie(array($this->keys['session_id']));
  157. }
  158. else
  159. {
  160. logger(\Fuel::L_ERROR, 'Session update failed, session record could not be found. Concurrency issue?');
  161. }
  162. // do some garbage collection
  163. if (mt_rand(0,100) < $this->config['gc_probability'])
  164. {
  165. $expired = $this->time->get_timestamp() - $this->config['expiration_time'];
  166. $result = \DB::delete($this->config['table'])->where('updated', '<', $expired)->execute($this->config['database']);
  167. }
  168. }
  169. return $this;
  170. }
  171. // --------------------------------------------------------------------
  172. /**
  173. * destroy the current session
  174. *
  175. * @access public
  176. * @return Fuel\Core\Session_Db
  177. */
  178. public function destroy()
  179. {
  180. // do we have something to destroy?
  181. if ( ! empty($this->keys) and ! empty($this->record))
  182. {
  183. // delete the session record
  184. $result = \DB::delete($this->config['table'])->where('session_id', '=', $this->keys['session_id'])->execute($this->config['database']);
  185. }
  186. // reset the stored session data
  187. $this->record = null;
  188. parent::destroy();
  189. return $this;
  190. }
  191. // --------------------------------------------------------------------
  192. /**
  193. * validate a driver config value
  194. *
  195. * @param array array with configuration values
  196. * @access public
  197. * @return array validated and consolidated config
  198. */
  199. public function _validate_config($config)
  200. {
  201. $validated = array();
  202. foreach ($config as $name => $item)
  203. {
  204. // filter out any driver config
  205. if (!is_array($item))
  206. {
  207. switch ($name)
  208. {
  209. case 'cookie_name':
  210. if ( empty($item) or ! is_string($item))
  211. {
  212. $item = 'fueldid';
  213. }
  214. break;
  215. case 'database':
  216. // do we have a database?
  217. if ( empty($item) or ! is_string($item))
  218. {
  219. \Config::load('db', true);
  220. $item = \Config::get('db.active', false);
  221. }
  222. if ($item === false)
  223. {
  224. throw new \FuelException('You have specify a database to use database backed sessions.');
  225. }
  226. break;
  227. case 'table':
  228. // and a table name?
  229. if ( empty($item) or ! is_string($item))
  230. {
  231. throw new \FuelException('You have specify a database table name to use database backed sessions.');
  232. }
  233. break;
  234. case 'gc_probability':
  235. // do we have a path?
  236. if ( ! is_numeric($item) or $item < 0 or $item > 100)
  237. {
  238. // default value: 5%
  239. $item = 5;
  240. }
  241. break;
  242. default:
  243. break;
  244. }
  245. // global config, was validated in the driver
  246. $validated[$name] = $item;
  247. }
  248. }
  249. // validate all global settings as well
  250. return parent::_validate_config($validated);
  251. }
  252. }