Tutorial Extension  1.0.0
SellerDeck Extensions - Tutorial Extension
CSession.php
1 <?php
2 
3 /**
4  * Session Helper Class
5  *
6  * A simple session wrapper class.
7  *
8  * Recommended for use with PHP 5.4.0 or higher. (Not required.)
9  *
10  * Usage Example:
11  * <?php
12  * try {
13  * Session::w('foo', 'bar');
14  *
15  * echo Session::r('foo');
16  * }
17  * catch (Exception $e) {
18  * // do something
19  * }
20  * ?>
21  *
22  * Copyright (c) 2013 Robert Dunham
23  * Modified by Peter Erdodi (c) 2015 SellerDeck Ltd.
24  *
25  * Permission is hereby granted, free of charge, to any person obtaining a copy
26  * of this software and associated documentation files (the "Software"), to deal
27  * in the Software without restriction, including without limitation the rights
28  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
29  * copies of the Software, and to permit persons to whom the Software is
30  * furnished to do so, subject to the following conditions:
31  *
32  * The above copyright notice and this permission notice shall be included in
33  * all copies or substantial portions of the Software.
34  *
35  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
38  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
41  * THE SOFTWARE.
42  *
43  * @remarks A simple session wrapper class.
44  * @author Robert Dunham <contact@robdunham.info>
45  * @website http://www.robdunham.info
46  * @version 1.0.3
47  * @date 20130514
48  * @copyright Copyright (c) 2013, Robert Dunham
49  */
50 
51 namespace SDExtension\Helper;
52 
53 class SessionHandlerException extends \Exception
54  {
55 
56  }
57 
59  {
60 
61  }
62 
64  {
65 
66  }
67 
69  {
70 
71  }
72 
73 //defined('CHECK_ACCESS') or die('Direct access is not allowed.');
74 
75 class CSession
76  {
77 
78  /**
79  * Session Age.
80  *
81  * The number of seconds of inactivity before a session expires.
82  *
83  * @var integer
84  */
85  protected static $SESSION_AGE = 1800;
86 
87  /**
88  * Writes a value to the current session data.
89  *
90  * @param string $key String identifier.
91  * @param mixed $value Single value or array of values to be written.
92  * @return mixed Value or array of values written.
93  * @throws InvalidArgumentTypeException Session key is not a string value.
94  */
95  public static function write($key, $value)
96  {
97  if (!is_string($key))
98  {
99  $sErrorMessage = 'Session key must be string value';
100  \SDExtension\Helper\CLogger::get(LOG_CHANNEL_NAME)->addError($sErrorMessage);
101  throw new InvalidArgumentTypeException($sErrorMessage);
102  }
103  self::_init();
104  $_SESSION[$key] = $value;
105  self::_age();
106  return $value;
107  }
108 
109  /**
110  * Alias for {@link Session::write()}.
111  *
112  * @see CSession::write()
113  * @param string $key String identifier.
114  * @param mixed $value Single value or array of values to be written.
115  * @return mixed Value or array of values written.
116  * @throws InvalidArgumentTypeException Session key is not a string value.
117  */
118  public static function w($key, $value)
119  {
120  return self::write($key, $value);
121  }
122 
123  /**
124  * Reads a specific value from the current session data.
125  *
126  * @param string $key String identifier.
127  * @param mixed $default Default value
128  * @param boolean $child Optional child identifier for accessing array elements.
129  * @return mixed Returns a string value upon success. Returns false upon failure.
130  * @throws InvalidArgumentTypeException Session key is not a string value.
131  */
132  public static function read($key, $default = false, $child = false)
133  {
134  if (!is_string($key))
135  {
136  $sErrorMessage = 'Session key must be string value';
137  \SDExtension\Helper\CLogger::get(LOG_CHANNEL_NAME)->addError($sErrorMessage);
138  throw new InvalidArgumentTypeException($sErrorMessage);
139  }
140  self::_init();
141  if (isset($_SESSION[$key]))
142  {
143  self::_age();
144 
145  if (false == $child)
146  {
147  return $_SESSION[$key];
148  }
149  else
150  {
151  if (isset($_SESSION[$key][$child]))
152  {
153  return $_SESSION[$key][$child];
154  }
155  }
156  }
157  else
158  {
159  return $default;
160  }
161  }
162 
163  /**
164  * Alias for {@link Session::read()}.
165  *
166  * @see CSession::read()
167  * @param string $key String identifier.
168  * @param mixed $default Default value
169  * @param boolean $child Optional child identifier for accessing array elements.
170  * @return mixed Returns a string value upon success. Returns false upon failure.
171  * @throws InvalidArgumentTypeException Session key is not a string value.
172  */
173  public static function r($key, $default = false, $child = false)
174  {
175  return self::read($key, $default, $child);
176  }
177 
178  /**
179  * Deletes a value from the current session data.
180  *
181  * @param string $key String identifying the array key to delete.
182  * @return void
183  * @throws InvalidArgumentTypeException Session key is not a string value.
184  */
185  public static function delete($key)
186  {
187  if (!is_string($key))
188  {
189  $sErrorMessage = 'Session key must be string value';
190  \SDExtension\Helper\CLogger::get(LOG_CHANNEL_NAME)->addError($sErrorMessage);
191  throw new InvalidArgumentTypeException($sErrorMessage);
192  }
193  self::_init();
194  unset($_SESSION[$key]);
195  self::_age();
196  }
197 
198  /**
199  * Alias for {@link Session::delete()}.
200  *
201  * @see CSession::delete()
202  * @param string $key String identifying the key to delete from session data.
203  * @return void
204  * @throws InvalidArgumentTypeException Session key is not a string value.
205  */
206  public static function d($key)
207  {
208  self::delete($key);
209  }
210 
211  /**
212  * Echos current session data.
213  *
214  * @return void
215  */
216  public static function dump()
217  {
218  self::_init();
219  echo nl2br(print_r($_SESSION));
220  }
221 
222  /**
223  * Starts or resumes a session by calling {@link Session::_init()}.
224  *
225  * @see CSession::_init()
226  * @return boolean Returns true upon success and false upon failure.
227  * @throws SessionDisabledException Sessions are disabled.
228  */
229  public static function start()
230  {
231  // this function is extraneous
232  return self::_init();
233  }
234 
235  /**
236  * Expires a session if it has been inactive for a specified amount of time.
237  *
238  * @return void
239  * @throws ExpiredSessionException() Throws exception when read or write is attempted on an expired session.
240  */
241  private static function _age()
242  {
243  $last = isset($_SESSION['LAST_ACTIVE']) ? $_SESSION['LAST_ACTIVE'] : false;
244 
245  if (false !== $last && (time() - $last > self::$SESSION_AGE))
246  {
247  self::destroy();
248  \SDExtension\Helper\CLogger::get(LOG_CHANNEL_NAME)->addError('Session Expired');
249  throw new ExpiredSessionException();
250  }
251  $_SESSION['LAST_ACTIVE'] = time();
252  }
253 
254  /**
255  * Returns current session cookie parameters or an empty array.
256  *
257  * @return array Associative array of session cookie parameters.
258  */
259  public static function params()
260  {
261  $r = array();
262  if ('' !== session_id())
263  {
264  $r = session_get_cookie_params();
265  }
266  return $r;
267  }
268 
269  /**
270  * Closes the current session and releases session file lock.
271  *
272  * @return boolean Returns true upon success and false upon failure.
273  */
274  public static function close()
275  {
276  if ('' !== session_id())
277  {
278  return session_write_close();
279  }
280  return true;
281  }
282 
283  /**
284  * Alias for {@link Session::close()}.
285  *
286  * @see CSession::close()
287  * @return boolean Returns true upon success and false upon failure.
288  */
289  public static function commit()
290  {
291  return self::close();
292  }
293 
294  /**
295  * Removes session data and destroys the current session.
296  *
297  * @return void
298  */
299  public static function destroy()
300  {
301  if ('' !== session_id())
302  {
303  $_SESSION = array();
304 
305  // If it's desired to kill the session, also delete the session cookie.
306  // Note: This will destroy the session, and not just the session data!
307  if (ini_get("session.use_cookies"))
308  {
309  $params = session_get_cookie_params();
310  setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]
311  );
312  }
313 
314  session_destroy();
315  }
316  }
317 
318  /**
319  * Initializes a new session or resumes an existing session.
320  *
321  * @return boolean Returns true upon success and false upon failure.
322  * @throws SessionDisabledException Sessions are disabled.
323  */
324  private static function _init()
325  {
326  if (function_exists('session_status'))
327  {
328  // PHP 5.4.0+
329  if (session_status() == PHP_SESSION_DISABLED)
330  {
331  throw new SessionDisabledException();
332  }
333  }
334 
335  if ('' === session_id())
336  {
337  return session_start();
338  }
339  // Helps prevent hijacking by resetting the session ID at every request.
340  // Might cause unnecessary file I/O overhead?
341  // TODO: create config variable to control regenerate ID behavior
342  return session_regenerate_id(true);
343  }
344 
345  }
static get($sChannel="default", $sLogRoot="")
Definition: CLogger.php:90
static read($key, $default=false, $child=false)
Definition: CSession.php:132
static write($key, $value)
Definition: CSession.php:95
static w($key, $value)
Definition: CSession.php:118
static r($key, $default=false, $child=false)
Definition: CSession.php:173