3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Core_Session.
31 class CRM_Core_Session
{
34 * Cache of all the session names that we manage.
36 static $_managedNames = NULL;
39 * Key is used to allow the application to have multiple top
40 * level scopes rather than a single scope. (avoids naming
41 * conflicts). We also extend this idea further and have local
42 * scopes within a global scope. Allows us to do cool things
43 * like resetting a specific area of the session code while
44 * keeping the rest intact
48 protected $_key = 'CiviCRM';
49 const USER_CONTEXT
= 'userContext';
52 * This is just a reference to the real session. Allows us to
53 * debug this class a wee bit easier
57 protected $_session = NULL;
60 * We only need one instance of this object. So we use the singleton
61 * pattern and cache the instance in this variable
65 static private $_singleton = NULL;
70 * The CMS takes care of initiating the php session handler session_start().
72 * When using CiviCRM standalone (w/o a CMS), we start the session
73 * in index.php and then pass it off to here.
75 * All crm code should always use the session using
76 * CRM_Core_Session. we prefix stuff to avoid collisions with the CMS and also
77 * collisions with other crm modules!
79 * This constructor is invoked whenever any module requests an instance of
80 * the session and one is not available.
82 * @return CRM_Core_Session
84 public function __construct() {
85 $this->_session
= NULL;
89 * Singleton function used to manage this object.
91 * @return CRM_Core_Session
93 public static function &singleton() {
94 if (self
::$_singleton === NULL) {
95 self
::$_singleton = new CRM_Core_Session();
97 return self
::$_singleton;
101 * Creates an array in the session.
103 * All variables now will be stored under this array.
105 * @param bool $isRead
106 * Is this a read operation, in this case, the session will not be touched.
108 public function initialize($isRead = FALSE) {
109 // lets initialize the _session variable just before we need it
110 // hopefully any bootstrapping code will actually load the session from the CMS
111 if (!isset($this->_session
)) {
113 if (!isset($_SESSION) && PHP_SAPI
!== 'cli') {
117 // FIXME: This belongs in CRM_Utils_System_*
118 if (CRM_Core_Config
::singleton()->userSystem
->is_drupal
&& function_exists('drupal_session_start')) {
119 // https://issues.civicrm.org/jira/browse/CRM-14356
120 if (!(isset($GLOBALS['lazy_session']) && $GLOBALS['lazy_session'] == TRUE)) {
121 drupal_session_start();
129 $this->_session
=& $_SESSION;
136 if (!isset($this->_session
[$this->_key
]) ||
137 !is_array($this->_session
[$this->_key
])
139 $this->_session
[$this->_key
] = array();
144 * Resets the session store.
148 public function reset($all = 1) {
152 // to make certain we clear it, first initialize it to empty
153 $this->_session
[$this->_key
] = array();
154 unset($this->_session
[$this->_key
]);
157 $this->_session
= array();
163 * Creates a session local scope.
165 * @param string $prefix
167 * @param bool $isRead
168 * Is this a read operation, in this case, the session will not be touched.
170 public function createScope($prefix, $isRead = FALSE) {
171 $this->initialize($isRead);
173 if ($isRead ||
empty($prefix)) {
177 if (empty($this->_session
[$this->_key
][$prefix])) {
178 $this->_session
[$this->_key
][$prefix] = array();
183 * Resets the session local scope.
185 * @param string $prefix
188 public function resetScope($prefix) {
191 if (empty($prefix)) {
195 if (array_key_exists($prefix, $this->_session
[$this->_key
])) {
196 unset($this->_session
[$this->_key
][$prefix]);
201 * Store the variable with the value in the session scope.
203 * This function takes a name, value pair and stores this
204 * in the session scope. Not sure what happens if we try
205 * to store complex objects in the session. I suspect it
206 * is supported but we need to verify this
209 * @param string $name
210 * Name of the variable.
211 * @param mixed $value
212 * Value of the variable.
213 * @param string $prefix
214 * A string to prefix the keys in the session with.
216 public function set($name, $value = NULL, $prefix = NULL) {
217 // create session scope
218 $this->createScope($prefix);
220 if (empty($prefix)) {
221 $session = &$this->_session
[$this->_key
];
224 $session = &$this->_session
[$this->_key
][$prefix];
227 if (is_array($name)) {
228 foreach ($name as $n => $v) {
233 $session[$name] = $value;
238 * Gets the value of the named variable in the session scope.
240 * This function takes a name and retrieves the value of this
241 * variable from the session scope.
244 * @param string $name
245 * name of the variable.
246 * @param string $prefix
247 * adds another level of scope to the session.
251 public function get($name, $prefix = NULL) {
252 // create session scope
253 $this->createScope($prefix, TRUE);
255 if (empty($this->_session
) ||
empty($this->_session
[$this->_key
])) {
259 if (empty($prefix)) {
260 $session =& $this->_session
[$this->_key
];
263 if (empty($this->_session
[$this->_key
][$prefix])) {
266 $session =& $this->_session
[$this->_key
][$prefix];
269 return CRM_Utils_Array
::value($name, $session);
273 * Gets all the variables in the current session scope and stuffs them in an associate array.
276 * Associative array to store name/value pairs.
277 * @param string $prefix
278 * Will be stripped from the key before putting it in the return.
280 public function getVars(&$vars, $prefix = '') {
281 // create session scope
282 $this->createScope($prefix, TRUE);
284 if (empty($prefix)) {
285 $values = &$this->_session
[$this->_key
];
288 $values = Civi
::cache('session')->get("CiviCRM_{$prefix}");
292 foreach ($values as $name => $value) {
293 $vars[$name] = $value;
299 * Set and check a timer.
301 * If it's expired, it will be set again.
303 * Good for showing a message to the user every hour or day (so not bugging them on every page)
304 * Returns true-ish values if the timer is not set or expired, and false if the timer is still running
305 * 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
308 * @param string $name
311 * expiry time (in seconds).
315 public function timer($name, $expire) {
316 $ts = $this->get($name, 'timer');
317 if (!$ts ||
$ts < time() - $expire) {
318 $this->set($name, time(), 'timer');
319 return $ts ?
$ts : 'not set';
325 * Adds a userContext to the stack.
327 * @param string $userContext
328 * The url to return to when done.
330 * Should we do a dupe checking with the top element.
332 public function pushUserContext($userContext, $check = TRUE) {
333 if (empty($userContext)) {
337 $this->createScope(self
::USER_CONTEXT
);
339 // hack, reset if too big
340 if (count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) > 10) {
341 $this->resetScope(self
::USER_CONTEXT
);
342 $this->createScope(self
::USER_CONTEXT
);
345 $topUC = array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
347 // see if there is a match between the new UC and the top one. the match needs to be
348 // fuzzy since we use the referer at times
349 // if close enough, lets just replace the top with the new one
350 if ($check && $topUC && CRM_Utils_String
::match($topUC, $userContext)) {
351 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
355 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $topUC);
357 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
362 * Replace the userContext of the stack with the passed one.
364 * @param string $userContext
365 * The url to return to when done.
367 public function replaceUserContext($userContext) {
368 if (empty($userContext)) {
372 $this->createScope(self
::USER_CONTEXT
);
374 array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
375 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
379 * Pops the top userContext stack.
382 * the top of the userContext stack (also pops the top element)
384 public function popUserContext() {
385 $this->createScope(self
::USER_CONTEXT
);
387 return array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
391 * Reads the top userContext stack.
394 * the top of the userContext stack
396 public function readUserContext() {
397 $this->createScope(self
::USER_CONTEXT
);
399 $config = CRM_Core_Config
::singleton();
400 $lastElement = count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) - 1;
401 return $lastElement >= 0 ?
$this->_session
[$this->_key
][self
::USER_CONTEXT
][$lastElement] : $config->userFrameworkBaseURL
;
405 * Dumps the session to the log.
409 public function debug($all = 1) {
412 CRM_Core_Error
::debug('CRM Session', $this->_session
);
415 CRM_Core_Error
::debug('CRM Session', $this->_session
[$this->_key
]);
420 * Fetches status messages.
423 * Should we reset the status variable?.
426 * the status message if any
428 public function getStatus($reset = FALSE) {
432 if (array_key_exists('status', $this->_session
[$this->_key
])) {
433 $status = $this->_session
[$this->_key
]['status'];
436 $this->_session
[$this->_key
]['status'] = NULL;
437 unset($this->_session
[$this->_key
]['status']);
443 * Stores an alert to be displayed to the user via crm-messages.
445 * @param string $text
448 * @param string $title
449 * The optional title of this message
451 * @param string $type
452 * The type of this message (printed as a css class). Possible options:
453 * - 'alert' (default)
456 * - 'error' (this message type by default will remain on the screen
457 * until the user dismisses it)
458 * - 'no-popup' (will display in the document like old-school)
460 * @param array $options
461 * Additional options. Possible values:
462 * - 'unique' (default: true) Check if this message was already set before adding
463 * - 'expires' how long to display this message before fadeout (in ms)
464 * set to 0 for no expiration
465 * defaults to 10 seconds for most messages, 5 if it has a title but no body,
466 * or 0 for errors or messages containing links
468 public static function setStatus($text, $title = '', $type = 'alert', $options = array()) {
469 // make sure session is initialized, CRM-8120
470 $session = self
::singleton();
471 $session->initialize();
473 // Sanitize any HTML we're displaying. This helps prevent reflected XSS in error messages.
474 $text = CRM_Utils_String
::purifyHTML($text);
475 $title = CRM_Utils_String
::purifyHTML($title);
478 $options +
= array('unique' => TRUE);
480 if (!isset(self
::$_singleton->_session
[self
::$_singleton->_key
]['status'])) {
481 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] = array();
483 if ($text ||
$title) {
484 if ($options['unique']) {
485 foreach (self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] as $msg) {
486 if ($msg['text'] == $text && $msg['title'] == $title) {
491 unset($options['unique']);
492 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'][] = array(
496 'options' => $options ?
$options : NULL,
502 * Register and retrieve session objects.
504 * @param string|array $names
506 public static function registerAndRetrieveSessionObjects($names) {
507 if (!is_array($names)) {
508 $names = array($names);
511 if (!self
::$_managedNames) {
512 self
::$_managedNames = $names;
515 self
::$_managedNames = array_merge(self
::$_managedNames, $names);
518 CRM_Core_BAO_Cache
::restoreSessionFromCache($names);
522 * Store session objects.
526 public static function storeSessionObjects($reset = TRUE) {
527 if (empty(self
::$_managedNames)) {
531 self
::$_managedNames = CRM_Utils_Array
::crmArrayUnique(self
::$_managedNames);
533 CRM_Core_BAO_Cache
::storeSessionToCache(self
::$_managedNames, $reset);
535 self
::$_managedNames = NULL;
539 * Retrieve contact id of the logged in user.
542 * contact ID of logged in user
544 public static function getLoggedInContactID() {
545 $session = CRM_Core_Session
::singleton();
546 if (!is_numeric($session->get('userID'))) {
549 return $session->get('userID');
553 * Get display name of the logged in user.
557 * @throws CiviCRM_API3_Exception
559 public function getLoggedInContactDisplayName() {
560 $userContactID = CRM_Core_Session
::getLoggedInContactID();
561 if (!$userContactID) {
564 return civicrm_api3('Contact', 'getvalue', array('id' => $userContactID, 'return' => 'display_name'));
568 * Check if session is empty.
570 * if so we don't cache stuff that we can get away with, helps proxies like varnish.
574 public function isEmpty() {
575 return empty($_SESSION);