You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

420 lines
10 KiB

7 years ago
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 3.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * CodeIgniter Session Database Driver
  41. *
  42. * @package CodeIgniter
  43. * @subpackage Libraries
  44. * @category Sessions
  45. * @author Andrey Andreev
  46. * @link https://codeigniter.com/user_guide/libraries/sessions.html
  47. */
  48. class CI_Session_database_driver extends CI_Session_driver implements SessionHandlerInterface {
  49. /**
  50. * DB object
  51. *
  52. * @var object
  53. */
  54. protected $_db;
  55. /**
  56. * Row exists flag
  57. *
  58. * @var bool
  59. */
  60. protected $_row_exists = FALSE;
  61. /**
  62. * Lock "driver" flag
  63. *
  64. * @var string
  65. */
  66. protected $_platform;
  67. // ------------------------------------------------------------------------
  68. /**
  69. * Class constructor
  70. *
  71. * @param array $params Configuration parameters
  72. * @return void
  73. */
  74. public function __construct(&$params)
  75. {
  76. parent::__construct($params);
  77. $CI =& get_instance();
  78. isset($CI->db) OR $CI->load->database();
  79. $this->_db = $CI->db;
  80. if ( ! $this->_db instanceof CI_DB_query_builder)
  81. {
  82. throw new Exception('Query Builder not enabled for the configured database. Aborting.');
  83. }
  84. elseif ($this->_db->pconnect)
  85. {
  86. throw new Exception('Configured database connection is persistent. Aborting.');
  87. }
  88. elseif ($this->_db->cache_on)
  89. {
  90. throw new Exception('Configured database connection has cache enabled. Aborting.');
  91. }
  92. $db_driver = $this->_db->dbdriver.(empty($this->_db->subdriver) ? '' : '_'.$this->_db->subdriver);
  93. if (strpos($db_driver, 'mysql') !== FALSE)
  94. {
  95. $this->_platform = 'mysql';
  96. }
  97. elseif (in_array($db_driver, array('postgre', 'pdo_pgsql'), TRUE))
  98. {
  99. $this->_platform = 'postgre';
  100. }
  101. // Note: BC work-around for the old 'sess_table_name' setting, should be removed in the future.
  102. if ( ! isset($this->_config['save_path']) && ($this->_config['save_path'] = config_item('sess_table_name')))
  103. {
  104. log_message('debug', 'Session: "sess_save_path" is empty; using BC fallback to "sess_table_name".');
  105. }
  106. }
  107. // ------------------------------------------------------------------------
  108. /**
  109. * Open
  110. *
  111. * Initializes the database connection
  112. *
  113. * @param string $save_path Table name
  114. * @param string $name Session cookie name, unused
  115. * @return bool
  116. */
  117. public function open($save_path, $name)
  118. {
  119. if (empty($this->_db->conn_id) && ! $this->_db->db_connect())
  120. {
  121. return $this->_fail();
  122. }
  123. return $this->_success;
  124. }
  125. // ------------------------------------------------------------------------
  126. /**
  127. * Read
  128. *
  129. * Reads session data and acquires a lock
  130. *
  131. * @param string $session_id Session ID
  132. * @return string Serialized session data
  133. */
  134. public function read($session_id)
  135. {
  136. if ($this->_get_lock($session_id) !== FALSE)
  137. {
  138. // Prevent previous QB calls from messing with our queries
  139. $this->_db->reset_query();
  140. // Needed by write() to detect session_regenerate_id() calls
  141. $this->_session_id = $session_id;
  142. $this->_db
  143. ->select('data')
  144. ->from($this->_config['save_path'])
  145. ->where('id', $session_id);
  146. if ($this->_config['match_ip'])
  147. {
  148. $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
  149. }
  150. if ( ! ($result = $this->_db->get()) OR ($result = $result->row()) === NULL)
  151. {
  152. // PHP7 will reuse the same SessionHandler object after
  153. // ID regeneration, so we need to explicitly set this to
  154. // FALSE instead of relying on the default ...
  155. $this->_row_exists = FALSE;
  156. $this->_fingerprint = md5('');
  157. return '';
  158. }
  159. // PostgreSQL's variant of a BLOB datatype is Bytea, which is a
  160. // PITA to work with, so we use base64-encoded data in a TEXT
  161. // field instead.
  162. $result = ($this->_platform === 'postgre')
  163. ? base64_decode(rtrim($result->data))
  164. : $result->data;
  165. $this->_fingerprint = md5($result);
  166. $this->_row_exists = TRUE;
  167. return $result;
  168. }
  169. $this->_fingerprint = md5('');
  170. return '';
  171. }
  172. // ------------------------------------------------------------------------
  173. /**
  174. * Write
  175. *
  176. * Writes (create / update) session data
  177. *
  178. * @param string $session_id Session ID
  179. * @param string $session_data Serialized session data
  180. * @return bool
  181. */
  182. public function write($session_id, $session_data)
  183. {
  184. // Prevent previous QB calls from messing with our queries
  185. $this->_db->reset_query();
  186. // Was the ID regenerated?
  187. if (isset($this->_session_id) && $session_id !== $this->_session_id)
  188. {
  189. if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
  190. {
  191. return $this->_fail();
  192. }
  193. $this->_row_exists = FALSE;
  194. $this->_session_id = $session_id;
  195. }
  196. elseif ($this->_lock === FALSE)
  197. {
  198. return $this->_fail();
  199. }
  200. if ($this->_row_exists === FALSE)
  201. {
  202. $insert_data = array(
  203. 'id' => $session_id,
  204. 'ip_address' => $_SERVER['REMOTE_ADDR'],
  205. 'timestamp' => time(),
  206. 'data' => ($this->_platform === 'postgre' ? base64_encode($session_data) : $session_data)
  207. );
  208. if ($this->_db->insert($this->_config['save_path'], $insert_data))
  209. {
  210. $this->_fingerprint = md5($session_data);
  211. $this->_row_exists = TRUE;
  212. return $this->_success;
  213. }
  214. return $this->_fail();
  215. }
  216. $this->_db->where('id', $session_id);
  217. if ($this->_config['match_ip'])
  218. {
  219. $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
  220. }
  221. $update_data = array('timestamp' => time());
  222. if ($this->_fingerprint !== md5($session_data))
  223. {
  224. $update_data['data'] = ($this->_platform === 'postgre')
  225. ? base64_encode($session_data)
  226. : $session_data;
  227. }
  228. if ($this->_db->update($this->_config['save_path'], $update_data))
  229. {
  230. $this->_fingerprint = md5($session_data);
  231. return $this->_success;
  232. }
  233. return $this->_fail();
  234. }
  235. // ------------------------------------------------------------------------
  236. /**
  237. * Close
  238. *
  239. * Releases locks
  240. *
  241. * @return bool
  242. */
  243. public function close()
  244. {
  245. return ($this->_lock && ! $this->_release_lock())
  246. ? $this->_fail()
  247. : $this->_success;
  248. }
  249. // ------------------------------------------------------------------------
  250. /**
  251. * Destroy
  252. *
  253. * Destroys the current session.
  254. *
  255. * @param string $session_id Session ID
  256. * @return bool
  257. */
  258. public function destroy($session_id)
  259. {
  260. if ($this->_lock)
  261. {
  262. // Prevent previous QB calls from messing with our queries
  263. $this->_db->reset_query();
  264. $this->_db->where('id', $session_id);
  265. if ($this->_config['match_ip'])
  266. {
  267. $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
  268. }
  269. if ( ! $this->_db->delete($this->_config['save_path']))
  270. {
  271. return $this->_fail();
  272. }
  273. }
  274. if ($this->close() === $this->_success)
  275. {
  276. $this->_cookie_destroy();
  277. return $this->_success;
  278. }
  279. return $this->_fail();
  280. }
  281. // ------------------------------------------------------------------------
  282. /**
  283. * Garbage Collector
  284. *
  285. * Deletes expired sessions
  286. *
  287. * @param int $maxlifetime Maximum lifetime of sessions
  288. * @return bool
  289. */
  290. public function gc($maxlifetime)
  291. {
  292. // Prevent previous QB calls from messing with our queries
  293. $this->_db->reset_query();
  294. return ($this->_db->delete($this->_config['save_path'], 'timestamp < '.(time() - $maxlifetime)))
  295. ? $this->_success
  296. : $this->_fail();
  297. }
  298. // ------------------------------------------------------------------------
  299. /**
  300. * Get lock
  301. *
  302. * Acquires a lock, depending on the underlying platform.
  303. *
  304. * @param string $session_id Session ID
  305. * @return bool
  306. */
  307. protected function _get_lock($session_id)
  308. {
  309. if ($this->_platform === 'mysql')
  310. {
  311. $arg = md5($session_id.($this->_config['match_ip'] ? '_'.$_SERVER['REMOTE_ADDR'] : ''));
  312. if ($this->_db->query("SELECT GET_LOCK('".$arg."', 300) AS ci_session_lock")->row()->ci_session_lock)
  313. {
  314. $this->_lock = $arg;
  315. return TRUE;
  316. }
  317. return FALSE;
  318. }
  319. elseif ($this->_platform === 'postgre')
  320. {
  321. $arg = "hashtext('".$session_id."')".($this->_config['match_ip'] ? ", hashtext('".$_SERVER['REMOTE_ADDR']."')" : '');
  322. if ($this->_db->simple_query('SELECT pg_advisory_lock('.$arg.')'))
  323. {
  324. $this->_lock = $arg;
  325. return TRUE;
  326. }
  327. return FALSE;
  328. }
  329. return parent::_get_lock($session_id);
  330. }
  331. // ------------------------------------------------------------------------
  332. /**
  333. * Release lock
  334. *
  335. * Releases a previously acquired lock
  336. *
  337. * @return bool
  338. */
  339. protected function _release_lock()
  340. {
  341. if ( ! $this->_lock)
  342. {
  343. return TRUE;
  344. }
  345. if ($this->_platform === 'mysql')
  346. {
  347. if ($this->_db->query("SELECT RELEASE_LOCK('".$this->_lock."') AS ci_session_lock")->row()->ci_session_lock)
  348. {
  349. $this->_lock = FALSE;
  350. return TRUE;
  351. }
  352. return FALSE;
  353. }
  354. elseif ($this->_platform === 'postgre')
  355. {
  356. if ($this->_db->simple_query('SELECT pg_advisory_unlock('.$this->_lock.')'))
  357. {
  358. $this->_lock = FALSE;
  359. return TRUE;
  360. }
  361. return FALSE;
  362. }
  363. return parent::_release_lock();
  364. }
  365. }