Php.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\storage\session\adapter;
  9. use lithium\util\Set;
  10. use RuntimeException;
  11. use lithium\core\ConfigException;
  12. /**
  13. * A minimal adapter to interface with native PHP sessions.
  14. *
  15. * This adapter provides basic support for `write`, `read` and `delete`
  16. * session handling, as well as allowing these three methods to be filtered as
  17. * per the Lithium filtering system.
  18. *
  19. */
  20. class Php extends \lithium\core\Object {
  21. /**
  22. * Default ini settings for this session adapter.
  23. *
  24. * @var array Keys are session ini settings, with the `session.` namespace.
  25. */
  26. protected $_defaults = array(
  27. 'session.cookie_lifetime' => '0',
  28. 'session.cookie_httponly' => true
  29. );
  30. /**
  31. * Class constructor.
  32. *
  33. * Takes care of setting appropriate configurations for this object.
  34. *
  35. * @param array $config Unified constructor configuration parameters. You can set
  36. * the `session.*` PHP ini settings here as key/value pairs.
  37. */
  38. public function __construct(array $config = array()) {
  39. if (empty($config['session.name'])) {
  40. $config['session.name'] = basename(LITHIUM_APP_PATH);
  41. }
  42. parent::__construct($config + $this->_defaults);
  43. }
  44. /**
  45. * Initialization of the session.
  46. *
  47. * @todo Split up into an _initialize() and a _start().
  48. * @return void
  49. */
  50. protected function _init() {
  51. if (static::isStarted()) {
  52. return true;
  53. }
  54. $config = $this->_config;
  55. unset($config['adapter'], $config['strategies'], $config['filters'], $config['init']);
  56. foreach ($config as $key => $value) {
  57. if (strpos($key, 'session.') === false) {
  58. continue;
  59. }
  60. if (ini_set($key, $value) === false) {
  61. throw new ConfigException("Could not initialize the session.");
  62. }
  63. }
  64. }
  65. /**
  66. * Starts the session.
  67. *
  68. * @return boolean True if session successfully started (or has already been started),
  69. * false otherwise.
  70. */
  71. protected static function _start() {
  72. if (session_id()) {
  73. return true;
  74. }
  75. if (!isset($_SESSION)) {
  76. session_cache_limiter('nocache');
  77. }
  78. return session_start();
  79. }
  80. /**
  81. * Obtain the status of the session.
  82. *
  83. * @return boolean True if $_SESSION is accessible and if a '_timestamp' key
  84. * has been set, false otherwise.
  85. */
  86. public static function isStarted() {
  87. return (boolean) session_id();
  88. }
  89. /**
  90. * Sets or obtains the session ID.
  91. *
  92. * @param string $key Optional. If specified, sets the session ID to the value of `$key`.
  93. * @return mixed Session ID, or `null` if the session has not been started.
  94. */
  95. public static function key($key = null) {
  96. if ($key) {
  97. return session_id($key);
  98. }
  99. return session_id() ?: null;
  100. }
  101. /**
  102. * Checks if a value has been set in the session.
  103. *
  104. * @param string $key Key of the entry to be checked.
  105. * @param array $options Options array. Not used for this adapter method.
  106. * @return closure Function returning boolean `true` if the key exists, `false` otherwise.
  107. */
  108. public static function check($key, array $options = array()) {
  109. if (!static::isStarted() && !static::_start()) {
  110. throw new RuntimeException("Could not start session.");
  111. }
  112. return function($self, $params) {
  113. return Set::check($_SESSION, $params['key']);
  114. };
  115. }
  116. /**
  117. * Read a value from the session.
  118. *
  119. * @param null|string $key Key of the entry to be read. If no key is passed, all
  120. * current session data is returned.
  121. * @param array $options Options array. Not used for this adapter method.
  122. * @return closure Function returning data in the session if successful, `false` otherwise.
  123. */
  124. public static function read($key = null, array $options = array()) {
  125. if (!static::isStarted() && !static::_start()) {
  126. throw new RuntimeException("Could not start session.");
  127. }
  128. return function($self, $params) {
  129. $key = $params['key'];
  130. if (!$key) {
  131. return $_SESSION;
  132. }
  133. if (strpos($key, '.') === false) {
  134. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  135. }
  136. $filter = function($keys, $data) use (&$filter) {
  137. $key = array_shift($keys);
  138. if (isset($data[$key])) {
  139. return (empty($keys)) ? $data[$key] : $filter($keys, $data[$key]);
  140. }
  141. };
  142. return $filter(explode('.', $key), $_SESSION);
  143. };
  144. }
  145. /**
  146. * Write a value to the session.
  147. *
  148. * @param string $key Key of the item to be stored.
  149. * @param mixed $value The value to be stored.
  150. * @param array $options Options array. Not used for this adapter method.
  151. * @return closure Function returning boolean `true` on successful write, `false` otherwise.
  152. */
  153. public static function write($key, $value, array $options = array()) {
  154. if (!static::isStarted() && !static::_start()) {
  155. throw new RuntimeException("Could not start session.");
  156. }
  157. $class = __CLASS__;
  158. return function($self, $params) use ($class) {
  159. return $class::overwrite(
  160. $_SESSION, Set::insert($_SESSION, $params['key'], $params['value'])
  161. );
  162. };
  163. }
  164. /**
  165. * Delete value from the session
  166. *
  167. * @param string $key The key to be deleted
  168. * @param array $options Options array. Not used for this adapter method.
  169. * @return closure Function returning boolean `true` if the key no longer exists
  170. * in the session, `false` otherwise
  171. */
  172. public static function delete($key, array $options = array()) {
  173. if (!static::isStarted() && !static::_start()) {
  174. throw new RuntimeException("Could not start session.");
  175. }
  176. $class = __CLASS__;
  177. return function($self, $params) use ($class) {
  178. $key = $params['key'];
  179. $class::overwrite($_SESSION, Set::remove($_SESSION, $key));
  180. return !Set::check($_SESSION, $key);
  181. };
  182. }
  183. /**
  184. * Clears all keys from the session.
  185. *
  186. * @param array $options Options array. Not used fro this adapter method.
  187. * @return closure Function returning boolean `true` on successful clear, `false` otherwise.
  188. */
  189. public function clear(array $options = array()) {
  190. if (!static::isStarted() && !static::_start()) {
  191. throw new RuntimeException("Could not start session.");
  192. }
  193. return function($self, $params) {
  194. return session_destroy();
  195. };
  196. }
  197. /**
  198. * Determines if PHP sessions are enabled.
  199. *
  200. * @return boolean True if enabled (that is, if session_id() returns a value), false otherwise.
  201. */
  202. public static function enabled() {
  203. return (boolean) session_id();
  204. }
  205. /**
  206. * Overwrites session keys and values.
  207. *
  208. * @param array $old Reference to the array that needs to be overwritten. Will usually
  209. * be `$_SESSION`.
  210. * @param array $new The data that should overwrite the keys/values in `$old`.
  211. * @return boolean Always `true`
  212. */
  213. public static function overwrite(&$old, $new) {
  214. if (!empty($old)) {
  215. foreach ($old as $key => $value) {
  216. if (!isset($new[$key])) {
  217. unset($old[$key]);
  218. }
  219. }
  220. }
  221. foreach ($new as $key => $value) {
  222. $old[$key] = $value;
  223. }
  224. return true;
  225. }
  226. }
  227. ?>