| 1 |
<?php |
| 2 |
/* |
| 3 |
* This file is part of the ManageWP Worker plugin. |
| 4 |
* |
| 5 |
* (c) ManageWP LLC <contact@managewp.com> |
| 6 |
* |
| 7 |
* For the full copyright and license information, please view the LICENSE |
| 8 |
* file that was distributed with this source code. |
| 9 |
*/ |
| 10 |
|
| 11 |
class MWP_WordPress_SessionStore |
| 12 |
{ |
| 13 |
|
| 14 |
private $context; |
| 15 |
|
| 16 |
private $sessionsKey = 'mwp_sessions'; |
| 17 |
|
| 18 |
public function __construct(MWP_WordPress_Context $context) |
| 19 |
{ |
| 20 |
$this->context = $context; |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* @param int $userId |
| 25 |
* @param string $token |
| 26 |
*/ |
| 27 |
public function add($userId, $token) |
| 28 |
{ |
| 29 |
$sessions = $this->getSessions(); |
| 30 |
$sessions[(int) $userId][] = (string) $token; |
| 31 |
|
| 32 |
$this->saveSessions($sessions); |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* @return int Number of destroyed sessions. |
| 37 |
*/ |
| 38 |
public function destroyAll() |
| 39 |
{ |
| 40 |
if (!$this->context->isVersionAtLeast('4.0.0')) { |
| 41 |
// Not supported before WordPress 4.0.0. |
| 42 |
return -1; |
| 43 |
} |
| 44 |
|
| 45 |
$removed = 0; |
| 46 |
foreach ($this->getSessions() as $userId => $tokens) { |
| 47 |
$sessionTokens = $this->context->getSessionTokens($userId); |
| 48 |
foreach ($tokens as $token) { |
| 49 |
$sessionTokens->destroy($token); |
| 50 |
$removed++; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
$this->saveSessions(array()); |
| 55 |
|
| 56 |
return $removed; |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* Returns array of arrays of session IDs, indexed by user ID. |
| 61 |
* |
| 62 |
* @example |
| 63 |
* - |
| 64 |
* user_id_1: |
| 65 |
* - token_id_1 |
| 66 |
* - token_id_2 |
| 67 |
* user_id_2: |
| 68 |
* - token_id_3 |
| 69 |
* - token_id_4 |
| 70 |
* - token_id_5 |
| 71 |
* ... |
| 72 |
* |
| 73 |
* @return array[] |
| 74 |
*/ |
| 75 |
private function getSessions() |
| 76 |
{ |
| 77 |
$sessions = $this->context->transientGet($this->sessionsKey); |
| 78 |
|
| 79 |
return $sessions ? $sessions : array(); |
| 80 |
} |
| 81 |
|
| 82 |
private function saveSessions($sessions) |
| 83 |
{ |
| 84 |
$this->context->transientSet($this->sessionsKey, $sessions); |
| 85 |
} |
| 86 |
} |
| 87 |
|