memcached.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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_Memcached extends \Session_Driver
  15. {
  16. /**
  17. * array of driver config defaults
  18. */
  19. protected static $_defaults = array(
  20. 'cookie_name' => 'fuelmid', // name of the session cookie for memcached based sessions
  21. 'servers' => array( // array of servers and portnumbers that run the memcached service
  22. array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100)
  23. )
  24. );
  25. /*
  26. * @var storage for the memcached object
  27. */
  28. protected $memcached = false;
  29. // --------------------------------------------------------------------
  30. public function __construct($config = array())
  31. {
  32. // merge the driver config with the global config
  33. $this->config = array_merge($config, is_array($config['memcached']) ? $config['memcached'] : static::$_defaults);
  34. $this->config = $this->_validate_config($this->config);
  35. // adjust the expiration time to the maximum possible for memcached
  36. $this->config['expiration_time'] = min($this->config['expiration_time'], 2592000);
  37. }
  38. // --------------------------------------------------------------------
  39. /**
  40. * driver initialisation
  41. *
  42. * @access public
  43. * @return void
  44. */
  45. public function init()
  46. {
  47. // generic driver initialisation
  48. parent::init();
  49. if ($this->memcached === false)
  50. {
  51. // do we have the PHP memcached extension available
  52. if ( ! class_exists('Memcached') )
  53. {
  54. throw new \FuelException('Memcached sessions are configured, but your PHP installation doesn\'t have the Memcached extension loaded.');
  55. }
  56. // instantiate the memcached object
  57. $this->memcached = new \Memcached();
  58. // add the configured servers
  59. $this->memcached->addServers($this->config['servers']);
  60. // check if we can connect to the server(s)
  61. if ($this->memcached->getVersion() === false)
  62. {
  63. throw new \FuelException('Memcached sessions are configured, but there is no connection possible. Check your configuration.');
  64. }
  65. }
  66. }
  67. // --------------------------------------------------------------------
  68. /**
  69. * create a new session
  70. *
  71. * @access public
  72. * @return Fuel\Core\Session_Memcached
  73. */
  74. public function create()
  75. {
  76. // create a new session
  77. $this->keys['session_id'] = $this->_new_session_id();
  78. $this->keys['previous_id'] = $this->keys['session_id']; // prevents errors if previous_id has a unique index
  79. $this->keys['ip_hash'] = md5(\Input::ip().\Input::real_ip());
  80. $this->keys['user_agent'] = \Input::user_agent();
  81. $this->keys['created'] = $this->time->get_timestamp();
  82. $this->keys['updated'] = $this->keys['created'];
  83. return $this;
  84. }
  85. // --------------------------------------------------------------------
  86. /**
  87. * read the session
  88. *
  89. * @access public
  90. * @param boolean, set to true if we want to force a new session to be created
  91. * @return Fuel\Core\Session_Driver
  92. */
  93. public function read($force = false)
  94. {
  95. // initialize the session
  96. $this->data = array();
  97. $this->keys = array();
  98. $this->flash = array();
  99. // get the session cookie
  100. $cookie = $this->_get_cookie();
  101. // if a cookie was present, find the session record
  102. if ($cookie and ! $force and isset($cookie[0]))
  103. {
  104. // read the session file
  105. $payload = $this->_read_memcached($cookie[0]);
  106. if ($payload === false)
  107. {
  108. // cookie present, but session record missing. force creation of a new session
  109. return $this->read(true);
  110. }
  111. // unpack the payload
  112. $payload = $this->_unserialize($payload);
  113. // session referral?
  114. if (isset($payload['rotated_session_id']))
  115. {
  116. $payload = $this->_read_memcached($payload['rotated_session_id']);
  117. if ($payload === false)
  118. {
  119. // cookie present, but session record missing. force creation of a new session
  120. return $this->read(true);
  121. }
  122. else
  123. {
  124. // unpack the payload
  125. $payload = $this->_unserialize($payload);
  126. }
  127. }
  128. if ( ! isset($payload[0]) or ! is_array($payload[0]))
  129. {
  130. // not a valid cookie payload
  131. }
  132. elseif ($payload[0]['updated'] + $this->config['expiration_time'] <= $this->time->get_timestamp())
  133. {
  134. // session has expired
  135. }
  136. elseif ($this->config['match_ip'] and $payload[0]['ip_hash'] !== md5(\Input::ip().\Input::real_ip()))
  137. {
  138. // IP address doesn't match
  139. }
  140. elseif ($this->config['match_ua'] and $payload[0]['user_agent'] !== \Input::user_agent())
  141. {
  142. // user agent doesn't match
  143. }
  144. else
  145. {
  146. // session is valid, retrieve the rest of the payload
  147. if (isset($payload[0]) and is_array($payload[0])) $this->keys = $payload[0];
  148. if (isset($payload[1]) and is_array($payload[1])) $this->data = $payload[1];
  149. if (isset($payload[2]) and is_array($payload[2])) $this->flash = $payload[2];
  150. }
  151. }
  152. return parent::read();
  153. }
  154. // --------------------------------------------------------------------
  155. /**
  156. * write the session
  157. *
  158. * @access public
  159. * @return Fuel\Core\Session_Memcached
  160. */
  161. public function write()
  162. {
  163. // do we have something to write?
  164. if ( ! empty($this->keys) or ! empty($this->data) or ! empty($this->flash))
  165. {
  166. parent::write();
  167. // rotate the session id if needed
  168. $this->rotate(false);
  169. // session payload
  170. $payload = $this->_serialize(array($this->keys, $this->data, $this->flash));
  171. // create the session file
  172. $this->_write_memcached($this->keys['session_id'], $payload);
  173. // was the session id rotated?
  174. if ( isset($this->keys['previous_id']) and $this->keys['previous_id'] != $this->keys['session_id'])
  175. {
  176. // point the old session file to the new one, we don't want to lose the session
  177. $payload = $this->_serialize(array('rotated_session_id' => $this->keys['session_id']));
  178. $this->_write_memcached($this->keys['previous_id'], $payload);
  179. }
  180. $this->_set_cookie(array($this->keys['session_id']));
  181. }
  182. return $this;
  183. }
  184. // --------------------------------------------------------------------
  185. /**
  186. * destroy the current session
  187. *
  188. * @access public
  189. * @return Fuel\Core\Session_Memcached
  190. */
  191. public function destroy()
  192. {
  193. // do we have something to destroy?
  194. if ( ! empty($this->keys))
  195. {
  196. // delete the key from the memcached server
  197. if ($this->memcached->delete($this->config['cookie_name'].'_'.$this->keys['session_id']) === false)
  198. {
  199. throw new \FuelException('Memcached returned error code "'.$this->memcached->getResultCode().'" on delete. Check your configuration.');
  200. }
  201. }
  202. parent::destroy();
  203. return $this;
  204. }
  205. // --------------------------------------------------------------------
  206. /**
  207. * Writes the memcached entry
  208. *
  209. * @access private
  210. * @return boolean, true if it was an existing session, false if not
  211. */
  212. protected function _write_memcached($session_id, $payload)
  213. {
  214. // write it to the memcached server
  215. if ($this->memcached->set($this->config['cookie_name'].'_'.$session_id, $payload, $this->config['expiration_time']) === false)
  216. {
  217. throw new \FuelException('Memcached returned error code "'.$this->memcached->getResultCode().'" on write. Check your configuration.');
  218. }
  219. }
  220. // --------------------------------------------------------------------
  221. /**
  222. * Reads the memcached entry
  223. *
  224. * @access private
  225. * @return mixed, the payload if the file exists, or false if not
  226. */
  227. protected function _read_memcached($session_id)
  228. {
  229. // fetch the session data from the Memcached server
  230. return $this->memcached->get($this->config['cookie_name'].'_'.$session_id);
  231. }
  232. // --------------------------------------------------------------------
  233. /**
  234. * validate a driver config value
  235. *
  236. * @param array array with configuration values
  237. * @access public
  238. * @return array validated and consolidated config
  239. */
  240. public function _validate_config($config)
  241. {
  242. $validated = array();
  243. foreach ($config as $name => $item)
  244. {
  245. if ($name == 'memcached' and is_array($item))
  246. {
  247. foreach ($item as $name => $value)
  248. {
  249. switch ($name)
  250. {
  251. case 'cookie_name':
  252. if ( empty($value) or ! is_string($value))
  253. {
  254. $value = 'fuelmid';
  255. }
  256. break;
  257. case 'servers':
  258. // do we have a servers config
  259. if ( empty($value) or ! is_array($value))
  260. {
  261. $value = array('default' => array('host' => '127.0.0.1', 'port' => '11211'));
  262. }
  263. // validate the servers
  264. foreach ($value as $key => $server)
  265. {
  266. // do we have a host?
  267. if ( ! isset($server['host']) or ! is_string($server['host']))
  268. {
  269. throw new \FuelException('Invalid Memcached server definition in the session configuration.');
  270. }
  271. // do we have a port number?
  272. if ( ! isset($server['port']) or ! is_numeric($server['port']) or $server['port'] < 1025 or $server['port'] > 65535)
  273. {
  274. throw new \FuelException('Invalid Memcached server definition in the session configuration.');
  275. }
  276. // do we have a relative server weight?
  277. if ( ! isset($server['weight']) or ! is_numeric($server['weight']) or $server['weight'] < 0)
  278. {
  279. // set a default
  280. $value[$key]['weight'] = 0;
  281. }
  282. }
  283. break;
  284. default:
  285. // unknown property
  286. continue;
  287. }
  288. $validated[$name] = $value;
  289. }
  290. }
  291. else
  292. {
  293. // skip all config array properties
  294. if (is_array($item))
  295. {
  296. continue;
  297. }
  298. // global config, was validated in the driver
  299. $validated[$name] = $item;
  300. }
  301. }
  302. // validate all global settings as well
  303. return parent::_validate_config($validated);
  304. }
  305. }