Merge pull request #12379 from totten/master-psr16-sqlgroup
[civicrm-core.git] / CRM / Core / Session.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035 27
4c6ce474 28/**
8eedd10a 29 * Class CRM_Core_Session.
4c6ce474 30 */
6a488035
TO
31class CRM_Core_Session {
32
33 /**
f9e31d7f 34 * Cache of all the session names that we manage.
6a488035
TO
35 */
36 static $_managedNames = NULL;
37
38 /**
100fef9d 39 * Key is used to allow the application to have multiple top
6a488035
TO
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
45 *
46 * @var string
47 */
48 protected $_key = 'CiviCRM';
7da04cde 49 const USER_CONTEXT = 'userContext';
6a488035
TO
50
51 /**
52 * This is just a reference to the real session. Allows us to
53 * debug this class a wee bit easier
54 *
55 * @var object
56 */
57 protected $_session = NULL;
58
59 /**
60 * We only need one instance of this object. So we use the singleton
61 * pattern and cache the instance in this variable
62 *
63 * @var object
6a488035
TO
64 */
65 static private $_singleton = NULL;
66
67 /**
f9e31d7f 68 * Constructor.
6a488035 69 *
d4ad6ab3 70 * The CMS takes care of initiating the php session handler session_start().
6a488035 71 *
d4ad6ab3 72 * When using CiviCRM standalone (w/o a CMS), we start the session
6a488035
TO
73 * in index.php and then pass it off to here.
74 *
75 * All crm code should always use the session using
d4ad6ab3
CW
76 * CRM_Core_Session. we prefix stuff to avoid collisions with the CMS and also
77 * collisions with other crm modules!
78 *
6a488035
TO
79 * This constructor is invoked whenever any module requests an instance of
80 * the session and one is not available.
81 *
d4ad6ab3 82 * @return CRM_Core_Session
6a488035 83 */
00be9182 84 public function __construct() {
2aa397bc 85 $this->_session = NULL;
6a488035
TO
86 }
87
88 /**
f9e31d7f 89 * Singleton function used to manage this object.
6a488035 90 *
d46561f5 91 * @return CRM_Core_Session
6a488035 92 */
00be9182 93 public static function &singleton() {
6a488035 94 if (self::$_singleton === NULL) {
317fceb4 95 self::$_singleton = new CRM_Core_Session();
6a488035
TO
96 }
97 return self::$_singleton;
98 }
99
100 /**
8eedd10a 101 * Creates an array in the session.
102 *
103 * All variables now will be stored under this array.
6a488035 104 *
6a0b768e
TO
105 * @param bool $isRead
106 * Is this a read operation, in this case, the session will not be touched.
6a488035 107 */
00be9182 108 public function initialize($isRead = FALSE) {
6a488035
TO
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)) {
112 // CRM-9483
113 if (!isset($_SESSION) && PHP_SAPI !== 'cli') {
114 if ($isRead) {
115 return;
116 }
117 $config =& CRM_Core_Config::singleton();
d4ad6ab3 118 // FIXME: This belongs in CRM_Utils_System_*
6a488035 119 if ($config->userSystem->is_drupal && function_exists('drupal_session_start')) {
2c85a284 120 // https://issues.civicrm.org/jira/browse/CRM-14356
353ffa53 121 if (!(isset($GLOBALS['lazy_session']) && $GLOBALS['lazy_session'] == TRUE)) {
af730db2
TO
122 drupal_session_start();
123 }
124 $_SESSION = array();
6a488035
TO
125 }
126 else {
127 session_start();
128 }
129 }
130 $this->_session =& $_SESSION;
131 }
132
133 if ($isRead) {
134 return;
135 }
136
137 if (!isset($this->_session[$this->_key]) ||
138 !is_array($this->_session[$this->_key])
139 ) {
140 $this->_session[$this->_key] = array();
141 }
6a488035
TO
142 }
143
144 /**
f9e31d7f 145 * Resets the session store.
6a488035 146 *
dd244018 147 * @param int $all
6a488035 148 */
00be9182 149 public function reset($all = 1) {
6a488035
TO
150 if ($all != 1) {
151 $this->initialize();
152
153 // to make certain we clear it, first initialize it to empty
154 $this->_session[$this->_key] = array();
155 unset($this->_session[$this->_key]);
156 }
157 else {
158 $this->_session = array();
159 }
160
6a488035
TO
161 }
162
163 /**
f9e31d7f 164 * Creates a session local scope.
6a488035 165 *
6a0b768e
TO
166 * @param string $prefix
167 * Local scope name.
168 * @param bool $isRead
169 * Is this a read operation, in this case, the session will not be touched.
6a488035 170 */
00be9182 171 public function createScope($prefix, $isRead = FALSE) {
6a488035
TO
172 $this->initialize($isRead);
173
174 if ($isRead || empty($prefix)) {
175 return;
176 }
177
a7488080 178 if (empty($this->_session[$this->_key][$prefix])) {
6a488035
TO
179 $this->_session[$this->_key][$prefix] = array();
180 }
181 }
182
183 /**
f9e31d7f 184 * Resets the session local scope.
6a488035 185 *
6a0b768e
TO
186 * @param string $prefix
187 * Local scope name.
6a488035 188 */
00be9182 189 public function resetScope($prefix) {
6a488035
TO
190 $this->initialize();
191
192 if (empty($prefix)) {
193 return;
194 }
195
196 if (array_key_exists($prefix, $this->_session[$this->_key])) {
197 unset($this->_session[$this->_key][$prefix]);
198 }
199 }
200
201 /**
f9e31d7f 202 * Store the variable with the value in the session scope.
6a488035
TO
203 *
204 * This function takes a name, value pair and stores this
205 * in the session scope. Not sure what happens if we try
206 * to store complex objects in the session. I suspect it
207 * is supported but we need to verify this
208 *
6a488035 209 *
6a0b768e
TO
210 * @param string $name
211 * Name of the variable.
212 * @param mixed $value
213 * Value of the variable.
214 * @param string $prefix
215 * A string to prefix the keys in the session with.
6a488035 216 */
00be9182 217 public function set($name, $value = NULL, $prefix = NULL) {
6a488035
TO
218 // create session scope
219 $this->createScope($prefix);
220
221 if (empty($prefix)) {
222 $session = &$this->_session[$this->_key];
223 }
224 else {
225 $session = &$this->_session[$this->_key][$prefix];
226 }
227
228 if (is_array($name)) {
229 foreach ($name as $n => $v) {
230 $session[$n] = $v;
231 }
232 }
233 else {
234 $session[$name] = $value;
235 }
236 }
237
238 /**
f9e31d7f 239 * Gets the value of the named variable in the session scope.
6a488035
TO
240 *
241 * This function takes a name and retrieves the value of this
242 * variable from the session scope.
243 *
6a488035 244 *
6a0b768e 245 * @param string $name
16b10e64 246 * name of the variable.
6a0b768e 247 * @param string $prefix
16b10e64 248 * adds another level of scope to the session.
6a488035
TO
249 *
250 * @return mixed
6a488035 251 */
00be9182 252 public function get($name, $prefix = NULL) {
6a488035
TO
253 // create session scope
254 $this->createScope($prefix, TRUE);
255
256 if (empty($this->_session) || empty($this->_session[$this->_key])) {
2aa397bc 257 return NULL;
6a488035
TO
258 }
259
260 if (empty($prefix)) {
261 $session =& $this->_session[$this->_key];
262 }
263 else {
264 if (empty($this->_session[$this->_key][$prefix])) {
2aa397bc 265 return NULL;
6a488035
TO
266 }
267 $session =& $this->_session[$this->_key][$prefix];
268 }
269
270 return CRM_Utils_Array::value($name, $session);
271 }
272
273 /**
8eedd10a 274 * Gets all the variables in the current session scope and stuffs them in an associate array.
6a488035 275 *
6a0b768e
TO
276 * @param array $vars
277 * Associative array to store name/value pairs.
278 * @param string $prefix
279 * Will be stripped from the key before putting it in the return.
6a488035 280 */
00be9182 281 public function getVars(&$vars, $prefix = '') {
6a488035
TO
282 // create session scope
283 $this->createScope($prefix, TRUE);
284
285 if (empty($prefix)) {
286 $values = &$this->_session[$this->_key];
287 }
288 else {
289 $values = CRM_Core_BAO_Cache::getItem('CiviCRM Session', "CiviCRM_{$prefix}");
290 }
291
292 if ($values) {
293 foreach ($values as $name => $value) {
294 $vars[$name] = $value;
295 }
296 }
297 }
298
299 /**
8eedd10a 300 * Set and check a timer.
301 *
302 * If it's expired, it will be set again.
303 *
6a488035
TO
304 * Good for showing a message to the user every hour or day (so not bugging them on every page)
305 * Returns true-ish values if the timer is not set or expired, and false if the timer is still running
306 * 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
307 *
6a488035 308 *
6a0b768e 309 * @param string $name
16b10e64 310 * name of the timer.
6a0b768e 311 * @param int $expire
16b10e64 312 * expiry time (in seconds).
6a488035
TO
313 *
314 * @return mixed
6a488035 315 */
00be9182 316 public function timer($name, $expire) {
6a488035
TO
317 $ts = $this->get($name, 'timer');
318 if (!$ts || $ts < time() - $expire) {
319 $this->set($name, time(), 'timer');
320 return $ts ? $ts : 'not set';
321 }
2aa397bc 322 return FALSE;
6a488035
TO
323 }
324
325 /**
f9e31d7f 326 * Adds a userContext to the stack.
6a488035 327 *
6a0b768e
TO
328 * @param string $userContext
329 * The url to return to when done.
330 * @param bool $check
331 * Should we do a dupe checking with the top element.
6a488035 332 */
00be9182 333 public function pushUserContext($userContext, $check = TRUE) {
6a488035
TO
334 if (empty($userContext)) {
335 return;
336 }
337
338 $this->createScope(self::USER_CONTEXT);
339
340 // hack, reset if too big
341 if (count($this->_session[$this->_key][self::USER_CONTEXT]) > 10) {
342 $this->resetScope(self::USER_CONTEXT);
343 $this->createScope(self::USER_CONTEXT);
344 }
345
346 $topUC = array_pop($this->_session[$this->_key][self::USER_CONTEXT]);
347
348 // see if there is a match between the new UC and the top one. the match needs to be
349 // fuzzy since we use the referer at times
350 // if close enough, lets just replace the top with the new one
351 if ($check && $topUC && CRM_Utils_String::match($topUC, $userContext)) {
352 array_push($this->_session[$this->_key][self::USER_CONTEXT], $userContext);
353 }
354 else {
355 if ($topUC) {
356 array_push($this->_session[$this->_key][self::USER_CONTEXT], $topUC);
357 }
358 array_push($this->_session[$this->_key][self::USER_CONTEXT], $userContext);
359 }
360 }
361
362 /**
f9e31d7f 363 * Replace the userContext of the stack with the passed one.
6a488035 364 *
6a0b768e
TO
365 * @param string $userContext
366 * The url to return to when done.
6a488035 367 */
00be9182 368 public function replaceUserContext($userContext) {
6a488035
TO
369 if (empty($userContext)) {
370 return;
371 }
372
373 $this->createScope(self::USER_CONTEXT);
374
375 array_pop($this->_session[$this->_key][self::USER_CONTEXT]);
376 array_push($this->_session[$this->_key][self::USER_CONTEXT], $userContext);
377 }
378
379 /**
f9e31d7f 380 * Pops the top userContext stack.
6a488035 381 *
a6c01b45
CW
382 * @return string
383 * the top of the userContext stack (also pops the top element)
6a488035 384 */
00be9182 385 public function popUserContext() {
6a488035
TO
386 $this->createScope(self::USER_CONTEXT);
387
388 return array_pop($this->_session[$this->_key][self::USER_CONTEXT]);
389 }
390
391 /**
f9e31d7f 392 * Reads the top userContext stack.
6a488035 393 *
a6c01b45
CW
394 * @return string
395 * the top of the userContext stack
6a488035 396 */
00be9182 397 public function readUserContext() {
6a488035
TO
398 $this->createScope(self::USER_CONTEXT);
399
400 $config = CRM_Core_Config::singleton();
401 $lastElement = count($this->_session[$this->_key][self::USER_CONTEXT]) - 1;
402 return $lastElement >= 0 ? $this->_session[$this->_key][self::USER_CONTEXT][$lastElement] : $config->userFrameworkBaseURL;
403 }
404
405 /**
f9e31d7f 406 * Dumps the session to the log.
8eedd10a 407 *
d4ad6ab3 408 * @param int $all
6a488035 409 */
00be9182 410 public function debug($all = 1) {
6a488035
TO
411 $this->initialize();
412 if ($all != 1) {
413 CRM_Core_Error::debug('CRM Session', $this->_session);
414 }
415 else {
416 CRM_Core_Error::debug('CRM Session', $this->_session[$this->_key]);
417 }
418 }
419
420 /**
f9e31d7f 421 * Fetches status messages.
6a488035 422 *
6a0b768e
TO
423 * @param bool $reset
424 * Should we reset the status variable?.
6a488035 425 *
a6c01b45
CW
426 * @return string
427 * the status message if any
6a488035 428 */
00be9182 429 public function getStatus($reset = FALSE) {
6a488035
TO
430 $this->initialize();
431
432 $status = NULL;
433 if (array_key_exists('status', $this->_session[$this->_key])) {
434 $status = $this->_session[$this->_key]['status'];
435 }
436 if ($reset) {
437 $this->_session[$this->_key]['status'] = NULL;
438 unset($this->_session[$this->_key]['status']);
439 }
440 return $status;
441 }
442
443 /**
8eedd10a 444 * Stores an alert to be displayed to the user via crm-messages.
6a488035 445 *
5a4f6742 446 * @param string $text
6a488035
TO
447 * The status message
448 *
5a4f6742 449 * @param string $title
6a488035
TO
450 * The optional title of this message
451 *
5a4f6742 452 * @param string $type
6a488035
TO
453 * The type of this message (printed as a css class). Possible options:
454 * - 'alert' (default)
455 * - 'info'
456 * - 'success'
457 * - 'error' (this message type by default will remain on the screen
458 * until the user dismisses it)
459 * - 'no-popup' (will display in the document like old-school)
460 *
5a4f6742 461 * @param array $options
6a488035
TO
462 * Additional options. Possible values:
463 * - 'unique' (default: true) Check if this message was already set before adding
464 * - 'expires' how long to display this message before fadeout (in ms)
465 * set to 0 for no expiration
466 * defaults to 10 seconds for most messages, 5 if it has a title but no body,
467 * or 0 for errors or messages containing links
6a488035 468 */
00be9182 469 public static function setStatus($text, $title = '', $type = 'alert', $options = array()) {
6a488035
TO
470 // make sure session is initialized, CRM-8120
471 $session = self::singleton();
472 $session->initialize();
473
474 // default options
39b795ba 475 $options += array('unique' => TRUE);
6a488035
TO
476
477 if (!isset(self::$_singleton->_session[self::$_singleton->_key]['status'])) {
478 self::$_singleton->_session[self::$_singleton->_key]['status'] = array();
479 }
bc86ffa9 480 if ($text || $title) {
6a488035
TO
481 if ($options['unique']) {
482 foreach (self::$_singleton->_session[self::$_singleton->_key]['status'] as $msg) {
483 if ($msg['text'] == $text && $msg['title'] == $title) {
484 return;
485 }
486 }
487 }
488 unset($options['unique']);
489 self::$_singleton->_session[self::$_singleton->_key]['status'][] = array(
490 'text' => $text,
491 'title' => $title,
492 'type' => $type,
03a7ec8f 493 'options' => $options ? $options : NULL,
6a488035
TO
494 );
495 }
496 }
497
a0ee3941 498 /**
8eedd10a 499 * Register and retrieve session objects.
500 *
d4ad6ab3 501 * @param string|array $names
a0ee3941 502 */
00be9182 503 public static function registerAndRetrieveSessionObjects($names) {
6a488035
TO
504 if (!is_array($names)) {
505 $names = array($names);
506 }
507
508 if (!self::$_managedNames) {
509 self::$_managedNames = $names;
510 }
511 else {
512 self::$_managedNames = array_merge(self::$_managedNames, $names);
513 }
514
515 CRM_Core_BAO_Cache::restoreSessionFromCache($names);
516 }
517
a0ee3941 518 /**
8eedd10a 519 * Store session objects.
520 *
a0ee3941
EM
521 * @param bool $reset
522 */
00be9182 523 public static function storeSessionObjects($reset = TRUE) {
6a488035
TO
524 if (empty(self::$_managedNames)) {
525 return;
526 }
527
528 self::$_managedNames = CRM_Utils_Array::crmArrayUnique(self::$_managedNames);
529
530 CRM_Core_BAO_Cache::storeSessionToCache(self::$_managedNames, $reset);
531
532 self::$_managedNames = NULL;
533 }
534
bb341097 535 /**
f9e31d7f 536 * Retrieve contact id of the logged in user.
8eedd10a 537 *
df8d3074 538 * @return int|NULL
72b3a70c 539 * contact ID of logged in user
bb341097 540 */
00be9182 541 public static function getLoggedInContactID() {
bb341097
EM
542 $session = CRM_Core_Session::singleton();
543 if (!is_numeric($session->get('userID'))) {
544 return NULL;
545 }
546 return $session->get('userID');
547 }
548
8f864776 549 /**
550 * Get display name of the logged in user.
551 *
552 * @return string
553 *
554 * @throws CiviCRM_API3_Exception
555 */
556 public function getLoggedInContactDisplayName() {
3bdcd4ec 557 $userContactID = CRM_Core_Session::getLoggedInContactID();
8f864776 558 if (!$userContactID) {
559 return '';
560 }
561 return civicrm_api3('Contact', 'getvalue', array('id' => $userContactID, 'return' => 'display_name'));
562 }
563
a0ee3941 564 /**
8eedd10a 565 * Check if session is empty.
566 *
567 * if so we don't cache stuff that we can get away with, helps proxies like varnish.
568 *
a0ee3941
EM
569 * @return bool
570 */
00be9182 571 public function isEmpty() {
d4ad6ab3 572 return empty($_SESSION);
6a488035 573 }
96025800 574
6a488035 575}