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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * System wide utilities.
40 class CRM_Utils_System
{
42 static $_callbacks = NULL;
45 * @var string Page title
50 * Compose a new URL string from the current URL string.
52 * Used by all the framework components, specifically,
55 * @param string $urlVar
56 * The url variable being considered (i.e. crmPageID, crmSortID etc).
57 * @param bool $includeReset
58 * (optional) Whether to include the reset GET string (if present).
59 * @param bool $includeForce
60 * (optional) Whether to include the force GET string (if present).
62 * (optional) The path to use for the new url.
63 * @param string $absolute
64 * (optional) Whether to return an absolute URL.
70 static function makeURL($urlVar, $includeReset = FALSE, $includeForce = TRUE, $path = NULL, $absolute = FALSE) {
72 $config = CRM_Core_Config
::singleton();
73 $path = CRM_Utils_Array
::value($config->userFrameworkURLVar
, $_GET);
82 CRM_Utils_System
::getLinksUrl($urlVar, $includeReset, $includeForce),
88 * Get the query string and clean it up.
90 * Strips some variables that should not be propagated, specifically variables
91 * like 'reset'. Also strips any side-affect actions (e.g. export).
93 * This function is copied mostly verbatim from Pager.php (_getLinksUrl)
95 * @param string $urlVar
96 * The URL variable being considered (e.g. crmPageID, crmSortID etc).
97 * @param bool $includeReset
98 * (optional) By default this is FALSE, meaning that the reset parameter
99 * is skipped. Set to TRUE to leave the reset parameter as-is.
100 * @param bool $includeForce
102 * @param bool $skipUFVar
108 static function getLinksUrl($urlVar, $includeReset = FALSE, $includeForce = TRUE, $skipUFVar = TRUE) {
109 // Sort out query string to prevent messy urls
110 $querystring = array();
114 if (!empty($_SERVER['QUERY_STRING'])) {
115 $qs = explode('&', str_replace('&', '&', $_SERVER['QUERY_STRING']));
116 for ($i = 0, $cnt = count($qs); $i < $cnt; $i++
) {
117 // check first if exist a pair
118 if (strstr($qs[$i], '=') !== FALSE) {
119 list($name, $value) = explode('=', $qs[$i]);
120 if ($name != $urlVar) {
121 $name = rawurldecode($name);
122 //check for arrays in parameters: site.php?foo[]=1&foo[]=2&foo[]=3
123 if ((strpos($name, '[') !== FALSE) &&
124 (strpos($name, ']') !== FALSE)
144 // Ok this is a big assumption but usually works
145 // If we are in snippet mode, retain the 'section' param, if not, get rid
147 if (!empty($qs['snippet'])) {
148 unset($qs['snippet']);
151 unset($qs['section']);
155 $config = CRM_Core_Config
::singleton();
156 unset($qs[$config->userFrameworkURLVar
]);
159 foreach ($qs as $name => $value) {
160 if ($name != 'reset' ||
$includeReset) {
161 $querystring[] = $name . '=' . $value;
165 $querystring = array_merge($querystring, array_unique($arrays));
167 $url = implode('&', $querystring);
169 $url .= (!empty($querystring) ?
'&' : '') . $urlVar . '=';
176 * If we are using a theming system, invoke theme, else just print the
179 * @param string $content
180 * The content that will be themed.
182 * (optional) Are we displaying to the screen or bypassing theming?
183 * @param bool $maintenance
184 * (optional) For maintenance mode.
188 static function theme(
193 $config = &CRM_Core_Config
::singleton();
194 return $config->userSystem
->theme($content, $print, $maintenance);
198 * Generate a query string if input is an array.
200 * @param array|string $query
203 static function makeQueryString($query) {
204 if (is_array($query)) {
206 foreach ($query as $key => $value) {
207 $buf .= ($buf ?
'&' : '') . urlencode($key) . '=' . urlencode($value);
215 * Generate an internal CiviCRM URL.
217 * @param string $path
218 * The path being linked to, such as "civicrm/add".
219 * @param array|string $query
220 * A query string to append to the link, or an array of key-value pairs.
221 * @param bool $absolute
222 * Whether to force the output to be an absolute link (beginning with a
223 * URI-scheme such as 'http:'). Useful for links that will be displayed
224 * outside the site, such as in an RSS feed.
225 * @param string $fragment
226 * A fragment identifier (named anchor) to append to the link.
228 * @param bool $htmlize
229 * @param bool $frontend
230 * @param bool $forceBackend
232 * An HTML string containing a link to the given path.
242 $forceBackend = FALSE
244 $query = self
::makeQueryString($query);
246 // we have a valid query and it has not yet been transformed
247 if ($htmlize && !empty($query) && strpos($query, '&') === FALSE) {
248 $query = htmlentities($query);
251 $config = CRM_Core_Config
::singleton();
252 return $config->userSystem
->url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
255 static function href($text, $path = NULL, $query = NULL, $absolute = TRUE,
256 $fragment = NULL, $htmlize = TRUE, $frontend = FALSE, $forceBackend = FALSE
258 $url = self
::url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
259 return "<a href=\"$url\">$text</a>";
262 static function permissionDenied() {
263 $config = CRM_Core_Config
::singleton();
264 return $config->userSystem
->permissionDenied();
267 static function logout() {
268 $config = CRM_Core_Config
::singleton();
269 return $config->userSystem
->logout();
272 // this is a very drupal specific function for now
273 static function updateCategories() {
274 $config = CRM_Core_Config
::singleton();
275 if ($config->userSystem
->is_drupal
) {
276 $config->userSystem
->updateCategories();
281 * What menu path are we currently on. Called for the primary tpl
283 * @return string the current menu path
286 static function currentPath() {
287 $config = CRM_Core_Config
::singleton();
288 return trim(CRM_Utils_Array
::value($config->userFrameworkURLVar
, $_GET), '/');
292 * This function is called from a template to compose a url.
294 * @param array $params
295 * List of parameters.
300 static function crmURL($params) {
301 $p = CRM_Utils_Array
::value('p', $params);
303 $p = self
::currentPath();
308 CRM_Utils_Array
::value('q', $params),
309 CRM_Utils_Array
::value('a', $params, FALSE),
310 CRM_Utils_Array
::value('f', $params),
311 CRM_Utils_Array
::value('h', $params, TRUE),
312 CRM_Utils_Array
::value('fe', $params, FALSE),
313 CRM_Utils_Array
::value('fb', $params, FALSE)
318 * Sets the title of the page.
320 * @param string $title
321 * @param string $pageTitle
325 static function setTitle($title, $pageTitle = NULL) {
326 self
::$title = $title;
327 $config = CRM_Core_Config
::singleton();
328 return $config->userSystem
->setTitle($title, $pageTitle);
332 * Figures and sets the userContext.
334 * Uses the referer if valid else uses the default.
336 * @param array $names
337 * Refererer should match any str in this array.
338 * @param string $default
339 * (optional) The default userContext if no match found.
343 static function setUserContext($names, $default = NULL) {
346 $session = CRM_Core_Session
::singleton();
347 $referer = CRM_Utils_Array
::value('HTTP_REFERER', $_SERVER);
349 if ($referer && !empty($names)) {
350 foreach ($names as $name) {
351 if (strstr($referer, $name)) {
359 $session->pushUserContext($url);
364 * Gets a class name for an object.
366 * @param object $object
367 * Object whose class name is needed.
370 * The class name of the object.
374 static function getClassName($object) {
375 return get_class($object);
379 * Redirect to another URL.
382 * The URL to provide to the browser via the Location header.
386 static function redirect($url = NULL) {
388 $url = self
::url('civicrm/dashboard', 'reset=1');
391 // replace the & characters with &
392 // this is kinda hackish but not sure how to do it right
393 $url = str_replace('&', '&', $url);
395 // If we are in a json context, respond appropriately
396 if (CRM_Utils_Array
::value('snippet', $_GET) === 'json') {
397 CRM_Core_Page_AJAX
::returnJsonResponse(array(
398 'status' => 'redirect',
399 'userContext' => $url,
403 header('Location: ' . $url);
408 * Redirect to another URL using JavaScript.
410 * Use an html based file with javascript embedded to redirect to another url
411 * This prevent the too many redirect errors emitted by various browsers
414 * (optional) The destination URL.
415 * @param string $title
416 * (optional) The page title to use for the redirect page.
417 * @param string $message
418 * (optional) The message to provide in the body of the redirect page.
422 static function jsRedirect(
428 $url = self
::url('civicrm/dashboard', 'reset=1');
432 $title = ts('CiviCRM task in progress');
436 $message = ts('A long running CiviCRM task is currently in progress. This message will be refreshed till the task is completed');
439 // replace the & characters with &
440 // this is kinda hackish but not sure how to do it right
441 $url = str_replace('&', '&', $url);
443 $template = CRM_Core_Smarty
::singleton();
444 $template->assign('redirectURL', $url);
445 $template->assign('title', $title);
446 $template->assign('message', $message);
448 $html = $template->fetch('CRM/common/redirectJS.tpl');
456 * Append an additional breadcrumb tag to the existing breadcrumbs.
458 * @param $breadCrumbs
462 static function appendBreadCrumb($breadCrumbs) {
463 $config = CRM_Core_Config
::singleton();
464 return $config->userSystem
->appendBreadCrumb($breadCrumbs);
468 * Reset an additional breadcrumb tag to the existing breadcrumb.
472 static function resetBreadCrumb() {
473 $config = CRM_Core_Config
::singleton();
474 return $config->userSystem
->resetBreadCrumb();
478 * Append a string to the head of the HTML file.
484 static function addHTMLHead($bc) {
485 $config = CRM_Core_Config
::singleton();
486 return $config->userSystem
->addHTMLHead($bc);
490 * Determine the post URL for a form
493 * The default action if one is pre-specified.
496 * The URL to post the form.
499 static function postURL($action) {
500 $config = CRM_Core_Config
::singleton();
501 return $config->userSystem
->postURL($action);
505 * Rewrite various system URLs to https.
509 static function mapConfigToSSL() {
510 $config = CRM_Core_Config
::singleton();
511 $config->userFrameworkResourceURL
= str_replace('http://', 'https://', $config->userFrameworkResourceURL
);
512 $config->resourceBase
= $config->userFrameworkResourceURL
;
514 if (! empty($config->extensionsURL
)) {
515 $config->extensionsURL
= str_replace('http://', 'https://', $config->extensionsURL
);
518 return $config->userSystem
->mapConfigToSSL();
522 * Get the base URL of the system.
527 static function baseURL() {
528 $config = CRM_Core_Config
::singleton();
529 return $config->userFrameworkBaseURL
;
534 static function authenticateAbort($message, $abort) {
546 * (optional) Whether to exit; defaults to true.
548 static function authenticateKey($abort = TRUE) {
549 // also make sure the key is sent and is valid
550 $key = trim(CRM_Utils_Array
::value('key', $_REQUEST));
552 $docAdd = "More info at:" . CRM_Utils_System
::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
555 return self
::authenticateAbort(
556 "ERROR: You need to send a valid key to execute this file. " . $docAdd . "\n",
561 $siteKey = defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: NULL;
563 if (!$siteKey ||
empty($siteKey)) {
564 return self
::authenticateAbort(
565 "ERROR: You need to set a valid site key in civicrm.settings.php. " . $docAdd . "\n",
570 if (strlen($siteKey) < 8) {
571 return self
::authenticateAbort(
572 "ERROR: Site key needs to be greater than 7 characters in civicrm.settings.php. " . $docAdd . "\n",
577 if ($key !== $siteKey) {
578 return self
::authenticateAbort(
579 "ERROR: Invalid key value sent. " . $docAdd . "\n",
590 static function authenticateScript($abort = TRUE, $name = NULL, $pass = NULL, $storeInSession = TRUE, $loadCMSBootstrap = TRUE, $requireKey = TRUE) {
591 // auth to make sure the user has a login/password to do a shell operation
592 // later on we'll link this to acl's
594 $name = trim(CRM_Utils_Array
::value('name', $_REQUEST));
595 $pass = trim(CRM_Utils_Array
::value('pass', $_REQUEST));
598 // its ok to have an empty password
600 return self
::authenticateAbort(
601 "ERROR: You need to send a valid user name and password to execute this file\n",
606 if ($requireKey && !self
::authenticateKey($abort)) {
610 $result = CRM_Utils_System
::authenticate($name, $pass, $loadCMSBootstrap);
612 return self
::authenticateAbort(
613 "ERROR: Invalid username and/or password\n",
617 elseif ($storeInSession) {
618 // lets store contact id and user id in session
619 list($userID, $ufID, $randomNumber) = $result;
620 if ($userID && $ufID) {
621 $config = CRM_Core_Config
::singleton();
622 $config->userSystem
->setUserSession( array($userID, $ufID) );
625 return self
::authenticateAbort(
626 "ERROR: Unexpected error, could not match userID and contactID",
636 * Authenticate the user against the uf db.
638 * In case of succesful authentication, returns an array consisting of
639 * (contactID, ufID, unique string). Returns FALSE if authentication is
642 * @param string $name
644 * @param string $password
646 * @param bool $loadCMSBootstrap
649 * @return false|array
652 static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
653 $config = CRM_Core_Config
::singleton();
655 /* Before we do any loading, let's start the session and write to it.
656 * We typically call authenticate only when we need to bootstrap the CMS
657 * directly via Civi and hence bypass the normal CMS auth and bootstrap
658 * process typically done in CLI and cron scripts. See: CRM-12648
660 $session = CRM_Core_Session
::singleton();
661 $session->set( 'civicrmInitSession', TRUE );
663 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
664 return $config->userSystem
->authenticate($name, $password, $loadCMSBootstrap, $realPath);
668 * Set a message in the UF to display to a user.
670 * @param string $message
671 * The message to set.
675 static function setUFMessage($message) {
676 $config = CRM_Core_Config
::singleton();
677 return $config->userSystem
->setMessage($message);
682 * Determine whether a value is null-ish.
685 * The value to check for null.
688 static function isNull($value) {
689 // FIXME: remove $value = 'null' string test when we upgrade our DAO code to handle passing null in a better way.
690 if (!isset($value) ||
$value === NULL ||
$value === '' ||
$value === 'null') {
693 if (is_array($value)) {
694 foreach ($value as $key => $value) {
695 if (!self
::isNull($value)) {
705 * Obscure all but the last few digits of a credit card number.
707 * @param string $number
708 * The credit card number to obscure.
710 * (optional) The number of digits to preserve unmodified.
712 * The obscured credit card number.
714 static function mungeCreditCard($number, $keep = 4) {
715 $number = trim($number);
716 if (empty($number)) {
719 $replace = str_repeat('*', strlen($number) - $keep);
720 return substr_replace($number, $replace, 0, -$keep);
724 * Determine which PHP modules are loaded.
728 public static function parsePHPModules() {
730 phpinfo(INFO_MODULES
);
731 $s = ob_get_contents();
734 $s = strip_tags($s, '<h2><th><td>');
735 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/', "<info>\\1</info>", $s);
736 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/', "<info>\\1</info>", $s);
737 $vTmp = preg_split('/(<h2>[^<]+<\/h2>)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE
);
739 for ($i = 1; $i < count($vTmp); $i++
) {
740 if (preg_match('/<h2>([^<]+)<\/h2>/', $vTmp[$i], $vMat)) {
741 $vName = trim($vMat[1]);
742 $vTmp2 = explode("\n", $vTmp[$i +
1]);
743 foreach ($vTmp2 AS $vOne) {
744 $vPat = '<info>([^<]+)<\/info>';
745 $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
746 $vPat2 = "/$vPat\s*$vPat/";
748 if (preg_match($vPat3, $vOne, $vMat)) {
749 $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]), trim($vMat[3]));
752 elseif (preg_match($vPat2, $vOne, $vMat)) {
753 $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
762 * Get a setting from a loaded PHP module.
764 public static function getModuleSetting($pModuleName, $pSetting) {
765 $vModules = self
::parsePHPModules();
766 return $vModules[$pModuleName][$pSetting];
773 static function memory($title = NULL) {
776 $pid = posix_getpid();
779 $memory = str_replace("\n", '', shell_exec("ps -p" . $pid . " -o rss="));
780 $memory .= ", " . time();
782 CRM_Core_Error
::debug_var($title, $memory);
788 * @param string $name
789 * @param string $mimeType
792 * @param bool $output
794 static function download($name, $mimeType, &$buffer,
797 $disposition = 'attachment'
799 $now = gmdate('D, d M Y H:i:s') . ' GMT';
801 header('Content-Type: ' . $mimeType);
802 header('Expires: ' . $now);
804 // lem9 & loic1: IE need specific headers
805 $isIE = strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE');
807 $fileString = "filename=\"{$name}.{$ext}\"";
810 $fileString = "filename=\"{$name}\"";
813 header("Content-Disposition: inline; $fileString");
814 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
815 header('Pragma: public');
818 header("Content-Disposition: $disposition; $fileString");
819 header('Pragma: no-cache');
829 * Gather and print (and possibly log) amount of used memory.
831 * @param string $title
833 * (optional) Whether to log the memory usage information.
835 static function xMemory($title = NULL, $log = FALSE) {
836 $mem = (float ) xdebug_memory_usage() / (float )(1024);
837 $mem = number_format($mem, 5) . ", " . time();
839 echo "<p>$title: $mem<p>";
841 CRM_Core_Error
::debug_var($title, $mem);
844 echo "<p>$title: $mem<p>";
850 * Take a URL (or partial URL) and make it better.
852 * Currently, URLs pass straight through unchanged unless they are "seriously
853 * malformed" (see http://us2.php.net/parse_url).
856 * The URL to operate on.
860 static function fixURL($url) {
861 $components = parse_url($url);
867 // at some point we'll add code here to make sure the url is not
868 // something that will mess up up, so we need to clean it up here
873 * Make sure a callback is valid in the current context.
875 * @param string $callback
876 * Name of the function to check.
880 static function validCallback($callback) {
881 if (self
::$_callbacks === NULL) {
882 self
::$_callbacks = array();
885 if (!array_key_exists($callback, self
::$_callbacks)) {
886 if (strpos($callback, '::') !== FALSE) {
887 list($className, $methodName) = explode('::', $callback);
888 $fileName = str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
889 // ignore errors if any
890 @include_once
($fileName);
891 if (!class_exists($className)) {
892 self
::$_callbacks[$callback] = FALSE;
895 // instantiate the class
896 $object = new $className();
897 if (!method_exists($object, $methodName)) {
898 self
::$_callbacks[$callback] = FALSE;
901 self
::$_callbacks[$callback] = TRUE;
906 self
::$_callbacks[$callback] = function_exists($callback);
909 return self
::$_callbacks[$callback];
913 * Like PHP's built-in explode(), but always return an array of $limit items.
915 * This serves as a wrapper to the PHP explode() function. In the event that
916 * PHP's explode() returns an array with fewer than $limit elements, pad
917 * the end of the array with NULLs.
919 * @param string $separator
920 * @param string $string
924 static function explode($separator, $string, $limit) {
925 $result = explode($separator, $string, $limit);
926 for ($i = count($result); $i < $limit; $i++
) {
935 * @param bool $addCookie
938 static function checkURL($url, $addCookie = FALSE) {
939 // make a GET request to $url
940 $ch = curl_init($url);
942 curl_setopt($ch, CURLOPT_COOKIE
, http_build_query($_COOKIE));
944 // it's quite alright to use a self-signed cert
945 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, 0);
947 // lets capture the return stuff rather than echo
948 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true );
950 return curl_exec($ch);
954 * Assert that we are running on a particular PHP version.
957 * The major version of PHP that is required.
959 * (optional) Whether to fatally abort if the version requirement is not
960 * met. Defaults to TRUE.
962 * Returns TRUE if the requirement is met, FALSE if the requirement is not
963 * met and we're not aborting due to the failed requirement. If $abort is
964 * TRUE and the requirement fails, this function does not return.
966 static function checkPHPVersion($ver = 5, $abort = TRUE) {
967 $phpVersion = substr(PHP_VERSION
, 0, 1);
968 if ($phpVersion >= $ver) {
973 CRM_Core_Error
::fatal(ts('This feature requires PHP Version %1 or greater',
983 static function formatWikiURL($string, $encode = FALSE) {
984 $items = explode(' ', trim($string), 2);
985 if (count($items) == 2) {
993 $url = $encode ? self
::urlEncode($items[0]) : $items[0];
994 return "<a href=\"$url\">$title</a>";
1000 static function urlEncode($url) {
1001 $items = parse_url($url);
1002 if ($items === FALSE) {
1006 if (empty($items['query'])) {
1010 $items['query'] = urlencode($items['query']);
1012 $url = $items['scheme'] . '://';
1013 if (!empty($items['user'])) {
1014 $url .= "{$items['user']}:{$items['pass']}@";
1017 $url .= $items['host'];
1018 if (!empty($items['port'])) {
1019 $url .= ":{$items['port']}";
1022 $url .= "{$items['path']}?{$items['query']}";
1023 if (!empty($items['fragment'])) {
1024 $url .= "#{$items['fragment']}";
1031 * Return the running civicrm version.
1037 static function version() {
1041 $verFile = implode(DIRECTORY_SEPARATOR
,
1042 array(dirname(__FILE__
), '..', '..', 'civicrm-version.php')
1044 if (file_exists($verFile)) {
1045 require_once ($verFile);
1046 if (function_exists('civicrmVersion')) {
1047 $info = civicrmVersion();
1048 $version = $info['version'];
1052 // svn installs don't have version.txt by default. In that case version.xml should help -
1053 $verFile = implode(DIRECTORY_SEPARATOR
,
1054 array(dirname(__FILE__
), '..', '..', 'xml', 'version.xml')
1056 if (file_exists($verFile)) {
1057 $str = file_get_contents($verFile);
1058 $xmlObj = simplexml_load_string($str);
1059 $version = (string) $xmlObj->version_no
;
1064 if (!CRM_Utils_System
::isVersionFormatValid($version)) {
1065 CRM_Core_Error
::fatal('Unknown codebase version.');
1073 * Determines whether a string is a valid CiviCRM version string.
1075 * @param string $version
1076 * Version string to be checked.
1079 static function isVersionFormatValid($version) {
1080 return preg_match("/^(\d{1,2}\.){2,3}(\d{1,2}|(alpha|beta)\d{1,2})(\.upgrade)?$/", $version);
1084 * Wraps or emulates PHP's getallheaders() function.
1086 static function getAllHeaders() {
1087 if (function_exists('getallheaders')) {
1088 return getallheaders();
1091 // emulate get all headers
1092 // http://www.php.net/manual/en/function.getallheaders.php#66335
1094 foreach ($_SERVER as $name => $value) {
1095 if (substr($name, 0, 5) == 'HTTP_') {
1096 $headers[str_replace(' ',
1098 ucwords(strtolower(str_replace('_',
1111 static function getRequestHeaders() {
1112 if (function_exists('apache_request_headers')) {
1113 return apache_request_headers();
1121 * Determine whether this is an SSL request.
1123 * Note that we inline this function in install/civicrm.php, so if you change
1124 * this function, please go and change the code in the install script as well.
1126 static function isSSL( ) {
1128 (isset($_SERVER['HTTPS']) &&
1129 !empty($_SERVER['HTTPS']) &&
1130 strtolower($_SERVER['HTTPS']) != 'off') ?
true : false;
1135 static function redirectToSSL($abort = FALSE) {
1136 $config = CRM_Core_Config
::singleton();
1137 $req_headers = self
::getRequestHeaders();
1138 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'enableSSL') &&
1140 strtolower(CRM_Utils_Array
::value('X_FORWARDED_PROTO', $req_headers)) != 'https'
1142 // ensure that SSL is enabled on a civicrm url (for cookie reasons etc)
1143 $url = "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
1144 if (!self
::checkURL($url, TRUE)) {
1146 CRM_Core_Error
::fatal('HTTPS is not set up on this machine');
1149 CRM_Core_Session
::setStatus(ts('HTTPS is not set up on this machine'), ts('Warning'), 'alert');
1150 // admin should be the only one following this
1151 // since we dont want the user stuck in a bad place
1155 CRM_Utils_System
::redirect($url);
1160 * Get logged in user's IP address.
1162 * Get IP address from HTTP REMOTE_ADDR header. If the CMS is Drupal then use
1163 * the Drupal function as this also handles reverse proxies (based on proper
1164 * configuration in settings.php)
1166 * @param bool $strictIPV4
1167 * (optional) Whether to return only IPv4 addresses.
1170 * IP address of logged in user.
1172 static function ipAddress($strictIPV4 = TRUE) {
1173 $address = CRM_Utils_Array
::value('REMOTE_ADDR', $_SERVER);
1175 $config = CRM_Core_Config
::singleton();
1176 if ($config->userSystem
->is_drupal
&& function_exists('ip_address')) {
1177 //drupal function handles the server being behind a proxy securely. We still have legacy ipn methods
1178 // that reach this point without bootstrapping hence the check that the fn exists
1179 $address = ip_address();
1183 if ($address == '::1') {
1184 $address = '127.0.0.1';
1187 // when we need to have strictly IPV4 ip address
1188 // convert ipV6 to ipV4
1190 // this converts 'IPV4 mapped IPV6 address' to IPV4
1191 if (filter_var($address, FILTER_VALIDATE_IP
, FILTER_FLAG_IPV6
) && strstr($address, '::ffff:')) {
1192 $address = ltrim($address, '::ffff:');
1200 * Get the referring / previous page URL.
1203 * The previous page URL
1206 static function refererPath() {
1207 return CRM_Utils_Array
::value('HTTP_REFERER', $_SERVER);
1211 * Get the documentation base URL.
1214 * Base URL of the CRM documentation.
1217 static function getDocBaseURL() {
1218 // FIXME: move this to configuration at some stage
1219 return 'http://book.civicrm.org/';
1223 * Returns wiki (alternate) documentation URL base.
1225 * @return string documentation url
1228 static function getWikiBaseURL() {
1229 // FIXME: move this to configuration at some stage
1230 return 'http://wiki.civicrm.org/confluence/display/CRMDOC/';
1234 * Returns URL or link to documentation page, based on provided parameters.
1236 * For use in PHP code.
1237 * WARNING: Always returns URL, if ts function is not defined ($URLonly has
1240 * @param string $page
1241 * Title of documentation wiki page.
1242 * @param boolean $URLonly
1243 * (optional) Whether to return URL only or full HTML link (default).
1244 * @param string $text
1245 * (optional) Text of HTML link (no effect if $URLonly = false).
1246 * @param string $title
1247 * (optional) Tooltip text for HTML link (no effect if $URLonly = false)
1248 * @param string $style
1249 * (optional) Style attribute value for HTML link (no effect if $URLonly = false)
1252 * URL or link to documentation page, based on provided parameters.
1255 static function docURL2($page, $URLonly = FALSE, $text = NULL, $title = NULL, $style = NULL, $resource = NULL) {
1256 // if ts function doesn't exist, it means that CiviCRM hasn't been fully initialised yet -
1257 // return just the URL, no matter what other parameters are defined
1258 if (!function_exists('ts')) {
1259 if ($resource == 'wiki') {
1260 $docBaseURL = self
::getWikiBaseURL();
1262 $docBaseURL = self
::getDocBaseURL();
1264 return $docBaseURL . str_replace(' ', '+', $page);
1269 'URLonly' => $URLonly,
1273 'resource' => $resource,
1275 return self
::docURL($params);
1280 * Returns URL or link to documentation page, based on provided parameters.
1282 * For use in templates code.
1284 * @param array $params
1285 * An array of parameters (see CRM_Utils_System::docURL2 method for names)
1288 * URL or link to documentation page, based on provided parameters.
1291 static function docURL($params) {
1293 if (!isset($params['page'])) {
1297 if (CRM_Utils_Array
::value('resource', $params) == 'wiki') {
1298 $docBaseURL = self
::getWikiBaseURL();
1300 $docBaseURL = self
::getDocBaseURL();
1303 if (!isset($params['title']) or $params['title'] === NULL) {
1304 $params['title'] = ts('Opens documentation in a new window.');
1307 if (!isset($params['text']) or $params['text'] === NULL) {
1308 $params['text'] = ts('(learn more...)');
1311 if (!isset($params['style']) ||
$params['style'] === NULL) {
1315 $style = "style=\"{$params['style']}\"";
1318 $link = $docBaseURL . str_replace(' ', '+', $params['page']);
1320 if (isset($params['URLonly']) && $params['URLonly'] == TRUE) {
1324 return "<a href=\"{$link}\" $style target=\"_blank\" class=\"crm-doc-link no-popup\" title=\"{$params['title']}\">{$params['text']}</a>";
1329 * Get the locale set in the hosting CMS
1332 * The used locale or null for none.
1334 static function getUFLocale() {
1335 $config = CRM_Core_Config
::singleton();
1336 return $config->userSystem
->getUFLocale();
1340 * Execute external or internal URLs and return server response.
1342 * @param string $url
1344 * @param bool $addCookie
1345 * Whether to provide a cookie. Should be true to access internal URLs.
1348 * Response from URL.
1350 static function getServerResponse($url, $addCookie = TRUE) {
1351 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1352 require_once 'HTTP/Request.php';
1353 $request = new HTTP_Request($url);
1356 foreach ($_COOKIE as $name => $value) {
1357 $request->addCookie($name, $value);
1361 if (isset($_SERVER['AUTH_TYPE'])) {
1362 $request->setBasicAuth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
1365 $config = CRM_Core_Config
::singleton();
1366 if ($config->userFramework
== 'WordPress') {
1367 session_write_close();
1370 $request->sendRequest();
1371 $response = $request->getResponseBody();
1378 static function isDBVersionValid(&$errorMessage) {
1379 $dbVersion = CRM_Core_BAO_Domain
::version();
1382 // if db.ver missing
1383 $errorMessage = ts('Version information found to be missing in database. You will need to determine the correct version corresponding to your current database state.');
1386 elseif (!CRM_Utils_System
::isVersionFormatValid($dbVersion)) {
1387 $errorMessage = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
1390 elseif (stripos($dbVersion, 'upgrade')) {
1391 // if db.ver indicates a partially upgraded db
1392 $upgradeUrl = CRM_Utils_System
::url("civicrm/upgrade", "reset=1");
1393 $errorMessage = ts('Database check failed - the database looks to have been partially upgraded. You may want to reload the database with the backup and try the <a href=\'%1\'>upgrade process</a> again.', array(1 => $upgradeUrl));
1397 $codeVersion = CRM_Utils_System
::version();
1399 // if db.ver < code.ver, time to upgrade
1400 if (version_compare($dbVersion, $codeVersion) < 0) {
1401 $upgradeUrl = CRM_Utils_System
::url("civicrm/upgrade", "reset=1");
1402 $errorMessage = ts('New codebase version detected. You might want to visit <a href=\'%1\'>upgrade screen</a> to upgrade the database.', array(1 => $upgradeUrl));
1406 // if db.ver > code.ver, sth really wrong
1407 if (version_compare($dbVersion, $codeVersion) > 0) {
1408 $errorMessage = '<p>' . ts('Your database is marked with an unexpected version number: %1. The v%2 codebase may not be compatible with your database state. You will need to determine the correct version corresponding to your current database state. You may want to revert to the codebase you were using until you resolve this problem.',
1409 array(1 => $dbVersion, 2 => $codeVersion)
1411 $errorMessage .= "<p>" . ts('OR if this is a manual install from git, you might want to fix civicrm-version.php file.') . "</p>";
1415 // FIXME: there should be another check to make sure version is in valid format - X.Y.alpha_num
1421 * Exit with provided exit code.
1423 * @param int $status
1424 * (optional) Code with which to exit.
1426 static function civiExit($status = 0) {
1427 // move things to CiviCRM cache as needed
1428 CRM_Core_Session
::storeSessionObjects();
1434 * Reset the various system caches and some important static variables.
1436 static function flushCache( ) {
1437 // flush out all cache entries so we can reload new data
1438 // a bit aggressive, but livable for now
1439 $cache = CRM_Utils_Cache
::singleton();
1442 // also reset the various static memory caches
1444 // reset the memory or array cache
1445 CRM_Core_BAO_Cache
::deleteGroup('contact fields', NULL, FALSE);
1448 CRM_ACL_BAO_Cache
::resetCache();
1450 // reset various static arrays used here
1451 CRM_Contact_BAO_Contact
::$_importableFields =
1452 CRM_Contact_BAO_Contact
::$_exportableFields =
1453 CRM_Contribute_BAO_Contribution
::$_importableFields =
1454 CRM_Contribute_BAO_Contribution
::$_exportableFields =
1455 CRM_Pledge_BAO_Pledge
::$_exportableFields =
1456 CRM_Contribute_BAO_Query
::$_contributionFields =
1457 CRM_Core_BAO_CustomField
::$_importFields =
1458 CRM_Core_BAO_Cache
::$_cache =
1459 CRM_Core_DAO
::$_dbColumnValueCache = NULL;
1461 CRM_Core_OptionGroup
::flushAll();
1462 CRM_Utils_PseudoConstant
::flushAll();
1466 * Load CMS bootstrap.
1468 * @param array $params
1469 * Array with uid name and pass
1470 * @param bool $loadUser
1471 * Boolean load user or not.
1472 * @param bool $throwError
1475 static function loadBootStrap($params = array(
1476 ), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
1477 if (!is_array($params)) {
1480 $config = CRM_Core_Config
::singleton();
1481 return $config->userSystem
->loadBootStrap($params, $loadUser, $throwError, $realPath);
1485 * Check if user is logged in.
1489 public static function isUserLoggedIn() {
1490 $config = CRM_Core_Config
::singleton();
1491 return $config->userSystem
->isUserLoggedIn();
1495 * Get current logged in user id.
1498 * ufId, currently logged in user uf id.
1500 public static function getLoggedInUfID() {
1501 $config = CRM_Core_Config
::singleton();
1502 return $config->userSystem
->getLoggedInUfID();
1507 static function baseCMSURL() {
1508 static $_baseURL = NULL;
1510 $config = CRM_Core_Config
::singleton();
1511 $_baseURL = $userFrameworkBaseURL = $config->userFrameworkBaseURL
;
1513 if ($config->userFramework
== 'Joomla') {
1515 // we need to remove the administrator/ from the end
1516 $_baseURL = str_replace("/administrator/", "/", $userFrameworkBaseURL);
1520 global $civicrm_root;
1521 if (strpos($civicrm_root,
1522 DIRECTORY_SEPARATOR
. 'sites' .
1523 DIRECTORY_SEPARATOR
. 'all' .
1524 DIRECTORY_SEPARATOR
. 'modules'
1526 $startPos = strpos($civicrm_root,
1527 DIRECTORY_SEPARATOR
. 'sites' . DIRECTORY_SEPARATOR
1529 $endPos = strpos($civicrm_root,
1530 DIRECTORY_SEPARATOR
. 'modules' . DIRECTORY_SEPARATOR
1532 if ($startPos && $endPos) {
1533 // if component is in sites/SITENAME/modules
1534 $siteName = substr($civicrm_root,
1536 $endPos - $startPos - 7
1539 $_baseURL = $userFrameworkBaseURL . "sites/$siteName/";
1548 * Given a URL, return a relative URL if possible.
1550 * @param string $url
1553 static function relativeURL($url) {
1554 // check if url is relative, if so return immediately
1555 if (substr($url, 0, 4) != 'http') {
1559 // make everything relative from the baseFilePath
1560 $baseURL = self
::baseCMSURL();
1562 // check if baseURL is a substr of $url, if so
1563 // return rest of string
1564 if (substr($url, 0, strlen($baseURL)) == $baseURL) {
1565 return substr($url, strlen($baseURL));
1568 // return the original value
1573 * Produce an absolute URL from a possibly-relative URL.
1575 * @param string $url
1576 * @param bool $remoteLanguagePart
1579 static function absoluteURL($url, $removeLanguagePart = FALSE) {
1580 // check if url is already absolute, if so return immediately
1581 if (substr($url, 0, 4) == 'http') {
1585 // make everything absolute from the baseFileURL
1586 $baseURL = self
::baseCMSURL();
1588 //CRM-7622: drop the language from the URL if requested (and it’s there)
1589 $config = CRM_Core_Config
::singleton();
1590 if ($removeLanguagePart) {
1591 $baseURL = self
::languageNegotiationURL($baseURL, FALSE, TRUE);
1594 return $baseURL . $url;
1598 * Function to clean url, replaces first '&' with '?'
1600 * @param string $url
1602 * @return string $url, clean url
1604 static function cleanUrl($url) {
1609 if ($pos = strpos($url, '&')) {
1610 $url = substr_replace($url, '?', $pos, 1);
1617 * Format the url as per language Negotiation.
1619 * @param string $url
1621 * @return string $url, formatted url.
1623 static function languageNegotiationURL($url,
1624 $addLanguagePart = TRUE,
1625 $removeLanguagePart = FALSE
1627 $config = &CRM_Core_Config
::singleton();
1628 return $config->userSystem
->languageNegotiationURL($url, $addLanguagePart, $removeLanguagePart);
1632 * Append the contents of an 'extra' smarty template file if it is present in
1633 * the custom template directory. This does not work if there are
1634 * multiple custom template directories
1636 * @param string $fileName
1637 * The name of the tpl file that we are processing.
1638 * @param string $content
1639 * The current content string. May be modified by this function.
1640 * @param string $overideFileName
1641 * (optional) Sent by contribution/event reg/profile pages which uses a id
1642 * specific extra file name if present.
1644 static function appendTPLFile($fileName,
1646 $overideFileName = NULL
1648 $template = CRM_Core_Smarty
::singleton();
1649 if ($overideFileName) {
1650 $additionalTPLFile = $overideFileName;
1653 $additionalTPLFile = str_replace('.tpl', '.extra.tpl', $fileName);
1656 if ($template->template_exists($additionalTPLFile)) {
1657 $content .= $template->fetch($additionalTPLFile);
1662 * Get a list of all files that are found within the directories
1663 * that are the result of appending the provided relative path to
1664 * each component of the PHP include path.
1666 * @author Ken Zalewski
1668 * @param string $relpath
1669 * A relative path, typically pointing to a directory with multiple class
1673 * An array of files that exist in one or more of the directories that are
1674 * referenced by the relative path when appended to each element of the PHP
1678 static function listIncludeFiles($relpath) {
1679 $file_list = array();
1680 $inc_dirs = explode(PATH_SEPARATOR
, get_include_path());
1681 foreach ($inc_dirs as $inc_dir) {
1682 $target_dir = $inc_dir . DIRECTORY_SEPARATOR
. $relpath;
1683 if (is_dir($target_dir)) {
1684 $cur_list = scandir($target_dir);
1685 foreach ($cur_list as $fname) {
1686 if ($fname != '.' && $fname != '..') {
1687 $file_list[$fname] = $fname;
1694 // listIncludeFiles()
1697 * Get a list of all "plugins" (PHP classes that implement a piece of
1698 * functionality using a well-defined interface) that are found in a
1699 * particular CiviCRM directory (both custom and core are searched).
1701 * @author Ken Zalewski
1703 * @param string $relpath
1704 * A relative path referencing a directory that contains one or more
1706 * @param string $fext
1707 * (optional) Only files with this extension will be considered to be
1709 * @param array $skipList
1710 * (optional) List of files to skip.
1713 * List of plugins, where the plugin name is both the key and the value of
1717 static function getPluginList($relpath, $fext = '.php', $skipList = array(
1719 $fext_len = strlen($fext);
1721 $inc_files = CRM_Utils_System
::listIncludeFiles($relpath);
1722 foreach ($inc_files as $inc_file) {
1723 if (substr($inc_file, 0 - $fext_len) == $fext) {
1724 $plugin_name = substr($inc_file, 0, 0 - $fext_len);
1725 if (!in_array($plugin_name, $skipList)) {
1726 $plugins[$plugin_name] = $plugin_name;
1737 static function executeScheduledJobs() {
1738 $facility = new CRM_Core_JobManager();
1739 $facility->execute(FALSE);
1741 $redirectUrl = self
::url('civicrm/admin/job', 'reset=1');
1743 CRM_Core_Session
::setStatus(
1744 ts('Scheduled jobs have been executed according to individual timing settings. Please check log for messages.'),
1745 ts('Complete'), 'success');
1747 CRM_Utils_System
::redirect($redirectUrl);
1751 * Evaluate any tokens in a URL.
1753 * @param string|FALSE $url
1754 * @return string|FALSE
1756 public static function evalUrl($url) {
1757 if ($url === FALSE) {
1761 $config = CRM_Core_Config
::singleton();
1763 '{ver}' => CRM_Utils_System
::version(),
1764 '{uf}' => $config->userFramework
,
1765 '{php}' => phpversion(),
1766 '{sid}' => md5('sid_' . (defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: '') . '_' . $config->userFrameworkBaseURL
),
1767 '{baseUrl}' => $config->userFrameworkBaseURL
,
1768 '{lang}' => $config->lcMessages
,
1769 '{co}' => $config->defaultContactCountry
,
1771 foreach (array_keys($vars) as $k) {
1772 $vars[$k] = urlencode($vars[$k]);
1774 return strtr($url, $vars);
1780 * Determine whether this is a developmental system.
1784 static function isDevelopment() {
1785 static $cache = NULL;
1786 if ($cache === NULL) {
1787 global $civicrm_root;
1788 $cache = file_exists("{$civicrm_root}/.svn") ||
file_exists("{$civicrm_root}/.git");