3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Class CRM_Core_Session.
15 class CRM_Core_Session
{
18 * Cache of all the session names that we manage.
21 public static $_managedNames = NULL;
24 * Key is used to allow the application to have multiple top
25 * level scopes rather than a single scope. (avoids naming
26 * conflicts). We also extend this idea further and have local
27 * scopes within a global scope. Allows us to do cool things
28 * like resetting a specific area of the session code while
29 * keeping the rest intact
33 protected $_key = 'CiviCRM';
34 const USER_CONTEXT
= 'userContext';
37 * This is just a reference to the real session. Allows us to
38 * debug this class a wee bit easier
42 protected $_session = NULL;
45 * Current php Session ID : needed to detect if the session is changed
52 * We only need one instance of this object. So we use the singleton
53 * pattern and cache the instance in this variable
55 * @var \CRM_Core_Session
57 static private $_singleton;
62 * The CMS takes care of initiating the php session handler session_start().
64 * All crm code should always use the session using
65 * CRM_Core_Session. we prefix stuff to avoid collisions with the CMS and also
66 * collisions with other crm modules!
68 * This constructor is invoked whenever any module requests an instance of
69 * the session and one is not available.
71 * @return CRM_Core_Session
73 public function __construct() {
74 $this->_session
= NULL;
78 * Singleton function used to manage this object.
80 * @return CRM_Core_Session
82 public static function &singleton() {
83 if (self
::$_singleton === NULL) {
84 self
::$_singleton = new CRM_Core_Session();
86 return self
::$_singleton;
90 * Replace the session object with a fake session.
92 public static function useFakeSession() {
93 self
::$_singleton = new class() extends CRM_Core_Session
{
95 public function initialize($isRead = FALSE) {
100 if (!isset($this->_session
)) {
101 $this->_session
= [];
104 if (!isset($this->_session
[$this->_key
]) ||
!is_array($this->_session
[$this->_key
])) {
105 $this->_session
[$this->_key
] = [];
109 public function isEmpty() {
110 return empty($this->_session
);
114 self
::$_singleton->_session
= NULL;
115 // This is not a revocable proposition. Should survive, even with things 'System.flush'.
116 if (!defined('_CIVICRM_FAKE_SESSION')) {
117 define('_CIVICRM_FAKE_SESSION', TRUE);
119 return self
::$_singleton;
123 * Creates an array in the session.
125 * All variables now will be stored under this array.
127 * @param bool $isRead
128 * Is this a read operation, in this case, the session will not be touched.
130 public function initialize($isRead = FALSE) {
131 // remove $_SESSION reference if session is changed
132 if (($sid = session_id()) !== $this->sessionID
) {
133 $this->_session
= NULL;
134 $this->sessionID
= $sid;
136 // lets initialize the _session variable just before we need it
137 // hopefully any bootstrapping code will actually load the session from the CMS
138 if (!isset($this->_session
)) {
140 if (!isset($_SESSION) && PHP_SAPI
!== 'cli') {
144 CRM_Core_Config
::singleton()->userSystem
->sessionStart();
146 $this->_session
=& $_SESSION;
153 if (!isset($this->_session
[$this->_key
]) ||
154 !is_array($this->_session
[$this->_key
])
156 $this->_session
[$this->_key
] = [];
161 * Resets the session store.
165 public function reset($all = 1) {
169 // to make certain we clear it, first initialize it to empty
170 $this->_session
[$this->_key
] = [];
171 unset($this->_session
[$this->_key
]);
174 $this->_session
= [];
180 * Creates a session local scope.
182 * @param string $prefix
184 * @param bool $isRead
185 * Is this a read operation, in this case, the session will not be touched.
187 public function createScope($prefix, $isRead = FALSE) {
188 $this->initialize($isRead);
190 if ($isRead ||
empty($prefix)) {
194 if (empty($this->_session
[$this->_key
][$prefix])) {
195 $this->_session
[$this->_key
][$prefix] = [];
200 * Resets the session local scope.
202 * @param string $prefix
205 public function resetScope($prefix) {
208 if (empty($prefix)) {
212 if (array_key_exists($prefix, $this->_session
[$this->_key
])) {
213 unset($this->_session
[$this->_key
][$prefix]);
218 * Store the variable with the value in the session scope.
220 * This function takes a name, value pair and stores this
221 * in the session scope. Not sure what happens if we try
222 * to store complex objects in the session. I suspect it
223 * is supported but we need to verify this
226 * @param string $name
227 * Name of the variable.
228 * @param mixed $value
229 * Value of the variable.
230 * @param string $prefix
231 * A string to prefix the keys in the session with.
233 public function set($name, $value = NULL, $prefix = NULL) {
234 // create session scope
235 $this->createScope($prefix);
237 if (empty($prefix)) {
238 $session = &$this->_session
[$this->_key
];
241 $session = &$this->_session
[$this->_key
][$prefix];
244 if (is_array($name)) {
245 foreach ($name as $n => $v) {
250 $session[$name] = $value;
255 * Gets the value of the named variable in the session scope.
257 * This function takes a name and retrieves the value of this
258 * variable from the session scope.
261 * @param string $name
262 * name of the variable.
263 * @param string $prefix
264 * adds another level of scope to the session.
268 public function get($name, $prefix = NULL) {
269 // create session scope
270 $this->createScope($prefix, TRUE);
272 if (empty($this->_session
) ||
empty($this->_session
[$this->_key
])) {
276 if (empty($prefix)) {
277 $session =& $this->_session
[$this->_key
];
280 if (empty($this->_session
[$this->_key
][$prefix])) {
283 $session =& $this->_session
[$this->_key
][$prefix];
286 return $session[$name] ??
NULL;
290 * Gets all the variables in the current session scope and stuffs them in an associate array.
293 * Associative array to store name/value pairs.
294 * @param string $prefix
295 * Will be stripped from the key before putting it in the return.
297 public function getVars(&$vars, $prefix = '') {
298 // create session scope
299 $this->createScope($prefix, TRUE);
301 if (empty($prefix)) {
302 $values = &$this->_session
[$this->_key
];
305 $values = Civi
::cache('session')->get("CiviCRM_{$prefix}");
309 foreach ($values as $name => $value) {
310 $vars[$name] = $value;
316 * Set and check a timer.
318 * If it's expired, it will be set again.
320 * Good for showing a message to the user every hour or day (so not bugging them on every page)
321 * Returns true-ish values if the timer is not set or expired, and false if the timer is still running
322 * If you want to get more nuanced, you can check the type of the return to see if it's 'not set' or actually expired at a certain time
325 * @param string $name
328 * expiry time (in seconds).
332 public function timer($name, $expire) {
333 $ts = $this->get($name, 'timer');
334 if (!$ts ||
$ts < time() - $expire) {
335 $this->set($name, time(), 'timer');
336 return $ts ?
$ts : 'not set';
342 * Adds a userContext to the stack.
344 * @param string $userContext
345 * The url to return to when done.
347 * Should we do a dupe checking with the top element.
349 public function pushUserContext($userContext, $check = TRUE) {
350 if (empty($userContext)) {
354 $this->createScope(self
::USER_CONTEXT
);
356 // hack, reset if too big
357 if (count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) > 10) {
358 $this->resetScope(self
::USER_CONTEXT
);
359 $this->createScope(self
::USER_CONTEXT
);
362 $topUC = array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
364 // see if there is a match between the new UC and the top one. the match needs to be
365 // fuzzy since we use the referer at times
366 // if close enough, lets just replace the top with the new one
367 if ($check && $topUC && CRM_Utils_String
::match($topUC, $userContext)) {
368 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
372 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $topUC);
374 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
379 * Replace the userContext of the stack with the passed one.
381 * @param string $userContext
382 * The url to return to when done.
384 public function replaceUserContext($userContext) {
385 if (empty($userContext)) {
389 $this->createScope(self
::USER_CONTEXT
);
391 array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
392 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
396 * Pops the top userContext stack.
399 * the top of the userContext stack (also pops the top element)
401 public function popUserContext() {
402 $this->createScope(self
::USER_CONTEXT
);
404 return array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
408 * Reads the top userContext stack.
411 * the top of the userContext stack
413 public function readUserContext() {
414 $this->createScope(self
::USER_CONTEXT
);
416 $config = CRM_Core_Config
::singleton();
417 $lastElement = count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) - 1;
418 return $lastElement >= 0 ?
$this->_session
[$this->_key
][self
::USER_CONTEXT
][$lastElement] : $config->userFrameworkBaseURL
;
422 * Dumps the session to the log.
426 public function debug($all = 1) {
429 CRM_Core_Error
::debug('CRM Session', $this->_session
);
432 CRM_Core_Error
::debug('CRM Session', $this->_session
[$this->_key
]);
437 * Fetches status messages.
440 * Should we reset the status variable?.
443 * the status message if any
445 public function getStatus($reset = FALSE) {
449 if (array_key_exists('status', $this->_session
[$this->_key
])) {
450 $status = $this->_session
[$this->_key
]['status'];
453 $this->_session
[$this->_key
]['status'] = NULL;
454 unset($this->_session
[$this->_key
]['status']);
460 * Stores an alert to be displayed to the user via crm-messages.
462 * @param string $text
465 * @param string $title
466 * The optional title of this message
468 * @param string $type
469 * The type of this message (printed as a css class). Possible options:
470 * - 'alert' (default)
473 * - 'error' (this message type by default will remain on the screen
474 * until the user dismisses it)
475 * - 'no-popup' (will display in the document like old-school)
477 * @param array $options
478 * Additional options. Possible values:
479 * - 'unique' (default: true) Check if this message was already set before adding
480 * - 'expires' how long to display this message before fadeout (in ms)
481 * set to 0 for no expiration
482 * defaults to 10 seconds for most messages, 5 if it has a title but no body,
483 * or 0 for errors or messages containing links
485 public static function setStatus($text, $title = '', $type = 'alert', $options = []) {
486 // make sure session is initialized, CRM-8120
487 $session = self
::singleton();
488 $session->initialize();
490 // Sanitize any HTML we're displaying. This helps prevent reflected XSS in error messages.
491 $text = CRM_Utils_String
::purifyHTML($text);
492 $title = CRM_Utils_String
::purifyHTML($title);
495 $options +
= ['unique' => TRUE];
497 if (!isset(self
::$_singleton->_session
[self
::$_singleton->_key
]['status'])) {
498 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] = [];
500 if ($text ||
$title) {
501 if ($options['unique']) {
502 foreach (self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] as $msg) {
503 if ($msg['text'] == $text && $msg['title'] == $title) {
508 unset($options['unique']);
509 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'][] = [
513 'options' => $options ?
$options : NULL,
519 * Register and retrieve session objects.
521 * @param string|array $names
523 public static function registerAndRetrieveSessionObjects($names) {
524 if (!is_array($names)) {
528 if (!self
::$_managedNames) {
529 self
::$_managedNames = $names;
532 self
::$_managedNames = array_merge(self
::$_managedNames, $names);
535 CRM_Core_BAO_Cache
::restoreSessionFromCache($names);
539 * Store session objects.
543 public static function storeSessionObjects($reset = TRUE) {
544 if (empty(self
::$_managedNames)) {
548 self
::$_managedNames = CRM_Utils_Array
::crmArrayUnique(self
::$_managedNames);
550 CRM_Core_BAO_Cache
::storeSessionToCache(self
::$_managedNames, $reset);
552 self
::$_managedNames = NULL;
556 * Retrieve contact id of the logged in user.
559 * contact ID of logged in user
561 public static function getLoggedInContactID() {
562 $session = CRM_Core_Session
::singleton();
563 if (!is_numeric($session->get('userID'))) {
566 return $session->get('userID');
570 * Get display name of the logged in user.
574 * @throws CiviCRM_API3_Exception
576 public function getLoggedInContactDisplayName() {
577 $userContactID = CRM_Core_Session
::getLoggedInContactID();
578 if (!$userContactID) {
581 return civicrm_api3('Contact', 'getvalue', ['id' => $userContactID, 'return' => 'display_name']);
585 * Check if session is empty.
587 * if so we don't cache stuff that we can get away with, helps proxies like varnish.
591 public function isEmpty() {
592 return empty($_SESSION);