Sin descripción

Session.php 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace NSL\Persistent\Storage;
  3. class Session extends StorageAbstract {
  4. /**
  5. * @var string name of the cookie. Can be changed with nsl_session_name filter and NSL_SESSION_NAME constant.
  6. *
  7. * @see https://pantheon.io/docs/caching-advanced-topics/
  8. */
  9. private $sessionName = 'SESSnsl';
  10. public function __construct() {
  11. /**
  12. * WP Engine hosting needs custom cookie name to prevent caching.
  13. *
  14. * @see https://wpengine.com/support/wpengine-ecommerce/
  15. */
  16. if (class_exists('WpePlugin_common', false)) {
  17. $this->sessionName = 'wordpress_nsl';
  18. }
  19. if (defined('NSL_SESSION_NAME')) {
  20. $this->sessionName = NSL_SESSION_NAME;
  21. }
  22. $this->sessionName = apply_filters('nsl_session_name', $this->sessionName);
  23. }
  24. public function clear() {
  25. parent::clear();
  26. $this->destroy();
  27. }
  28. private function destroy() {
  29. $sessionID = $this->sessionId;
  30. if ($sessionID) {
  31. $this->setCookie($sessionID, time() - YEAR_IN_SECONDS, apply_filters('nsl_session_use_secure_cookie', false));
  32. add_action('shutdown', array(
  33. $this,
  34. 'destroySiteTransient'
  35. ));
  36. }
  37. }
  38. public function destroySiteTransient() {
  39. $sessionID = $this->sessionId;
  40. if ($sessionID) {
  41. delete_site_transient('nsl_' . $sessionID);
  42. }
  43. }
  44. protected function load($createSession = false) {
  45. static $isLoaded = false;
  46. if ($this->sessionId === null) {
  47. if (isset($_COOKIE[$this->sessionName])) {
  48. $this->sessionId = 'nsl_persistent_' . md5(SECURE_AUTH_KEY . $_COOKIE[$this->sessionName]);
  49. } else if ($createSession) {
  50. $unique = uniqid('nsl', true);
  51. $this->setCookie($unique, apply_filters('nsl_session_cookie_expiration', 0), apply_filters('nsl_session_use_secure_cookie', false));
  52. $this->sessionId = 'nsl_persistent_' . md5(SECURE_AUTH_KEY . $unique);
  53. $isLoaded = true;
  54. }
  55. }
  56. if (!$isLoaded) {
  57. if ($this->sessionId !== null) {
  58. $data = maybe_unserialize(get_site_transient($this->sessionId));
  59. if (is_array($data)) {
  60. $this->data = $data;
  61. }
  62. $isLoaded = true;
  63. }
  64. }
  65. }
  66. private function setCookie($value, $expire, $secure = false) {
  67. setcookie($this->sessionName, $value, $expire, COOKIEPATH ? COOKIEPATH : '/', COOKIE_DOMAIN, $secure);
  68. }
  69. }