2
0

Session.php 6.3 KB

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