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
57 static private $_singleton = NULL;
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 * Creates an array in the session.
92 * All variables now will be stored under this array.
95 * Is this a read operation, in this case, the session will not be touched.
97 public function initialize($isRead = FALSE) {
98 // remove $_SESSION reference if session is changed
99 if (($sid = session_id()) !== $this->sessionID
) {
100 $this->_session
= NULL;
101 $this->sessionID
= $sid;
103 // lets initialize the _session variable just before we need it
104 // hopefully any bootstrapping code will actually load the session from the CMS
105 if (!isset($this->_session
)) {
107 if (!isset($_SESSION) && PHP_SAPI
!== 'cli') {
111 CRM_Core_Config
::singleton()->userSystem
->sessionStart();
113 $this->_session
=& $_SESSION;
120 if (!isset($this->_session
[$this->_key
]) ||
121 !is_array($this->_session
[$this->_key
])
123 $this->_session
[$this->_key
] = [];
128 * Resets the session store.
132 public function reset($all = 1) {
136 // to make certain we clear it, first initialize it to empty
137 $this->_session
[$this->_key
] = [];
138 unset($this->_session
[$this->_key
]);
141 $this->_session
= [];
147 * Creates a session local scope.
149 * @param string $prefix
151 * @param bool $isRead
152 * Is this a read operation, in this case, the session will not be touched.
154 public function createScope($prefix, $isRead = FALSE) {
155 $this->initialize($isRead);
157 if ($isRead ||
empty($prefix)) {
161 if (empty($this->_session
[$this->_key
][$prefix])) {
162 $this->_session
[$this->_key
][$prefix] = [];
167 * Resets the session local scope.
169 * @param string $prefix
172 public function resetScope($prefix) {
175 if (empty($prefix)) {
179 if (array_key_exists($prefix, $this->_session
[$this->_key
])) {
180 unset($this->_session
[$this->_key
][$prefix]);
185 * Store the variable with the value in the session scope.
187 * This function takes a name, value pair and stores this
188 * in the session scope. Not sure what happens if we try
189 * to store complex objects in the session. I suspect it
190 * is supported but we need to verify this
193 * @param string $name
194 * Name of the variable.
195 * @param mixed $value
196 * Value of the variable.
197 * @param string $prefix
198 * A string to prefix the keys in the session with.
200 public function set($name, $value = NULL, $prefix = NULL) {
201 // create session scope
202 $this->createScope($prefix);
204 if (empty($prefix)) {
205 $session = &$this->_session
[$this->_key
];
208 $session = &$this->_session
[$this->_key
][$prefix];
211 if (is_array($name)) {
212 foreach ($name as $n => $v) {
217 $session[$name] = $value;
222 * Gets the value of the named variable in the session scope.
224 * This function takes a name and retrieves the value of this
225 * variable from the session scope.
228 * @param string $name
229 * name of the variable.
230 * @param string $prefix
231 * adds another level of scope to the session.
235 public function get($name, $prefix = NULL) {
236 // create session scope
237 $this->createScope($prefix, TRUE);
239 if (empty($this->_session
) ||
empty($this->_session
[$this->_key
])) {
243 if (empty($prefix)) {
244 $session =& $this->_session
[$this->_key
];
247 if (empty($this->_session
[$this->_key
][$prefix])) {
250 $session =& $this->_session
[$this->_key
][$prefix];
253 return CRM_Utils_Array
::value($name, $session);
257 * Gets all the variables in the current session scope and stuffs them in an associate array.
260 * Associative array to store name/value pairs.
261 * @param string $prefix
262 * Will be stripped from the key before putting it in the return.
264 public function getVars(&$vars, $prefix = '') {
265 // create session scope
266 $this->createScope($prefix, TRUE);
268 if (empty($prefix)) {
269 $values = &$this->_session
[$this->_key
];
272 $values = Civi
::cache('session')->get("CiviCRM_{$prefix}");
276 foreach ($values as $name => $value) {
277 $vars[$name] = $value;
283 * Set and check a timer.
285 * If it's expired, it will be set again.
287 * Good for showing a message to the user every hour or day (so not bugging them on every page)
288 * Returns true-ish values if the timer is not set or expired, and false if the timer is still running
289 * 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
292 * @param string $name
295 * expiry time (in seconds).
299 public function timer($name, $expire) {
300 $ts = $this->get($name, 'timer');
301 if (!$ts ||
$ts < time() - $expire) {
302 $this->set($name, time(), 'timer');
303 return $ts ?
$ts : 'not set';
309 * Adds a userContext to the stack.
311 * @param string $userContext
312 * The url to return to when done.
314 * Should we do a dupe checking with the top element.
316 public function pushUserContext($userContext, $check = TRUE) {
317 if (empty($userContext)) {
321 $this->createScope(self
::USER_CONTEXT
);
323 // hack, reset if too big
324 if (count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) > 10) {
325 $this->resetScope(self
::USER_CONTEXT
);
326 $this->createScope(self
::USER_CONTEXT
);
329 $topUC = array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
331 // see if there is a match between the new UC and the top one. the match needs to be
332 // fuzzy since we use the referer at times
333 // if close enough, lets just replace the top with the new one
334 if ($check && $topUC && CRM_Utils_String
::match($topUC, $userContext)) {
335 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
339 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $topUC);
341 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
346 * Replace the userContext of the stack with the passed one.
348 * @param string $userContext
349 * The url to return to when done.
351 public function replaceUserContext($userContext) {
352 if (empty($userContext)) {
356 $this->createScope(self
::USER_CONTEXT
);
358 array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
359 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
363 * Pops the top userContext stack.
366 * the top of the userContext stack (also pops the top element)
368 public function popUserContext() {
369 $this->createScope(self
::USER_CONTEXT
);
371 return array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
375 * Reads the top userContext stack.
378 * the top of the userContext stack
380 public function readUserContext() {
381 $this->createScope(self
::USER_CONTEXT
);
383 $config = CRM_Core_Config
::singleton();
384 $lastElement = count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) - 1;
385 return $lastElement >= 0 ?
$this->_session
[$this->_key
][self
::USER_CONTEXT
][$lastElement] : $config->userFrameworkBaseURL
;
389 * Dumps the session to the log.
393 public function debug($all = 1) {
396 CRM_Core_Error
::debug('CRM Session', $this->_session
);
399 CRM_Core_Error
::debug('CRM Session', $this->_session
[$this->_key
]);
404 * Fetches status messages.
407 * Should we reset the status variable?.
410 * the status message if any
412 public function getStatus($reset = FALSE) {
416 if (array_key_exists('status', $this->_session
[$this->_key
])) {
417 $status = $this->_session
[$this->_key
]['status'];
420 $this->_session
[$this->_key
]['status'] = NULL;
421 unset($this->_session
[$this->_key
]['status']);
427 * Stores an alert to be displayed to the user via crm-messages.
429 * @param string $text
432 * @param string $title
433 * The optional title of this message
435 * @param string $type
436 * The type of this message (printed as a css class). Possible options:
437 * - 'alert' (default)
440 * - 'error' (this message type by default will remain on the screen
441 * until the user dismisses it)
442 * - 'no-popup' (will display in the document like old-school)
444 * @param array $options
445 * Additional options. Possible values:
446 * - 'unique' (default: true) Check if this message was already set before adding
447 * - 'expires' how long to display this message before fadeout (in ms)
448 * set to 0 for no expiration
449 * defaults to 10 seconds for most messages, 5 if it has a title but no body,
450 * or 0 for errors or messages containing links
452 public static function setStatus($text, $title = '', $type = 'alert', $options = []) {
453 // make sure session is initialized, CRM-8120
454 $session = self
::singleton();
455 $session->initialize();
457 // Sanitize any HTML we're displaying. This helps prevent reflected XSS in error messages.
458 $text = CRM_Utils_String
::purifyHTML($text);
459 $title = CRM_Utils_String
::purifyHTML($title);
462 $options +
= ['unique' => TRUE];
464 if (!isset(self
::$_singleton->_session
[self
::$_singleton->_key
]['status'])) {
465 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] = [];
467 if ($text ||
$title) {
468 if ($options['unique']) {
469 foreach (self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] as $msg) {
470 if ($msg['text'] == $text && $msg['title'] == $title) {
475 unset($options['unique']);
476 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'][] = [
480 'options' => $options ?
$options : NULL,
486 * Register and retrieve session objects.
488 * @param string|array $names
490 public static function registerAndRetrieveSessionObjects($names) {
491 if (!is_array($names)) {
495 if (!self
::$_managedNames) {
496 self
::$_managedNames = $names;
499 self
::$_managedNames = array_merge(self
::$_managedNames, $names);
502 CRM_Core_BAO_Cache
::restoreSessionFromCache($names);
506 * Store session objects.
510 public static function storeSessionObjects($reset = TRUE) {
511 if (empty(self
::$_managedNames)) {
515 self
::$_managedNames = CRM_Utils_Array
::crmArrayUnique(self
::$_managedNames);
517 CRM_Core_BAO_Cache
::storeSessionToCache(self
::$_managedNames, $reset);
519 self
::$_managedNames = NULL;
523 * Retrieve contact id of the logged in user.
526 * contact ID of logged in user
528 public static function getLoggedInContactID() {
529 $session = CRM_Core_Session
::singleton();
530 if (!is_numeric($session->get('userID'))) {
533 return $session->get('userID');
537 * Get display name of the logged in user.
541 * @throws CiviCRM_API3_Exception
543 public function getLoggedInContactDisplayName() {
544 $userContactID = CRM_Core_Session
::getLoggedInContactID();
545 if (!$userContactID) {
548 return civicrm_api3('Contact', 'getvalue', ['id' => $userContactID, 'return' => 'display_name']);
552 * Check if session is empty.
554 * if so we don't cache stuff that we can get away with, helps proxies like varnish.
558 public function isEmpty() {
559 return empty($_SESSION);