3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 require_once "PEAR.php";
32 * Class CRM_Core_Session
34 class CRM_Core_Session
{
37 * Cache of all the session names that we manage.
39 static $_managedNames = NULL;
42 * Key is used to allow the application to have multiple top
43 * level scopes rather than a single scope. (avoids naming
44 * conflicts). We also extend this idea further and have local
45 * scopes within a global scope. Allows us to do cool things
46 * like resetting a specific area of the session code while
47 * keeping the rest intact
51 protected $_key = 'CiviCRM';
52 const USER_CONTEXT
= 'userContext';
55 * This is just a reference to the real session. Allows us to
56 * debug this class a wee bit easier
60 protected $_session = NULL;
63 * We only need one instance of this object. So we use the singleton
64 * pattern and cache the instance in this variable
68 static private $_singleton = NULL;
73 * The CMS takes care of initiating the php session handler session_start().
75 * When using CiviCRM standalone (w/o a CMS), we start the session
76 * in index.php and then pass it off to here.
78 * All crm code should always use the session using
79 * CRM_Core_Session. we prefix stuff to avoid collisions with the CMS and also
80 * collisions with other crm modules!
82 * This constructor is invoked whenever any module requests an instance of
83 * the session and one is not available.
85 * @return CRM_Core_Session
87 public function __construct() {
88 $this->_session
= NULL;
92 * Singleton function used to manage this object.
94 * @return CRM_Core_Session
96 public static function &singleton() {
97 if (self
::$_singleton === NULL) {
98 self
::$_singleton = new CRM_Core_Session();
100 return self
::$_singleton;
104 * Creates an array in the session. All variables now will be stored
107 * @param bool $isRead
108 * Is this a read operation, in this case, the session will not be touched.
113 public function initialize($isRead = FALSE) {
114 // lets initialize the _session variable just before we need it
115 // hopefully any bootstrapping code will actually load the session from the CMS
116 if (!isset($this->_session
)) {
118 if (!isset($_SESSION) && PHP_SAPI
!== 'cli') {
122 $config =& CRM_Core_Config
::singleton();
123 // FIXME: This belongs in CRM_Utils_System_*
124 if ($config->userSystem
->is_drupal
&& function_exists('drupal_session_start')) {
125 // https://issues.civicrm.org/jira/browse/CRM-14356
126 if (!(isset($GLOBALS['lazy_session']) && $GLOBALS['lazy_session'] == TRUE)) {
127 drupal_session_start();
135 $this->_session
=& $_SESSION;
142 if (!isset($this->_session
[$this->_key
]) ||
143 !is_array($this->_session
[$this->_key
])
145 $this->_session
[$this->_key
] = array();
151 * Resets the session store.
158 public function reset($all = 1) {
162 // to make certain we clear it, first initialize it to empty
163 $this->_session
[$this->_key
] = array();
164 unset($this->_session
[$this->_key
]);
167 $this->_session
= array();
174 * Creates a session local scope.
176 * @param string $prefix
178 * @param bool $isRead
179 * Is this a read operation, in this case, the session will not be touched.
184 public function createScope($prefix, $isRead = FALSE) {
185 $this->initialize($isRead);
187 if ($isRead ||
empty($prefix)) {
191 if (empty($this->_session
[$this->_key
][$prefix])) {
192 $this->_session
[$this->_key
][$prefix] = array();
197 * Resets the session local scope.
199 * @param string $prefix
204 public function resetScope($prefix) {
207 if (empty($prefix)) {
211 if (array_key_exists($prefix, $this->_session
[$this->_key
])) {
212 unset($this->_session
[$this->_key
][$prefix]);
217 * Store the variable with the value in the session scope.
219 * This function takes a name, value pair and stores this
220 * in the session scope. Not sure what happens if we try
221 * to store complex objects in the session. I suspect it
222 * is supported but we need to verify this
225 * @param string $name
226 * Name of the variable.
227 * @param mixed $value
228 * Value of the variable.
229 * @param string $prefix
230 * A string to prefix the keys in the session with.
234 public function set($name, $value = NULL, $prefix = NULL) {
235 // create session scope
236 $this->createScope($prefix);
238 if (empty($prefix)) {
239 $session = &$this->_session
[$this->_key
];
242 $session = &$this->_session
[$this->_key
][$prefix];
245 if (is_array($name)) {
246 foreach ($name as $n => $v) {
251 $session[$name] = $value;
256 * Gets the value of the named variable in the session scope.
258 * This function takes a name and retrieves the value of this
259 * variable from the session scope.
262 * @param string $name
263 * name of the variable.
264 * @param string $prefix
265 * adds another level of scope to the session.
269 public function get($name, $prefix = NULL) {
270 // create session scope
271 $this->createScope($prefix, TRUE);
273 if (empty($this->_session
) ||
empty($this->_session
[$this->_key
])) {
277 if (empty($prefix)) {
278 $session =& $this->_session
[$this->_key
];
281 if (empty($this->_session
[$this->_key
][$prefix])) {
284 $session =& $this->_session
[$this->_key
][$prefix];
287 return CRM_Utils_Array
::value($name, $session);
291 * Gets all the variables in the current session scope
292 * and stuffs them in an associate array
296 * Associative array to store name/value pairs.
297 * @param string $prefix
298 * Will be stripped from the key before putting it in the return.
302 public function getVars(&$vars, $prefix = '') {
303 // create session scope
304 $this->createScope($prefix, TRUE);
306 if (empty($prefix)) {
307 $values = &$this->_session
[$this->_key
];
310 $values = CRM_Core_BAO_Cache
::getItem('CiviCRM Session', "CiviCRM_{$prefix}");
314 foreach ($values as $name => $value) {
315 $vars[$name] = $value;
321 * Set and check a timer. If it's expired, it will be set again.
322 * Good for showing a message to the user every hour or day (so not bugging them on every page)
323 * Returns true-ish values if the timer is not set or expired, and false if the timer is still running
324 * 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
327 * @param string $name
330 * expiry time (in seconds).
334 public function timer($name, $expire) {
335 $ts = $this->get($name, 'timer');
336 if (!$ts ||
$ts < time() - $expire) {
337 $this->set($name, time(), 'timer');
338 return $ts ?
$ts : 'not set';
344 * Adds a userContext to the stack.
346 * @param string $userContext
347 * The url to return to when done.
349 * Should we do a dupe checking with the top element.
353 public function pushUserContext($userContext, $check = TRUE) {
354 if (empty($userContext)) {
358 $this->createScope(self
::USER_CONTEXT
);
360 // hack, reset if too big
361 if (count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) > 10) {
362 $this->resetScope(self
::USER_CONTEXT
);
363 $this->createScope(self
::USER_CONTEXT
);
366 $topUC = array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
368 // see if there is a match between the new UC and the top one. the match needs to be
369 // fuzzy since we use the referer at times
370 // if close enough, lets just replace the top with the new one
371 if ($check && $topUC && CRM_Utils_String
::match($topUC, $userContext)) {
372 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
376 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $topUC);
378 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
383 * Replace the userContext of the stack with the passed one.
385 * @param string $userContext
386 * The url to return to when done.
390 public function replaceUserContext($userContext) {
391 if (empty($userContext)) {
395 $this->createScope(self
::USER_CONTEXT
);
397 array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
398 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
402 * Pops the top userContext stack.
405 * the top of the userContext stack (also pops the top element)
407 public function popUserContext() {
408 $this->createScope(self
::USER_CONTEXT
);
410 return array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
414 * Reads the top userContext stack.
417 * the top of the userContext stack
419 public function readUserContext() {
420 $this->createScope(self
::USER_CONTEXT
);
422 $config = CRM_Core_Config
::singleton();
423 $lastElement = count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) - 1;
424 return $lastElement >= 0 ?
$this->_session
[$this->_key
][self
::USER_CONTEXT
][$lastElement] : $config->userFrameworkBaseURL
;
428 * Dumps the session to the log.
431 public function debug($all = 1) {
434 CRM_Core_Error
::debug('CRM Session', $this->_session
);
437 CRM_Core_Error
::debug('CRM Session', $this->_session
[$this->_key
]);
442 * Fetches status messages.
445 * Should we reset the status variable?.
448 * the status message if any
450 public function getStatus($reset = FALSE) {
454 if (array_key_exists('status', $this->_session
[$this->_key
])) {
455 $status = $this->_session
[$this->_key
]['status'];
458 $this->_session
[$this->_key
]['status'] = NULL;
459 unset($this->_session
[$this->_key
]['status']);
465 * Stores an alert to be displayed to the user via crm-messages
467 * @param string $text
470 * @param string $title
471 * The optional title of this message
473 * @param string $type
474 * The type of this message (printed as a css class). Possible options:
475 * - 'alert' (default)
478 * - 'error' (this message type by default will remain on the screen
479 * until the user dismisses it)
480 * - 'no-popup' (will display in the document like old-school)
482 * @param array $options
483 * Additional options. Possible values:
484 * - 'unique' (default: true) Check if this message was already set before adding
485 * - 'expires' how long to display this message before fadeout (in ms)
486 * set to 0 for no expiration
487 * defaults to 10 seconds for most messages, 5 if it has a title but no body,
488 * or 0 for errors or messages containing links
493 public static function setStatus($text, $title = '', $type = 'alert', $options = array()) {
494 // make sure session is initialized, CRM-8120
495 $session = self
::singleton();
496 $session->initialize();
499 $options +
= array('unique' => TRUE);
501 if (!isset(self
::$_singleton->_session
[self
::$_singleton->_key
]['status'])) {
502 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] = array();
504 if ($text ||
$title) {
505 if ($options['unique']) {
506 foreach (self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] as $msg) {
507 if ($msg['text'] == $text && $msg['title'] == $title) {
512 unset($options['unique']);
513 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'][] = array(
517 'options' => $options ?
$options : NULL,
523 * @param string|array $names
525 public static function registerAndRetrieveSessionObjects($names) {
526 if (!is_array($names)) {
527 $names = array($names);
530 if (!self
::$_managedNames) {
531 self
::$_managedNames = $names;
534 self
::$_managedNames = array_merge(self
::$_managedNames, $names);
537 CRM_Core_BAO_Cache
::restoreSessionFromCache($names);
543 public static function storeSessionObjects($reset = TRUE) {
544 if (empty(self
::$_managedNames)) {
548 self
::$_managedNames = CRM_Utils_Array
::crmArrayUnique(self
::$_managedNames);
550 CRM_Core_BAO_Cache
::storeSessionToCache(self
::$_managedNames, $reset);
552 self
::$_managedNames = NULL;
556 * Retrieve contact id of the logged in user.
558 * contact ID of logged in user
560 public static function getLoggedInContactID() {
561 $session = CRM_Core_Session
::singleton();
562 if (!is_numeric($session->get('userID'))) {
565 return $session->get('userID');
571 public function isEmpty() {
572 // check if session is empty, if so we don't cache
573 // stuff that we can get away with
574 // helps proxies like varnish
575 return empty($_SESSION);