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 // FIXME: This belongs in CRM_Utils_System_*
112 if (CRM_Core_Config
::singleton()->userSystem
->is_drupal
&& function_exists('drupal_session_start')) {
113 // https://issues.civicrm.org/jira/browse/CRM-14356
114 if (!(isset($GLOBALS['lazy_session']) && $GLOBALS['lazy_session'] == TRUE)) {
115 drupal_session_start();
123 $this->_session
=& $_SESSION;
130 if (!isset($this->_session
[$this->_key
]) ||
131 !is_array($this->_session
[$this->_key
])
133 $this->_session
[$this->_key
] = [];
138 * Resets the session store.
142 public function reset($all = 1) {
146 // to make certain we clear it, first initialize it to empty
147 $this->_session
[$this->_key
] = [];
148 unset($this->_session
[$this->_key
]);
151 $this->_session
= [];
157 * Creates a session local scope.
159 * @param string $prefix
161 * @param bool $isRead
162 * Is this a read operation, in this case, the session will not be touched.
164 public function createScope($prefix, $isRead = FALSE) {
165 $this->initialize($isRead);
167 if ($isRead ||
empty($prefix)) {
171 if (empty($this->_session
[$this->_key
][$prefix])) {
172 $this->_session
[$this->_key
][$prefix] = [];
177 * Resets the session local scope.
179 * @param string $prefix
182 public function resetScope($prefix) {
185 if (empty($prefix)) {
189 if (array_key_exists($prefix, $this->_session
[$this->_key
])) {
190 unset($this->_session
[$this->_key
][$prefix]);
195 * Store the variable with the value in the session scope.
197 * This function takes a name, value pair and stores this
198 * in the session scope. Not sure what happens if we try
199 * to store complex objects in the session. I suspect it
200 * is supported but we need to verify this
203 * @param string $name
204 * Name of the variable.
205 * @param mixed $value
206 * Value of the variable.
207 * @param string $prefix
208 * A string to prefix the keys in the session with.
210 public function set($name, $value = NULL, $prefix = NULL) {
211 // create session scope
212 $this->createScope($prefix);
214 if (empty($prefix)) {
215 $session = &$this->_session
[$this->_key
];
218 $session = &$this->_session
[$this->_key
][$prefix];
221 if (is_array($name)) {
222 foreach ($name as $n => $v) {
227 $session[$name] = $value;
232 * Gets the value of the named variable in the session scope.
234 * This function takes a name and retrieves the value of this
235 * variable from the session scope.
238 * @param string $name
239 * name of the variable.
240 * @param string $prefix
241 * adds another level of scope to the session.
245 public function get($name, $prefix = NULL) {
246 // create session scope
247 $this->createScope($prefix, TRUE);
249 if (empty($this->_session
) ||
empty($this->_session
[$this->_key
])) {
253 if (empty($prefix)) {
254 $session =& $this->_session
[$this->_key
];
257 if (empty($this->_session
[$this->_key
][$prefix])) {
260 $session =& $this->_session
[$this->_key
][$prefix];
263 return CRM_Utils_Array
::value($name, $session);
267 * Gets all the variables in the current session scope and stuffs them in an associate array.
270 * Associative array to store name/value pairs.
271 * @param string $prefix
272 * Will be stripped from the key before putting it in the return.
274 public function getVars(&$vars, $prefix = '') {
275 // create session scope
276 $this->createScope($prefix, TRUE);
278 if (empty($prefix)) {
279 $values = &$this->_session
[$this->_key
];
282 $values = Civi
::cache('session')->get("CiviCRM_{$prefix}");
286 foreach ($values as $name => $value) {
287 $vars[$name] = $value;
293 * Set and check a timer.
295 * If it's expired, it will be set again.
297 * Good for showing a message to the user every hour or day (so not bugging them on every page)
298 * Returns true-ish values if the timer is not set or expired, and false if the timer is still running
299 * 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
302 * @param string $name
305 * expiry time (in seconds).
309 public function timer($name, $expire) {
310 $ts = $this->get($name, 'timer');
311 if (!$ts ||
$ts < time() - $expire) {
312 $this->set($name, time(), 'timer');
313 return $ts ?
$ts : 'not set';
319 * Adds a userContext to the stack.
321 * @param string $userContext
322 * The url to return to when done.
324 * Should we do a dupe checking with the top element.
326 public function pushUserContext($userContext, $check = TRUE) {
327 if (empty($userContext)) {
331 $this->createScope(self
::USER_CONTEXT
);
333 // hack, reset if too big
334 if (count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) > 10) {
335 $this->resetScope(self
::USER_CONTEXT
);
336 $this->createScope(self
::USER_CONTEXT
);
339 $topUC = array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
341 // see if there is a match between the new UC and the top one. the match needs to be
342 // fuzzy since we use the referer at times
343 // if close enough, lets just replace the top with the new one
344 if ($check && $topUC && CRM_Utils_String
::match($topUC, $userContext)) {
345 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
349 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $topUC);
351 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
356 * Replace the userContext of the stack with the passed one.
358 * @param string $userContext
359 * The url to return to when done.
361 public function replaceUserContext($userContext) {
362 if (empty($userContext)) {
366 $this->createScope(self
::USER_CONTEXT
);
368 array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
369 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
373 * Pops the top userContext stack.
376 * the top of the userContext stack (also pops the top element)
378 public function popUserContext() {
379 $this->createScope(self
::USER_CONTEXT
);
381 return array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
385 * Reads the top userContext stack.
388 * the top of the userContext stack
390 public function readUserContext() {
391 $this->createScope(self
::USER_CONTEXT
);
393 $config = CRM_Core_Config
::singleton();
394 $lastElement = count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) - 1;
395 return $lastElement >= 0 ?
$this->_session
[$this->_key
][self
::USER_CONTEXT
][$lastElement] : $config->userFrameworkBaseURL
;
399 * Dumps the session to the log.
403 public function debug($all = 1) {
406 CRM_Core_Error
::debug('CRM Session', $this->_session
);
409 CRM_Core_Error
::debug('CRM Session', $this->_session
[$this->_key
]);
414 * Fetches status messages.
417 * Should we reset the status variable?.
420 * the status message if any
422 public function getStatus($reset = FALSE) {
426 if (array_key_exists('status', $this->_session
[$this->_key
])) {
427 $status = $this->_session
[$this->_key
]['status'];
430 $this->_session
[$this->_key
]['status'] = NULL;
431 unset($this->_session
[$this->_key
]['status']);
437 * Stores an alert to be displayed to the user via crm-messages.
439 * @param string $text
442 * @param string $title
443 * The optional title of this message
445 * @param string $type
446 * The type of this message (printed as a css class). Possible options:
447 * - 'alert' (default)
450 * - 'error' (this message type by default will remain on the screen
451 * until the user dismisses it)
452 * - 'no-popup' (will display in the document like old-school)
454 * @param array $options
455 * Additional options. Possible values:
456 * - 'unique' (default: true) Check if this message was already set before adding
457 * - 'expires' how long to display this message before fadeout (in ms)
458 * set to 0 for no expiration
459 * defaults to 10 seconds for most messages, 5 if it has a title but no body,
460 * or 0 for errors or messages containing links
462 public static function setStatus($text, $title = '', $type = 'alert', $options = []) {
463 // make sure session is initialized, CRM-8120
464 $session = self
::singleton();
465 $session->initialize();
467 // Sanitize any HTML we're displaying. This helps prevent reflected XSS in error messages.
468 $text = CRM_Utils_String
::purifyHTML($text);
469 $title = CRM_Utils_String
::purifyHTML($title);
472 $options +
= ['unique' => TRUE];
474 if (!isset(self
::$_singleton->_session
[self
::$_singleton->_key
]['status'])) {
475 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] = [];
477 if ($text ||
$title) {
478 if ($options['unique']) {
479 foreach (self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] as $msg) {
480 if ($msg['text'] == $text && $msg['title'] == $title) {
485 unset($options['unique']);
486 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'][] = [
490 'options' => $options ?
$options : NULL,
496 * Register and retrieve session objects.
498 * @param string|array $names
500 public static function registerAndRetrieveSessionObjects($names) {
501 if (!is_array($names)) {
505 if (!self
::$_managedNames) {
506 self
::$_managedNames = $names;
509 self
::$_managedNames = array_merge(self
::$_managedNames, $names);
512 CRM_Core_BAO_Cache
::restoreSessionFromCache($names);
516 * Store session objects.
520 public static function storeSessionObjects($reset = TRUE) {
521 if (empty(self
::$_managedNames)) {
525 self
::$_managedNames = CRM_Utils_Array
::crmArrayUnique(self
::$_managedNames);
527 CRM_Core_BAO_Cache
::storeSessionToCache(self
::$_managedNames, $reset);
529 self
::$_managedNames = NULL;
533 * Retrieve contact id of the logged in user.
536 * contact ID of logged in user
538 public static function getLoggedInContactID() {
539 $session = CRM_Core_Session
::singleton();
540 if (!is_numeric($session->get('userID'))) {
543 return $session->get('userID');
547 * Get display name of the logged in user.
551 * @throws CiviCRM_API3_Exception
553 public function getLoggedInContactDisplayName() {
554 $userContactID = CRM_Core_Session
::getLoggedInContactID();
555 if (!$userContactID) {
558 return civicrm_api3('Contact', 'getvalue', ['id' => $userContactID, 'return' => 'display_name']);
562 * Check if session is empty.
564 * if so we don't cache stuff that we can get away with, helps proxies like varnish.
568 public function isEmpty() {
569 return empty($_SESSION);