Merge pull request #19099 from seamuslee001/ref_money_format_update
[civicrm-core.git] / CRM / Core / Session.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Class CRM_Core_Session.
14 */
15 class CRM_Core_Session {
16
17 /**
18 * Cache of all the session names that we manage.
19 * @var array
20 */
21 public static $_managedNames = NULL;
22
23 /**
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
30 *
31 * @var string
32 */
33 protected $_key = 'CiviCRM';
34 const USER_CONTEXT = 'userContext';
35
36 /**
37 * This is just a reference to the real session. Allows us to
38 * debug this class a wee bit easier
39 *
40 * @var object
41 */
42 protected $_session = NULL;
43
44 /**
45 * Current php Session ID : needed to detect if the session is changed
46 *
47 * @var string
48 */
49 protected $sessionID;
50
51 /**
52 * We only need one instance of this object. So we use the singleton
53 * pattern and cache the instance in this variable
54 *
55 * @var object
56 */
57 static private $_singleton = NULL;
58
59 /**
60 * Constructor.
61 *
62 * The CMS takes care of initiating the php session handler session_start().
63 *
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!
67 *
68 * This constructor is invoked whenever any module requests an instance of
69 * the session and one is not available.
70 *
71 * @return CRM_Core_Session
72 */
73 public function __construct() {
74 $this->_session = NULL;
75 }
76
77 /**
78 * Singleton function used to manage this object.
79 *
80 * @return CRM_Core_Session
81 */
82 public static function &singleton() {
83 if (self::$_singleton === NULL) {
84 self::$_singleton = new CRM_Core_Session();
85 }
86 return self::$_singleton;
87 }
88
89 /**
90 * Creates an array in the session.
91 *
92 * All variables now will be stored under this array.
93 *
94 * @param bool $isRead
95 * Is this a read operation, in this case, the session will not be touched.
96 */
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;
102 }
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)) {
106 // CRM-9483
107 if (!isset($_SESSION) && PHP_SAPI !== 'cli') {
108 if ($isRead) {
109 return;
110 }
111 CRM_Core_Config::singleton()->userSystem->sessionStart();
112 }
113 $this->_session =& $_SESSION;
114 }
115
116 if ($isRead) {
117 return;
118 }
119
120 if (!isset($this->_session[$this->_key]) ||
121 !is_array($this->_session[$this->_key])
122 ) {
123 $this->_session[$this->_key] = [];
124 }
125 }
126
127 /**
128 * Resets the session store.
129 *
130 * @param int $all
131 */
132 public function reset($all = 1) {
133 if ($all != 1) {
134 $this->initialize();
135
136 // to make certain we clear it, first initialize it to empty
137 $this->_session[$this->_key] = [];
138 unset($this->_session[$this->_key]);
139 }
140 else {
141 $this->_session = [];
142 }
143
144 }
145
146 /**
147 * Creates a session local scope.
148 *
149 * @param string $prefix
150 * Local scope name.
151 * @param bool $isRead
152 * Is this a read operation, in this case, the session will not be touched.
153 */
154 public function createScope($prefix, $isRead = FALSE) {
155 $this->initialize($isRead);
156
157 if ($isRead || empty($prefix)) {
158 return;
159 }
160
161 if (empty($this->_session[$this->_key][$prefix])) {
162 $this->_session[$this->_key][$prefix] = [];
163 }
164 }
165
166 /**
167 * Resets the session local scope.
168 *
169 * @param string $prefix
170 * Local scope name.
171 */
172 public function resetScope($prefix) {
173 $this->initialize();
174
175 if (empty($prefix)) {
176 return;
177 }
178
179 if (array_key_exists($prefix, $this->_session[$this->_key])) {
180 unset($this->_session[$this->_key][$prefix]);
181 }
182 }
183
184 /**
185 * Store the variable with the value in the session scope.
186 *
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
191 *
192 *
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.
199 */
200 public function set($name, $value = NULL, $prefix = NULL) {
201 // create session scope
202 $this->createScope($prefix);
203
204 if (empty($prefix)) {
205 $session = &$this->_session[$this->_key];
206 }
207 else {
208 $session = &$this->_session[$this->_key][$prefix];
209 }
210
211 if (is_array($name)) {
212 foreach ($name as $n => $v) {
213 $session[$n] = $v;
214 }
215 }
216 else {
217 $session[$name] = $value;
218 }
219 }
220
221 /**
222 * Gets the value of the named variable in the session scope.
223 *
224 * This function takes a name and retrieves the value of this
225 * variable from the session scope.
226 *
227 *
228 * @param string $name
229 * name of the variable.
230 * @param string $prefix
231 * adds another level of scope to the session.
232 *
233 * @return mixed
234 */
235 public function get($name, $prefix = NULL) {
236 // create session scope
237 $this->createScope($prefix, TRUE);
238
239 if (empty($this->_session) || empty($this->_session[$this->_key])) {
240 return NULL;
241 }
242
243 if (empty($prefix)) {
244 $session =& $this->_session[$this->_key];
245 }
246 else {
247 if (empty($this->_session[$this->_key][$prefix])) {
248 return NULL;
249 }
250 $session =& $this->_session[$this->_key][$prefix];
251 }
252
253 return $session[$name] ?? NULL;
254 }
255
256 /**
257 * Gets all the variables in the current session scope and stuffs them in an associate array.
258 *
259 * @param array $vars
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.
263 */
264 public function getVars(&$vars, $prefix = '') {
265 // create session scope
266 $this->createScope($prefix, TRUE);
267
268 if (empty($prefix)) {
269 $values = &$this->_session[$this->_key];
270 }
271 else {
272 $values = Civi::cache('session')->get("CiviCRM_{$prefix}");
273 }
274
275 if ($values) {
276 foreach ($values as $name => $value) {
277 $vars[$name] = $value;
278 }
279 }
280 }
281
282 /**
283 * Set and check a timer.
284 *
285 * If it's expired, it will be set again.
286 *
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
290 *
291 *
292 * @param string $name
293 * name of the timer.
294 * @param int $expire
295 * expiry time (in seconds).
296 *
297 * @return mixed
298 */
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';
304 }
305 return FALSE;
306 }
307
308 /**
309 * Adds a userContext to the stack.
310 *
311 * @param string $userContext
312 * The url to return to when done.
313 * @param bool $check
314 * Should we do a dupe checking with the top element.
315 */
316 public function pushUserContext($userContext, $check = TRUE) {
317 if (empty($userContext)) {
318 return;
319 }
320
321 $this->createScope(self::USER_CONTEXT);
322
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);
327 }
328
329 $topUC = array_pop($this->_session[$this->_key][self::USER_CONTEXT]);
330
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);
336 }
337 else {
338 if ($topUC) {
339 array_push($this->_session[$this->_key][self::USER_CONTEXT], $topUC);
340 }
341 array_push($this->_session[$this->_key][self::USER_CONTEXT], $userContext);
342 }
343 }
344
345 /**
346 * Replace the userContext of the stack with the passed one.
347 *
348 * @param string $userContext
349 * The url to return to when done.
350 */
351 public function replaceUserContext($userContext) {
352 if (empty($userContext)) {
353 return;
354 }
355
356 $this->createScope(self::USER_CONTEXT);
357
358 array_pop($this->_session[$this->_key][self::USER_CONTEXT]);
359 array_push($this->_session[$this->_key][self::USER_CONTEXT], $userContext);
360 }
361
362 /**
363 * Pops the top userContext stack.
364 *
365 * @return string
366 * the top of the userContext stack (also pops the top element)
367 */
368 public function popUserContext() {
369 $this->createScope(self::USER_CONTEXT);
370
371 return array_pop($this->_session[$this->_key][self::USER_CONTEXT]);
372 }
373
374 /**
375 * Reads the top userContext stack.
376 *
377 * @return string
378 * the top of the userContext stack
379 */
380 public function readUserContext() {
381 $this->createScope(self::USER_CONTEXT);
382
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;
386 }
387
388 /**
389 * Dumps the session to the log.
390 *
391 * @param int $all
392 */
393 public function debug($all = 1) {
394 $this->initialize();
395 if ($all != 1) {
396 CRM_Core_Error::debug('CRM Session', $this->_session);
397 }
398 else {
399 CRM_Core_Error::debug('CRM Session', $this->_session[$this->_key]);
400 }
401 }
402
403 /**
404 * Fetches status messages.
405 *
406 * @param bool $reset
407 * Should we reset the status variable?.
408 *
409 * @return string
410 * the status message if any
411 */
412 public function getStatus($reset = FALSE) {
413 $this->initialize();
414
415 $status = NULL;
416 if (array_key_exists('status', $this->_session[$this->_key])) {
417 $status = $this->_session[$this->_key]['status'];
418 }
419 if ($reset) {
420 $this->_session[$this->_key]['status'] = NULL;
421 unset($this->_session[$this->_key]['status']);
422 }
423 return $status;
424 }
425
426 /**
427 * Stores an alert to be displayed to the user via crm-messages.
428 *
429 * @param string $text
430 * The status message
431 *
432 * @param string $title
433 * The optional title of this message
434 *
435 * @param string $type
436 * The type of this message (printed as a css class). Possible options:
437 * - 'alert' (default)
438 * - 'info'
439 * - 'success'
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)
443 *
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
451 */
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();
456
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);
460
461 // default options
462 $options += ['unique' => TRUE];
463
464 if (!isset(self::$_singleton->_session[self::$_singleton->_key]['status'])) {
465 self::$_singleton->_session[self::$_singleton->_key]['status'] = [];
466 }
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) {
471 return;
472 }
473 }
474 }
475 unset($options['unique']);
476 self::$_singleton->_session[self::$_singleton->_key]['status'][] = [
477 'text' => $text,
478 'title' => $title,
479 'type' => $type,
480 'options' => $options ? $options : NULL,
481 ];
482 }
483 }
484
485 /**
486 * Register and retrieve session objects.
487 *
488 * @param string|array $names
489 */
490 public static function registerAndRetrieveSessionObjects($names) {
491 if (!is_array($names)) {
492 $names = [$names];
493 }
494
495 if (!self::$_managedNames) {
496 self::$_managedNames = $names;
497 }
498 else {
499 self::$_managedNames = array_merge(self::$_managedNames, $names);
500 }
501
502 CRM_Core_BAO_Cache::restoreSessionFromCache($names);
503 }
504
505 /**
506 * Store session objects.
507 *
508 * @param bool $reset
509 */
510 public static function storeSessionObjects($reset = TRUE) {
511 if (empty(self::$_managedNames)) {
512 return;
513 }
514
515 self::$_managedNames = CRM_Utils_Array::crmArrayUnique(self::$_managedNames);
516
517 CRM_Core_BAO_Cache::storeSessionToCache(self::$_managedNames, $reset);
518
519 self::$_managedNames = NULL;
520 }
521
522 /**
523 * Retrieve contact id of the logged in user.
524 *
525 * @return int|null
526 * contact ID of logged in user
527 */
528 public static function getLoggedInContactID() {
529 $session = CRM_Core_Session::singleton();
530 if (!is_numeric($session->get('userID'))) {
531 return NULL;
532 }
533 return $session->get('userID');
534 }
535
536 /**
537 * Get display name of the logged in user.
538 *
539 * @return string
540 *
541 * @throws CiviCRM_API3_Exception
542 */
543 public function getLoggedInContactDisplayName() {
544 $userContactID = CRM_Core_Session::getLoggedInContactID();
545 if (!$userContactID) {
546 return '';
547 }
548 return civicrm_api3('Contact', 'getvalue', ['id' => $userContactID, 'return' => 'display_name']);
549 }
550
551 /**
552 * Check if session is empty.
553 *
554 * if so we don't cache stuff that we can get away with, helps proxies like varnish.
555 *
556 * @return bool
557 */
558 public function isEmpty() {
559 return empty($_SESSION);
560 }
561
562 }