Session.php 6.4 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. if (isset($_REQUEST[session_name()]) && preg_match('~^[A-Za-z0-9,-]{16,64}$~', $_REQUEST[session_name()]) == 0 && !isset($_COOKIE[session_name()]))
  47. {
  48. $session_id = md5(md5('smf_sess_' . time()) . mt_rand());
  49. $_REQUEST[session_name()] = $session_id;
  50. $_GET[session_name()] = $session_id;
  51. $_POST[session_name()] = $session_id;
  52. }
  53. // Use database sessions? (they don't work in 4.1.x!)
  54. if (!empty($modSettings['databaseSession_enable']))
  55. {
  56. session_set_save_handler('sessionOpen', 'sessionClose', 'sessionRead', 'sessionWrite', 'sessionDestroy', 'sessionGC');
  57. @ini_set('session.gc_probability', '1');
  58. }
  59. elseif (ini_get('session.gc_maxlifetime') <= 1440 && !empty($modSettings['databaseSession_lifetime']))
  60. @ini_set('session.gc_maxlifetime', max($modSettings['databaseSession_lifetime'], 60));
  61. // Use cache setting sessions?
  62. if (empty($modSettings['databaseSession_enable']) && !empty($modSettings['cache_enable']) && php_sapi_name() != 'cli')
  63. {
  64. call_integration_hook('integrate_session_handlers');
  65. // @todo move these to a plugin.
  66. if (function_exists('mmcache_set_session_handlers'))
  67. mmcache_set_session_handlers();
  68. elseif (function_exists('eaccelerator_set_session_handlers'))
  69. eaccelerator_set_session_handlers();
  70. }
  71. session_start();
  72. // Change it so the cache settings are a little looser than default.
  73. if (!empty($modSettings['databaseSession_loose']))
  74. header('Cache-Control: private');
  75. }
  76. // Set the randomly generated code.
  77. if (!isset($_SESSION['session_var']))
  78. {
  79. $_SESSION['session_value'] = md5(session_id() . mt_rand());
  80. $_SESSION['session_var'] = substr(preg_replace('~^\d+~', '', sha1(mt_rand() . session_id() . mt_rand())), 0, rand(7, 12));
  81. }
  82. $sc = $_SESSION['session_value'];
  83. }
  84. /**
  85. * Implementation of sessionOpen() replacing the standard open handler.
  86. * It simply returns true.
  87. *
  88. * @param string $save_path
  89. * @param string $session_name
  90. * @return bool
  91. */
  92. function sessionOpen($save_path, $session_name)
  93. {
  94. return true;
  95. }
  96. /**
  97. * Implementation of sessionClose() replacing the standard close handler.
  98. * It simply returns true.
  99. *
  100. * @return bool
  101. */
  102. function sessionClose()
  103. {
  104. return true;
  105. }
  106. /**
  107. * Implementation of sessionRead() replacing the standard read handler.
  108. *
  109. * @param string $session_id
  110. * @return string
  111. */
  112. function sessionRead($session_id)
  113. {
  114. global $smcFunc;
  115. if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0)
  116. return false;
  117. // Look for it in the database.
  118. $result = $smcFunc['db_query']('', '
  119. SELECT data
  120. FROM {db_prefix}sessions
  121. WHERE session_id = {string:session_id}
  122. LIMIT 1',
  123. array(
  124. 'session_id' => $session_id,
  125. )
  126. );
  127. list ($sess_data) = $smcFunc['db_fetch_row']($result);
  128. $smcFunc['db_free_result']($result);
  129. return $sess_data;
  130. }
  131. /**
  132. * Implementation of sessionWrite() replacing the standard write handler.
  133. *
  134. * @param string $session_id
  135. * @param string $data
  136. * @return bool
  137. */
  138. function sessionWrite($session_id, $data)
  139. {
  140. global $smcFunc;
  141. if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0)
  142. return false;
  143. // First try to update an existing row...
  144. $result = $smcFunc['db_query']('', '
  145. UPDATE {db_prefix}sessions
  146. SET data = {string:data}, last_update = {int:last_update}
  147. WHERE session_id = {string:session_id}',
  148. array(
  149. 'last_update' => time(),
  150. 'data' => $data,
  151. 'session_id' => $session_id,
  152. )
  153. );
  154. // If that didn't work, try inserting a new one.
  155. if ($smcFunc['db_affected_rows']() == 0)
  156. $result = $smcFunc['db_insert']('ignore',
  157. '{db_prefix}sessions',
  158. array('session_id' => 'string', 'data' => 'string', 'last_update' => 'int'),
  159. array($session_id, $data, time()),
  160. array('session_id')
  161. );
  162. return $result;
  163. }
  164. /**
  165. * Implementation of sessionDestroy() replacing the standard destroy handler.
  166. *
  167. * @param string $session_id
  168. * @return bool
  169. */
  170. function sessionDestroy($session_id)
  171. {
  172. global $smcFunc;
  173. if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0)
  174. return false;
  175. // Just delete the row...
  176. return $smcFunc['db_query']('', '
  177. DELETE FROM {db_prefix}sessions
  178. WHERE session_id = {string:session_id}',
  179. array(
  180. 'session_id' => $session_id,
  181. )
  182. );
  183. }
  184. /**
  185. * Implementation of sessionGC() replacing the standard gc handler.
  186. * Callback for garbage collection.
  187. *
  188. * @param int $max_lifetime
  189. * @return bool
  190. */
  191. function sessionGC($max_lifetime)
  192. {
  193. global $modSettings, $smcFunc;
  194. // Just set to the default or lower? Ignore it for a higher value. (hopefully)
  195. if (!empty($modSettings['databaseSession_lifetime']) && ($max_lifetime <= 1440 || $modSettings['databaseSession_lifetime'] > $max_lifetime))
  196. $max_lifetime = max($modSettings['databaseSession_lifetime'], 60);
  197. // Clean up after yerself ;).
  198. return $smcFunc['db_query']('', '
  199. DELETE FROM {db_prefix}sessions
  200. WHERE last_update < {int:last_update}',
  201. array(
  202. 'last_update' => time() - $max_lifetime,
  203. )
  204. );
  205. }