3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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";
30 class CRM_Core_Session
{
33 * Cache of all the session names that we manage
35 static $_managedNames = NULL;
38 * key is used to allow the application to have multiple top
39 * level scopes rather than a single scope. (avoids naming
40 * conflicts). We also extend this idea further and have local
41 * scopes within a global scope. Allows us to do cool things
42 * like resetting a specific area of the session code while
43 * keeping the rest intact
47 protected $_key = 'CiviCRM';
48 CONST USER_CONTEXT
= 'userContext';
51 * This is just a reference to the real session. Allows us to
52 * debug this class a wee bit easier
56 protected $_session = NULL;
59 * We only need one instance of this object. So we use the singleton
60 * pattern and cache the instance in this variable
65 static private $_singleton = NULL;
70 * Since we are now a client / module of drupal, drupal takes care
71 * of initiating the php session handler session_start ().
73 * When using CiviCRM standalone (i.e. w/o Drupal), we start the session
74 * in index.php and then pass it off to here.
76 * All crm code should always use the session using
77 * CRM_Core_Session. we prefix stuff to avoid collisions with drupal and also
78 * 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 function __construct() {
85 $this->_session
= null;
89 * singleton function used to manage this object
91 * @return CRM_Core_Session
94 static function &singleton() {
95 if (self
::$_singleton === NULL) {
96 self
::$_singleton = new CRM_Core_Session
;
98 return self
::$_singleton;
102 * Creates an array in the session. All variables now will be stored
105 * @param boolean isRead is this a read operation, in this case, the session will not be touched
111 function initialize($isRead = FALSE) {
112 // lets initialize the _session variable just before we need it
113 // hopefully any bootstrapping code will actually load the session from the CMS
114 if (!isset($this->_session
)) {
116 if (!isset($_SESSION) && PHP_SAPI
!== 'cli') {
120 $config =& CRM_Core_Config
::singleton();
121 if ($config->userSystem
->is_drupal
&& function_exists('drupal_session_start')) {
122 // https://issues.civicrm.org/jira/browse/CRM-14356
123 if (! (isset($GLOBALS['lazy_session']) && $GLOBALS['lazy_session'] == true)) {
124 drupal_session_start();
132 $this->_session
=& $_SESSION;
139 if (!isset($this->_session
[$this->_key
]) ||
140 !is_array($this->_session
[$this->_key
])
142 $this->_session
[$this->_key
] = array();
148 * Resets the session store
156 function reset($all = 1) {
160 // to make certain we clear it, first initialize it to empty
161 $this->_session
[$this->_key
] = array();
162 unset($this->_session
[$this->_key
]);
165 $this->_session
= array();
172 * creates a session local scope
174 * @param string prefix local scope name
175 * @param boolean isRead is this a read operation, in this case, the session will not be touched
181 function createScope($prefix, $isRead = FALSE) {
182 $this->initialize($isRead);
184 if ($isRead ||
empty($prefix)) {
188 if (empty($this->_session
[$this->_key
][$prefix])) {
189 $this->_session
[$this->_key
][$prefix] = array();
194 * resets the session local scope
196 * @param string local scope name
201 function resetScope($prefix) {
204 if (empty($prefix)) {
208 if (array_key_exists($prefix, $this->_session
[$this->_key
])) {
209 unset($this->_session
[$this->_key
][$prefix]);
214 * Store the variable with the value in the session scope
216 * This function takes a name, value pair and stores this
217 * in the session scope. Not sure what happens if we try
218 * to store complex objects in the session. I suspect it
219 * is supported but we need to verify this
223 * @param string $name name of the variable
224 * @param mixed $value value of the variable
225 * @param string $prefix a string to prefix the keys in the session with
230 function set($name, $value = NULL, $prefix = NULL) {
231 // create session scope
232 $this->createScope($prefix);
234 if (empty($prefix)) {
235 $session = &$this->_session
[$this->_key
];
238 $session = &$this->_session
[$this->_key
][$prefix];
241 if (is_array($name)) {
242 foreach ($name as $n => $v) {
247 $session[$name] = $value;
252 * Gets the value of the named variable in the session scope
254 * This function takes a name and retrieves the value of this
255 * variable from the session scope.
259 * @param string name : name of the variable
260 * @param string prefix : adds another level of scope to the session
265 function get($name, $prefix = NULL) {
266 // create session scope
267 $this->createScope($prefix, TRUE);
269 if (empty($this->_session
) ||
empty($this->_session
[$this->_key
])) {
273 if (empty($prefix)) {
274 $session =& $this->_session
[$this->_key
];
277 if (empty($this->_session
[$this->_key
][$prefix])) {
280 $session =& $this->_session
[$this->_key
][$prefix];
283 return CRM_Utils_Array
::value($name, $session);
287 * Gets all the variables in the current session scope
288 * and stuffs them in an associate array
292 * @param array vars : associative array to store name/value pairs
293 * @param string Strip prefix from the key before putting it in the return
298 function getVars(&$vars, $prefix = '') {
299 // create session scope
300 $this->createScope($prefix, TRUE);
302 if (empty($prefix)) {
303 $values = &$this->_session
[$this->_key
];
306 $values = CRM_Core_BAO_Cache
::getItem('CiviCRM Session', "CiviCRM_{$prefix}");
310 foreach ($values as $name => $value) {
311 $vars[$name] = $value;
317 * Set and check a timer. If it's expired, it will be set again.
318 * Good for showing a message to the user every hour or day (so not bugging them on every page)
319 * Returns true-ish values if the timer is not set or expired, and false if the timer is still running
320 * 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
324 * @param string name : name of the timer
325 * @param int expire : expiry time (in seconds)
330 function timer($name, $expire) {
331 $ts = $this->get($name, 'timer');
332 if (!$ts ||
$ts < time() - $expire) {
333 $this->set($name, time(), 'timer');
334 return $ts ?
$ts : 'not set';
340 * adds a userContext to the stack
342 * @param string $userContext the url to return to when done
343 * @param boolean $check should we do a dupe checking with the top element
350 function pushUserContext($userContext, $check = TRUE) {
351 if (empty($userContext)) {
355 $this->createScope(self
::USER_CONTEXT
);
357 // hack, reset if too big
358 if (count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) > 10) {
359 $this->resetScope(self
::USER_CONTEXT
);
360 $this->createScope(self
::USER_CONTEXT
);
363 $topUC = array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
365 // see if there is a match between the new UC and the top one. the match needs to be
366 // fuzzy since we use the referer at times
367 // if close enough, lets just replace the top with the new one
368 if ($check && $topUC && CRM_Utils_String
::match($topUC, $userContext)) {
369 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
373 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $topUC);
375 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
380 * replace the userContext of the stack with the passed one
382 * @param string the url to return to when done
389 function replaceUserContext($userContext) {
390 if (empty($userContext)) {
394 $this->createScope(self
::USER_CONTEXT
);
396 array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
397 array_push($this->_session
[$this->_key
][self
::USER_CONTEXT
], $userContext);
401 * pops the top userContext stack
405 * @return the top of the userContext stack (also pops the top element)
408 function popUserContext() {
409 $this->createScope(self
::USER_CONTEXT
);
411 return array_pop($this->_session
[$this->_key
][self
::USER_CONTEXT
]);
415 * reads the top userContext stack
419 * @return the top of the userContext stack
422 function readUserContext() {
423 $this->createScope(self
::USER_CONTEXT
);
425 $config = CRM_Core_Config
::singleton();
426 $lastElement = count($this->_session
[$this->_key
][self
::USER_CONTEXT
]) - 1;
427 return $lastElement >= 0 ?
$this->_session
[$this->_key
][self
::USER_CONTEXT
][$lastElement] : $config->userFrameworkBaseURL
;
431 * dumps the session to the log
433 function debug($all = 1) {
436 CRM_Core_Error
::debug('CRM Session', $this->_session
);
439 CRM_Core_Error
::debug('CRM Session', $this->_session
[$this->_key
]);
444 * Fetches status messages
446 * @param $reset boolean should we reset the status variable?
448 * @return string the status message if any
450 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 $text string
470 * @param $title string
471 * The optional title of this message
473 * @param $type string
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 $options array
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
494 static function setStatus($text, $title = '', $type = 'alert', $options = array()) {
495 // make sure session is initialized, CRM-8120
496 $session = self
::singleton();
497 $session->initialize();
500 $options +
= array('unique' => TRUE);
502 if (!isset(self
::$_singleton->_session
[self
::$_singleton->_key
]['status'])) {
503 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] = array();
505 if ($text ||
$title) {
506 if ($options['unique']) {
507 foreach (self
::$_singleton->_session
[self
::$_singleton->_key
]['status'] as $msg) {
508 if ($msg['text'] == $text && $msg['title'] == $title) {
513 unset($options['unique']);
514 self
::$_singleton->_session
[self
::$_singleton->_key
]['status'][] = array(
518 'options' => $options ?
$options : NULL,
523 static function registerAndRetrieveSessionObjects($names) {
524 if (!is_array($names)) {
525 $names = array($names);
528 if (!self
::$_managedNames) {
529 self
::$_managedNames = $names;
532 self
::$_managedNames = array_merge(self
::$_managedNames, $names);
535 CRM_Core_BAO_Cache
::restoreSessionFromCache($names);
538 static function storeSessionObjects($reset = TRUE) {
539 if (empty(self
::$_managedNames)) {
543 self
::$_managedNames = CRM_Utils_Array
::crmArrayUnique(self
::$_managedNames);
545 CRM_Core_BAO_Cache
::storeSessionToCache(self
::$_managedNames, $reset);
547 self
::$_managedNames = NULL;
551 * Retrieve contact id of the logged in user
552 * @return integer | NULL contact ID of logged in user
554 static function getLoggedInContactID() {
555 $session = CRM_Core_Session
::singleton();
556 if (!is_numeric($session->get('userID'))) {
559 return $session->get('userID');
563 // check if session is empty, if so we dont cache
564 // stuff that we can get away with
565 // helps proxies like varnish
566 return empty($_SESSION) ?
TRUE : FALSE;