Session.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. <?php
  2. /**
  3. * Implementation of PHP's session API.
  4. * What it does:
  5. * - it handles the session data in the database (more scalable.)
  6. * - it uses the databaseSession_lifetime setting for garbage collection.
  7. * - the custom session handler is set by loadSession().
  8. *
  9. * Simple Machines Forum (SMF)
  10. *
  11. * @package SMF
  12. * @author Simple Machines http://www.simplemachines.org
  13. * @copyright 2011 Simple Machines
  14. * @license http://www.simplemachines.org/about/smf/license.php BSD
  15. *
  16. * @version 2.1 Alpha 1
  17. */
  18. if (!defined('SMF'))
  19. die('Hacking attempt...');
  20. /**
  21. * Attempt to start the session, unless it already has been.
  22. */
  23. function loadSession()
  24. {
  25. global $HTTP_SESSION_VARS, $modSettings, $boardurl, $sc;
  26. // Attempt to change a few PHP settings.
  27. @ini_set('session.use_cookies', true);
  28. @ini_set('session.use_only_cookies', false);
  29. @ini_set('url_rewriter.tags', '');
  30. @ini_set('session.use_trans_sid', false);
  31. @ini_set('arg_separator.output', '&amp;');
  32. if (!empty($modSettings['globalCookies']))
  33. {
  34. $parsed_url = parse_url($boardurl);
  35. if (preg_match('~^\d{1,3}(\.\d{1,3}){3}$~', $parsed_url['host']) == 0 && preg_match('~(?:[^\.]+\.)?([^\.]{2,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
  36. @ini_set('session.cookie_domain', '.' . $parts[1]);
  37. }
  38. // @todo Set the session cookie path?
  39. // If it's already been started... probably best to skip this.
  40. if ((ini_get('session.auto_start') == 1 && !empty($modSettings['databaseSession_enable'])) || session_id() == '')
  41. {
  42. // Attempt to end the already-started session.
  43. if (ini_get('session.auto_start') == 1)
  44. session_write_close();
  45. // This is here to stop people from using bad junky PHPSESSIDs.
  46. {
  47. $session_id = md5(md5('smf_sess_' . time()) . mt_rand());
  48. $_REQUEST[session_name()] = $session_id;
  49. $_GET[session_name()] = $session_id;
  50. $_POST[session_name()] = $session_id;
  51. }
  52. // Use database sessions? (they don't work in 4.1.x!)
  53. if (!empty($modSettings['databaseSession_enable']))
  54. {
  55. session_set_save_handler('sessionOpen', 'sessionClose', 'sessionRead', 'sessionWrite', 'sessionDestroy', 'sessionGC');
  56. @ini_set('session.gc_probability', '1');
  57. }
  58. elseif (ini_get('session.gc_maxlifetime') <= 1440 && !empty($modSettings['databaseSession_lifetime']))
  59. @ini_set('session.gc_maxlifetime', max($modSettings['databaseSession_lifetime'], 60));
  60. // Use cache setting sessions?
  61. if (empty($modSettings['databaseSession_enable']) && !empty($modSettings['cache_enable']) && php_sapi_name() != 'cli')
  62. {
  63. call_integration_hook('integrate_session_handlers');
  64. // @todo move these to a plugin.
  65. if (function_exists('mmcache_set_session_handlers'))
  66. mmcache_set_session_handlers();
  67. elseif (function_exists('eaccelerator_set_session_handlers'))
  68. eaccelerator_set_session_handlers();
  69. }
  70. session_start();
  71. // Change it so the cache settings are a little looser than default.
  72. if (!empty($modSettings['databaseSession_loose']))
  73. header('Cache-Control: private');
  74. }
  75. // Set the randomly generated code.
  76. if (!isset($_SESSION['session_var']))
  77. {
  78. $_SESSION['session_value'] = md5(session_id() . mt_rand());
  79. $_SESSION['session_var'] = substr(preg_replace('~^\d+~', '', sha1(mt_rand() . session_id() . mt_rand())), 0, rand(7, 12));
  80. }
  81. $sc = $_SESSION['session_value'];
  82. }
  83. /**
  84. * Implementation of sessionOpen() replacing the standard open handler.
  85. * It simply returns true.
  86. *
  87. * @param string $save_path
  88. * @param string $session_name
  89. * @return bool
  90. */
  91. function sessionOpen($save_path, $session_name)
  92. {
  93. return true;
  94. }
  95. /**
  96. * Implementation of sessionClose() replacing the standard close handler.
  97. * It simply returns true.
  98. *
  99. * @return bool
  100. */
  101. function sessionClose()
  102. {
  103. return true;
  104. }
  105. /**
  106. * Implementation of sessionRead() replacing the standard read handler.
  107. *
  108. * @param string $session_id
  109. * @return string
  110. */
  111. function sessionRead($session_id)
  112. {
  113. global $smcFunc;
  114. if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0)
  115. return false;
  116. // Look for it in the database.
  117. $result = $smcFunc['db_query']('', '
  118. SELECT data
  119. FROM {db_prefix}sessions
  120. WHERE session_id = {string:session_id}
  121. LIMIT 1',
  122. array(
  123. 'session_id' => $session_id,
  124. )
  125. );
  126. list ($sess_data) = $smcFunc['db_fetch_row']($result);
  127. $smcFunc['db_free_result']($result);
  128. return $sess_data;
  129. }
  130. /**
  131. * Implementation of sessionWrite() replacing the standard write handler.
  132. *
  133. * @param string $session_id
  134. * @param string $data
  135. * @return bool
  136. */
  137. function sessionWrite($session_id, $data)
  138. {
  139. global $smcFunc;
  140. if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0)
  141. return false;
  142. // First try to update an existing row...
  143. $result = $smcFunc['db_query']('', '
  144. UPDATE {db_prefix}sessions
  145. SET data = {string:data}, last_update = {int:last_update}
  146. WHERE session_id = {string:session_id}',
  147. array(
  148. 'last_update' => time(),
  149. 'data' => $data,
  150. 'session_id' => $session_id,
  151. )
  152. );
  153. // If that didn't work, try inserting a new one.
  154. if ($smcFunc['db_affected_rows']() == 0)
  155. $result = $smcFunc['db_insert']('ignore',
  156. '{db_prefix}sessions',
  157. array('session_id' => 'string', 'data' => 'string', 'last_update' => 'int'),
  158. array($session_id, $data, time()),
  159. array('session_id')
  160. );
  161. return $result;
  162. }
  163. /**
  164. * Implementation of sessionDestroy() replacing the standard destroy handler.
  165. *
  166. * @param string $session_id
  167. * @return bool
  168. */
  169. function sessionDestroy($session_id)
  170. {
  171. global $smcFunc;
  172. if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0)
  173. return false;
  174. // Just delete the row...
  175. return $smcFunc['db_query']('', '
  176. DELETE FROM {db_prefix}sessions
  177. WHERE session_id = {string:session_id}',
  178. array(
  179. 'session_id' => $session_id,
  180. )
  181. );
  182. }
  183. /**
  184. * Implementation of sessionDestroy() replacing the standard gc handler.
  185. * Callback for garbage collection.
  186. *
  187. * @param int $max_lifetime
  188. * @return bool
  189. */
  190. function sessionGC($max_lifetime)
  191. {
  192. global $modSettings, $smcFunc;
  193. // Just set to the default or lower? Ignore it for a higher value. (hopefully)
  194. if (!empty($modSettings['databaseSession_lifetime']) && ($max_lifetime <= 1440 || $modSettings['databaseSession_lifetime'] > $max_lifetime))
  195. $max_lifetime = max($modSettings['databaseSession_lifetime'], 60);
  196. // Clean up after yerself ;).
  197. return $smcFunc['db_query']('', '
  198. DELETE FROM {db_prefix}sessions
  199. WHERE last_update < {int:last_update}',
  200. array(
  201. 'last_update' => time() - $max_lifetime,
  202. )
  203. );
  204. }