3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 $config =& CRM_Core_Config
::singleton();
118 // FIXME: This belongs in CRM_Utils_System_*
119 if ($config->userSystem
->is_drupal
&& function_exists('drupal_session_start')) {
120 // https://issues.civicrm.org/jira/browse/CRM-14356
121 if (!(isset($GLOBALS['lazy_session']) && $GLOBALS['lazy_session'] == TRUE)) {
122 drupal_session_start();
130 $this->_session
=& $_SESSION;
137 if (!isset($this->_session
[$this->_key
]) ||
138 !is_array($this->_session
[$this->_key
])
140 $this->_session
[$this->_key
] = array();
145 * Resets the session store.
149 public function reset($all = 1) {
153 // to make certain we clear it, first initialize it to empty
154 $this->_session
[$this->_key
] = array();
155 unset($this->_session
[$this->_key
]);
158 $this->_session
= array();
164 * Creates a session local scope.
166 * @param string $prefix
168 * @param bool $isRead
169 * Is this a read operation, in this case, the session will not be touched.
171 public function createScope($prefix, $isRead = FALSE) {
172 $this->initialize($isRead);
174 if ($isRead ||
empty($prefix)) {
178 if (empty($this->_session
[$this->_key
][$prefix])) {
179 $this->_session
[$this->_key
][$prefix] = array();
184 * Resets the session local scope.
186 * @param string $prefix
189 public function resetScope($prefix) {
192 if (empty($prefix)) {
196 if (array_key_exists($prefix, $this->_session
[$this->_key
])) {
197 unset($this->_session
[$this->_key
][$prefix]);
202 * Store the variable with the value in the session scope.
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
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.
217 public function set($name, $value = NULL, $prefix = NULL) {
218 // create session scope
219 $this->createScope($prefix);
221 if (empty($prefix)) {
222 $session = &$this->_session
[$this->_key
];
225 $session = &$this->_session
[$this->_key
][$prefix];
228 if (is_array($name)) {
229 foreach ($name as $n => $v) {
234 $session[$name] = $value;
239 * Gets the value of the named variable in the session scope.
241 * This function takes a name and retrieves the value of this
242 * variable from the session scope.
245 * @param string $name
246 * name of the variable.
247 * @param string $prefix
248 * adds another level of scope to the session.
252 public function get($name, $prefix = NULL) {
253 // create session scope
254 $this->createScope($prefix, TRUE);
256 if (empty($this->_session
) ||
empty($this->_session
[$this->_key
])) {
260 if (empty($prefix)) {
261 $session =& $this->_session
[$this->_key
];
264 if (empty($this->_session
[$this->_key
][$prefix])) {
267 $session =& $this->_session
[$this->_key
][$prefix];
270 return CRM_Utils_Array
::value($name, $session);
274 * Gets all the variables in the current session scope and stuffs them in an associate array.
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.
281 public function getVars(&$vars, $prefix = '') {
282 // create session scope
283 $this->createScope($prefix, TRUE);
285 if (empty($prefix)) {
286 $values = &$this->_session
[$this->_key
];
289 $values = CRM_Core_BAO_Cache
::getItem('CiviCRM Session', "CiviCRM_{$prefix}");
293 foreach ($values as $name => $value) {
294 $vars[$name] = $value;
300 * Set and check a timer.
302 * If it's expired, it will be set again.
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
309 * @param string $name
312 * expiry time (in seconds).
316 public function timer($name, $expire) {
317 $ts = $this->get($name, 'timer');
318 if (!$ts ||
$ts < time() - $expire) {
319 $this->set($name, time(), 'timer');
320 return $ts ?
$ts : 'not set';
326 * Adds a userContext to the stack.
328 * @param string $userContext
329 * The url to return to when done.
331 * Should we do a dupe checking with the top element.
333 public function pushUserContext($userContext, $check = TRUE) {
334 if (empty($userContext)) {
338 $this->createScope(self
::USER_CONTEXT
);
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
);
346 $topUC = array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
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);
356 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $topUC);
358 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
363 * Replace the userContext of the stack with the passed one.
365 * @param string $userContext
366 * The url to return to when done.
368 public function replaceUserContext($userContext) {
369 if (empty($userContext)) {
373 $this->createScope(self
::USER_CONTEXT
);
375 array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
376 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
380 * Pops the top userContext stack.
383 * the top of the userContext stack (also pops the top element)
385 public function popUserContext() {
386 $this->createScope(self
::USER_CONTEXT
);
388 return array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
392 * Reads the top userContext stack.
395 * the top of the userContext stack
397 public function readUserContext() {
398 $this->createScope(self
::USER_CONTEXT
);
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
;
406 * Dumps the session to the log.
410 public function debug($all = 1) {
413 CRM_Core_Error
::debug('CRM Session', $this->_session
);
416 CRM_Core_Error
::debug('CRM Session', $this->_session
[$this->_key
]);
421 * Fetches status messages.
424 * Should we reset the status variable?.
427 * the status message if any
429 public function getStatus($reset = FALSE) {
433 if (array_key_exists('status', $this->_session
[$this->_key
])) {
434 $status = $this->_session
[$this->_key
]['status'];
437 $this->_session
[$this->_key
]['status'] = NULL;
438 unset($this->_session
[$this->_key
]['status']);
444 * Stores an alert to be displayed to the user via crm-messages.
446 * @param string $text
449 * @param string $title
450 * The optional title of this message
452 * @param string $type
453 * The type of this message (printed as a css class). Possible options:
454 * - 'alert' (default)
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)
461 * @param array $options
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
469 public static function setStatus($text, $title = '', $type = 'alert', $options = array()) {
470 // make sure session is initialized, CRM-8120
471 $session = self
::singleton();
472 $session->initialize();
475 $options +
= array('unique' => TRUE);
477 if (!isset(self
::$_singleton->_session
[self
::$_singleton->_key
]['status'])) {
478 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] = array();
480 if ($text ||
$title) {
481 if ($options['unique']) {
482 foreach (self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] as $msg) {
483 if ($msg['text'] == $text && $msg['title'] == $title) {
488 unset($options['unique']);
489 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'][] = array(
493 'options' => $options ?
$options : NULL,
499 * Register and retrieve session objects.
501 * @param string|array $names
503 public static function registerAndRetrieveSessionObjects($names) {
504 if (!is_array($names)) {
505 $names = array($names);
508 if (!self
::$_managedNames) {
509 self
::$_managedNames = $names;
512 self
::$_managedNames = array_merge(self
::$_managedNames, $names);
515 CRM_Core_BAO_Cache
::restoreSessionFromCache($names);
519 * Store session objects.
523 public static function storeSessionObjects($reset = TRUE) {
524 if (empty(self
::$_managedNames)) {
528 self
::$_managedNames = CRM_Utils_Array
::crmArrayUnique(self
::$_managedNames);
530 CRM_Core_BAO_Cache
::storeSessionToCache(self
::$_managedNames, $reset);
532 self
::$_managedNames = NULL;
536 * Retrieve contact id of the logged in user.
539 * contact ID of logged in user
541 public static function getLoggedInContactID() {
542 $session = CRM_Core_Session
::singleton();
543 if (!is_numeric($session->get('userID'))) {
546 return $session->get('userID');
550 * Check if session is empty.
552 * if so we don't cache stuff that we can get away with, helps proxies like varnish.
556 public function isEmpty() {
557 return empty($_SESSION);