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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
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 bool|string $absolute
64 * (optional) Whether to return an absolute URL.
69 public static function makeURL($urlVar, $includeReset = FALSE, $includeForce = TRUE, $path = NULL, $absolute = FALSE) {
71 $config = CRM_Core_Config
::singleton();
72 $path = CRM_Utils_Array
::value($config->userFrameworkURLVar
, $_GET);
81 CRM_Utils_System
::getLinksUrl($urlVar, $includeReset, $includeForce),
87 * Get the query string and clean it up.
89 * Strips some variables that should not be propagated, specifically variables
90 * like 'reset'. Also strips any side-affect actions (e.g. export).
92 * This function is copied mostly verbatim from Pager.php (_getLinksUrl)
94 * @param string $urlVar
95 * The URL variable being considered (e.g. crmPageID, crmSortID etc).
96 * @param bool $includeReset
97 * (optional) By default this is FALSE, meaning that the reset parameter
98 * is skipped. Set to TRUE to leave the reset parameter as-is.
99 * @param bool $includeForce
101 * @param bool $skipUFVar
106 public static function getLinksUrl($urlVar, $includeReset = FALSE, $includeForce = TRUE, $skipUFVar = TRUE) {
107 // Sort out query string to prevent messy urls
108 $querystring = array();
112 if (!empty($_SERVER['QUERY_STRING'])) {
113 $qs = explode('&', str_replace('&', '&', $_SERVER['QUERY_STRING']));
114 for ($i = 0, $cnt = count($qs); $i < $cnt; $i++
) {
115 // check first if exist a pair
116 if (strstr($qs[$i], '=') !== FALSE) {
117 list($name, $value) = explode('=', $qs[$i]);
118 if ($name != $urlVar) {
119 $name = rawurldecode($name);
120 //check for arrays in parameters: site.php?foo[]=1&foo[]=2&foo[]=3
121 if ((strpos($name, '[') !== FALSE) &&
122 (strpos($name, ']') !== FALSE)
142 // Ok this is a big assumption but usually works
143 // If we are in snippet mode, retain the 'section' param, if not, get rid
145 if (!empty($qs['snippet'])) {
146 unset($qs['snippet']);
149 unset($qs['section']);
153 $config = CRM_Core_Config
::singleton();
154 unset($qs[$config->userFrameworkURLVar
]);
157 foreach ($qs as $name => $value) {
158 if ($name != 'reset' ||
$includeReset) {
159 $querystring[] = $name . '=' . $value;
163 $querystring = array_merge($querystring, array_unique($arrays));
165 $url = implode('&', $querystring);
167 $url .= (!empty($querystring) ?
'&' : '') . $urlVar . '=';
174 * If we are using a theming system, invoke theme, else just print the
177 * @param string $content
178 * The content that will be themed.
180 * (optional) Are we displaying to the screen or bypassing theming?
181 * @param bool $maintenance
182 * (optional) For maintenance mode.
186 public static function theme(
191 $config = &CRM_Core_Config
::singleton();
192 return $config->userSystem
->theme($content, $print, $maintenance);
196 * Generate a query string if input is an array.
198 * @param array|string $query
201 public static function makeQueryString($query) {
202 if (is_array($query)) {
204 foreach ($query as $key => $value) {
205 $buf .= ($buf ?
'&' : '') . urlencode($key) . '=' . urlencode($value);
213 * Generate an internal CiviCRM URL.
215 * @param string $path
216 * The path being linked to, such as "civicrm/add".
217 * @param array|string $query
218 * A query string to append to the link, or an array of key-value pairs.
219 * @param bool $absolute
220 * Whether to force the output to be an absolute link (beginning with a
221 * URI-scheme such as 'http:'). Useful for links that will be displayed
222 * outside the site, such as in an RSS feed.
223 * @param string $fragment
224 * A fragment identifier (named anchor) to append to the link.
226 * @param bool $htmlize
227 * @param bool $frontend
228 * @param bool $forceBackend
230 * An HTML string containing a link to the given path.
232 public static function url(
239 $forceBackend = FALSE
241 $query = self
::makeQueryString($query);
243 // we have a valid query and it has not yet been transformed
244 if ($htmlize && !empty($query) && strpos($query, '&') === FALSE) {
245 $query = htmlentities($query);
248 $config = CRM_Core_Config
::singleton();
249 return $config->userSystem
->url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
256 * @param bool $absolute
257 * @param null $fragment
258 * @param bool $htmlize
259 * @param bool $frontend
260 * @param bool $forceBackend
264 public static function href(
265 $text, $path = NULL, $query = NULL, $absolute = TRUE,
266 $fragment = NULL, $htmlize = TRUE, $frontend = FALSE, $forceBackend = FALSE
268 $url = self
::url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
269 return "<a href=\"$url\">$text</a>";
275 public static function permissionDenied() {
276 $config = CRM_Core_Config
::singleton();
277 return $config->userSystem
->permissionDenied();
283 public static function logout() {
284 $config = CRM_Core_Config
::singleton();
285 return $config->userSystem
->logout();
289 * this is a very drupal specific function for now.
291 public static function updateCategories() {
292 $config = CRM_Core_Config
::singleton();
293 if ($config->userSystem
->is_drupal
) {
294 $config->userSystem
->updateCategories();
299 * What menu path are we currently on. Called for the primary tpl
302 * the current menu path
304 public static function currentPath() {
305 $config = CRM_Core_Config
::singleton();
306 return trim(CRM_Utils_Array
::value($config->userFrameworkURLVar
, $_GET), '/');
310 * called from a template to compose a url.
312 * @param array $params
313 * List of parameters.
318 public static function crmURL($params) {
319 $p = CRM_Utils_Array
::value('p', $params);
321 $p = self
::currentPath();
326 CRM_Utils_Array
::value('q', $params),
327 CRM_Utils_Array
::value('a', $params, FALSE),
328 CRM_Utils_Array
::value('f', $params),
329 CRM_Utils_Array
::value('h', $params, TRUE),
330 CRM_Utils_Array
::value('fe', $params, FALSE),
331 CRM_Utils_Array
::value('fb', $params, FALSE)
336 * Sets the title of the page.
338 * @param string $title
339 * @param string $pageTitle
341 public static function setTitle($title, $pageTitle = NULL) {
342 self
::$title = $title;
343 $config = CRM_Core_Config
::singleton();
344 return $config->userSystem
->setTitle($title, $pageTitle);
348 * Figures and sets the userContext.
350 * Uses the referer if valid else uses the default.
352 * @param array $names
353 * Refererer should match any str in this array.
354 * @param string $default
355 * (optional) The default userContext if no match found.
357 public static function setUserContext($names, $default = NULL) {
360 $session = CRM_Core_Session
::singleton();
361 $referer = CRM_Utils_Array
::value('HTTP_REFERER', $_SERVER);
363 if ($referer && !empty($names)) {
364 foreach ($names as $name) {
365 if (strstr($referer, $name)) {
373 $session->pushUserContext($url);
378 * Gets a class name for an object.
380 * @param object $object
381 * Object whose class name is needed.
384 * The class name of the object.
386 public static function getClassName($object) {
387 return get_class($object);
391 * Redirect to another URL.
394 * The URL to provide to the browser via the Location header.
396 public static function redirect($url = NULL) {
398 $url = self
::url('civicrm/dashboard', 'reset=1');
401 // replace the & characters with &
402 // this is kinda hackish but not sure how to do it right
403 $url = str_replace('&', '&', $url);
405 // If we are in a json context, respond appropriately
406 if (CRM_Utils_Array
::value('snippet', $_GET) === 'json') {
407 CRM_Core_Page_AJAX
::returnJsonResponse(array(
408 'status' => 'redirect',
409 'userContext' => $url,
413 header('Location: ' . $url);
418 * Redirect to another URL using JavaScript.
420 * Use an html based file with javascript embedded to redirect to another url
421 * This prevent the too many redirect errors emitted by various browsers
424 * (optional) The destination URL.
425 * @param string $title
426 * (optional) The page title to use for the redirect page.
427 * @param string $message
428 * (optional) The message to provide in the body of the redirect page.
430 public static function jsRedirect(
436 $url = self
::url('civicrm/dashboard', 'reset=1');
440 $title = ts('CiviCRM task in progress');
444 $message = ts('A long running CiviCRM task is currently in progress. This message will be refreshed till the task is completed');
447 // replace the & characters with &
448 // this is kinda hackish but not sure how to do it right
449 $url = str_replace('&', '&', $url);
451 $template = CRM_Core_Smarty
::singleton();
452 $template->assign('redirectURL', $url);
453 $template->assign('title', $title);
454 $template->assign('message', $message);
456 $html = $template->fetch('CRM/common/redirectJS.tpl');
464 * Append an additional breadcrumb tag to the existing breadcrumbs.
466 * @param $breadCrumbs
468 public static function appendBreadCrumb($breadCrumbs) {
469 $config = CRM_Core_Config
::singleton();
470 return $config->userSystem
->appendBreadCrumb($breadCrumbs);
474 * Reset an additional breadcrumb tag to the existing breadcrumb.
476 public static function resetBreadCrumb() {
477 $config = CRM_Core_Config
::singleton();
478 return $config->userSystem
->resetBreadCrumb();
482 * Append a string to the head of the HTML file.
486 public static function addHTMLHead($bc) {
487 $config = CRM_Core_Config
::singleton();
488 return $config->userSystem
->addHTMLHead($bc);
492 * Determine the post URL for a form.
495 * The default action if one is pre-specified.
498 * The URL to post the form.
500 public static function postURL($action) {
501 $config = CRM_Core_Config
::singleton();
502 return $config->userSystem
->postURL($action);
506 * Rewrite various system URLs to https.
508 public static function mapConfigToSSL() {
509 $config = CRM_Core_Config
::singleton();
510 $config->userFrameworkResourceURL
= str_replace('http://', 'https://', $config->userFrameworkResourceURL
);
511 $config->resourceBase
= $config->userFrameworkResourceURL
;
513 if (!empty($config->extensionsURL
)) {
514 $config->extensionsURL
= str_replace('http://', 'https://', $config->extensionsURL
);
517 return $config->userSystem
->mapConfigToSSL();
521 * Get the base URL of the system.
525 public static function baseURL() {
526 $config = CRM_Core_Config
::singleton();
527 return $config->userFrameworkBaseURL
;
532 public static function authenticateAbort($message, $abort) {
544 * (optional) Whether to exit; defaults to true.
548 public 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",
591 * @param bool $storeInSession
592 * @param bool $loadCMSBootstrap
593 * @param bool $requireKey
597 public static function authenticateScript($abort = TRUE, $name = NULL, $pass = NULL, $storeInSession = TRUE, $loadCMSBootstrap = TRUE, $requireKey = TRUE) {
598 // auth to make sure the user has a login/password to do a shell operation
599 // later on we'll link this to acl's
601 $name = trim(CRM_Utils_Array
::value('name', $_REQUEST));
602 $pass = trim(CRM_Utils_Array
::value('pass', $_REQUEST));
605 // its ok to have an empty password
607 return self
::authenticateAbort(
608 "ERROR: You need to send a valid user name and password to execute this file\n",
613 if ($requireKey && !self
::authenticateKey($abort)) {
617 $result = CRM_Utils_System
::authenticate($name, $pass, $loadCMSBootstrap);
619 return self
::authenticateAbort(
620 "ERROR: Invalid username and/or password\n",
624 elseif ($storeInSession) {
625 // lets store contact id and user id in session
626 list($userID, $ufID, $randomNumber) = $result;
627 if ($userID && $ufID) {
628 $config = CRM_Core_Config
::singleton();
629 $config->userSystem
->setUserSession(array($userID, $ufID));
632 return self
::authenticateAbort(
633 "ERROR: Unexpected error, could not match userID and contactID",
643 * Authenticate the user against the uf db.
645 * In case of successful authentication, returns an array consisting of
646 * (contactID, ufID, unique string). Returns FALSE if authentication is
649 * @param string $name
651 * @param string $password
653 * @param bool $loadCMSBootstrap
656 * @return false|array
658 public static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
659 $config = CRM_Core_Config
::singleton();
661 /* Before we do any loading, let's start the session and write to it.
662 * We typically call authenticate only when we need to bootstrap the CMS
663 * directly via Civi and hence bypass the normal CMS auth and bootstrap
664 * process typically done in CLI and cron scripts. See: CRM-12648
666 $session = CRM_Core_Session
::singleton();
667 $session->set('civicrmInitSession', TRUE);
669 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
670 return $config->userSystem
->authenticate($name, $password, $loadCMSBootstrap, $realPath);
674 * Set a message in the UF to display to a user.
676 * @param string $message
677 * The message to set.
679 public static function setUFMessage($message) {
680 $config = CRM_Core_Config
::singleton();
681 return $config->userSystem
->setMessage($message);
686 * Determine whether a value is null-ish.
689 * The value to check for null.
692 public static function isNull($value) {
693 // FIXME: remove $value = 'null' string test when we upgrade our DAO code to handle passing null in a better way.
694 if (!isset($value) ||
$value === NULL ||
$value === '' ||
$value === 'null') {
697 if (is_array($value)) {
698 // @todo Reuse of the $value variable = asking for trouble.
699 foreach ($value as $key => $value) {
700 if (!self
::isNull($value)) {
710 * Obscure all but the last few digits of a credit card number.
712 * @param string $number
713 * The credit card number to obscure.
715 * (optional) The number of digits to preserve unmodified.
717 * The obscured credit card number.
719 public static function mungeCreditCard($number, $keep = 4) {
720 $number = trim($number);
721 if (empty($number)) {
724 $replace = str_repeat('*', strlen($number) - $keep);
725 return substr_replace($number, $replace, 0, -$keep);
729 * Determine which PHP modules are loaded.
733 public static function parsePHPModules() {
735 phpinfo(INFO_MODULES
);
736 $s = ob_get_contents();
739 $s = strip_tags($s, '<h2><th><td>');
740 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/', "<info>\\1</info>", $s);
741 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/', "<info>\\1</info>", $s);
742 $vTmp = preg_split('/(<h2>[^<]+<\/h2>)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE
);
744 for ($i = 1; $i < count($vTmp); $i++
) {
745 if (preg_match('/<h2>([^<]+)<\/h2>/', $vTmp[$i], $vMat)) {
746 $vName = trim($vMat[1]);
747 $vTmp2 = explode("\n", $vTmp[$i +
1]);
748 foreach ($vTmp2 as $vOne) {
749 $vPat = '<info>([^<]+)<\/info>';
750 $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
751 $vPat2 = "/$vPat\s*$vPat/";
753 if (preg_match($vPat3, $vOne, $vMat)) {
754 $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]), trim($vMat[3]));
757 elseif (preg_match($vPat2, $vOne, $vMat)) {
758 $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
767 * Get a setting from a loaded PHP module.
769 public static function getModuleSetting($pModuleName, $pSetting) {
770 $vModules = self
::parsePHPModules();
771 return $vModules[$pModuleName][$pSetting];
778 * @return mixed|string
780 public static function memory($title = NULL) {
783 $pid = posix_getpid();
786 $memory = str_replace("\n", '', shell_exec("ps -p" . $pid . " -o rss="));
787 $memory .= ", " . time();
789 CRM_Core_Error
::debug_var($title, $memory);
795 * @param string $name
796 * @param string $mimeType
799 * @param bool $output
800 * @param string $disposition
802 public static function download(
803 $name, $mimeType, &$buffer,
806 $disposition = 'attachment'
808 $now = gmdate('D, d M Y H:i:s') . ' GMT';
810 header('Content-Type: ' . $mimeType);
811 header('Expires: ' . $now);
813 // lem9 & loic1: IE need specific headers
814 $isIE = strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE');
816 $fileString = "filename=\"{$name}.{$ext}\"";
819 $fileString = "filename=\"{$name}\"";
822 header("Content-Disposition: inline; $fileString");
823 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
824 header('Pragma: public');
827 header("Content-Disposition: $disposition; $fileString");
828 header('Pragma: no-cache');
838 * Gather and print (and possibly log) amount of used memory.
840 * @param string $title
842 * (optional) Whether to log the memory usage information.
844 public static function xMemory($title = NULL, $log = FALSE) {
845 $mem = (float ) xdebug_memory_usage() / (float ) (1024);
846 $mem = number_format($mem, 5) . ", " . time();
848 echo "<p>$title: $mem<p>";
850 CRM_Core_Error
::debug_var($title, $mem);
853 echo "<p>$title: $mem<p>";
859 * Take a URL (or partial URL) and make it better.
861 * Currently, URLs pass straight through unchanged unless they are "seriously
862 * malformed" (see http://us2.php.net/parse_url).
865 * The URL to operate on.
869 public static function fixURL($url) {
870 $components = parse_url($url);
876 // at some point we'll add code here to make sure the url is not
877 // something that will mess up up, so we need to clean it up here
882 * Make sure a callback is valid in the current context.
884 * @param string $callback
885 * Name of the function to check.
889 public static function validCallback($callback) {
890 if (self
::$_callbacks === NULL) {
891 self
::$_callbacks = array();
894 if (!array_key_exists($callback, self
::$_callbacks)) {
895 if (strpos($callback, '::') !== FALSE) {
896 list($className, $methodName) = explode('::', $callback);
897 $fileName = str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
898 // ignore errors if any
899 @include_once
$fileName;
900 if (!class_exists($className)) {
901 self
::$_callbacks[$callback] = FALSE;
904 // instantiate the class
905 $object = new $className();
906 if (!method_exists($object, $methodName)) {
907 self
::$_callbacks[$callback] = FALSE;
910 self
::$_callbacks[$callback] = TRUE;
915 self
::$_callbacks[$callback] = function_exists($callback);
918 return self
::$_callbacks[$callback];
922 * Like PHP's built-in explode(), but always return an array of $limit items.
924 * This serves as a wrapper to the PHP explode() function. In the event that
925 * PHP's explode() returns an array with fewer than $limit elements, pad
926 * the end of the array with NULLs.
928 * @param string $separator
929 * @param string $string
933 public static function explode($separator, $string, $limit) {
934 $result = explode($separator, $string, $limit);
935 for ($i = count($result); $i < $limit; $i++
) {
944 * @param bool $addCookie
949 public static function checkURL($url, $addCookie = FALSE) {
950 // make a GET request to $url
951 $ch = curl_init($url);
953 curl_setopt($ch, CURLOPT_COOKIE
, http_build_query($_COOKIE));
955 // it's quite alright to use a self-signed cert
956 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, 0);
958 // lets capture the return stuff rather than echo
959 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, TRUE);
961 // CRM-13227, CRM-14744: only return the SSL error status
962 return (curl_exec($ch) !== FALSE);
966 * Assert that we are running on a particular PHP version.
969 * The major version of PHP that is required.
971 * (optional) Whether to fatally abort if the version requirement is not
972 * met. Defaults to TRUE.
974 * Returns TRUE if the requirement is met, FALSE if the requirement is not
975 * met and we're not aborting due to the failed requirement. If $abort is
976 * TRUE and the requirement fails, this function does not return.
978 public static function checkPHPVersion($ver = 5, $abort = TRUE) {
979 $phpVersion = substr(PHP_VERSION
, 0, 1);
980 if ($phpVersion >= $ver) {
985 CRM_Core_Error
::fatal(ts('This feature requires PHP Version %1 or greater',
994 * @param bool $encode
998 public static function formatWikiURL($string, $encode = FALSE) {
999 $items = explode(' ', trim($string), 2);
1000 if (count($items) == 2) {
1008 $url = $encode ? self
::urlEncode($items[0]) : $items[0];
1009 return "<a href=\"$url\">$title</a>";
1013 * @param string $url
1015 * @return null|string
1017 public static function urlEncode($url) {
1018 $items = parse_url($url);
1019 if ($items === FALSE) {
1023 if (empty($items['query'])) {
1027 $items['query'] = urlencode($items['query']);
1029 $url = $items['scheme'] . '://';
1030 if (!empty($items['user'])) {
1031 $url .= "{$items['user']}:{$items['pass']}@";
1034 $url .= $items['host'];
1035 if (!empty($items['port'])) {
1036 $url .= ":{$items['port']}";
1039 $url .= "{$items['path']}?{$items['query']}";
1040 if (!empty($items['fragment'])) {
1041 $url .= "#{$items['fragment']}";
1048 * Return the running civicrm version.
1053 public static function version() {
1057 $verFile = implode(DIRECTORY_SEPARATOR
,
1058 array(dirname(__FILE__
), '..', '..', 'civicrm-version.php')
1060 if (file_exists($verFile)) {
1061 require_once $verFile;
1062 if (function_exists('civicrmVersion')) {
1063 $info = civicrmVersion();
1064 $version = $info['version'];
1068 // svn installs don't have version.txt by default. In that case version.xml should help -
1069 $verFile = implode(DIRECTORY_SEPARATOR
,
1070 array(dirname(__FILE__
), '..', '..', 'xml', 'version.xml')
1072 if (file_exists($verFile)) {
1073 $str = file_get_contents($verFile);
1074 $xmlObj = simplexml_load_string($str);
1075 $version = (string) $xmlObj->version_no
;
1080 if (!CRM_Utils_System
::isVersionFormatValid($version)) {
1081 CRM_Core_Error
::fatal('Unknown codebase version.');
1089 * Determines whether a string is a valid CiviCRM version string.
1091 * @param string $version
1092 * Version string to be checked.
1095 public static function isVersionFormatValid($version) {
1096 return preg_match("/^(\d{1,2}\.){2,3}(\d{1,2}|(alpha|beta)\d{1,2})(\.upgrade)?$/", $version);
1100 * Wraps or emulates PHP's getallheaders() function.
1102 public static function getAllHeaders() {
1103 if (function_exists('getallheaders')) {
1104 return getallheaders();
1107 // emulate get all headers
1108 // http://www.php.net/manual/en/function.getallheaders.php#66335
1110 foreach ($_SERVER as $name => $value) {
1111 if (substr($name, 0, 5) == 'HTTP_') {
1112 $headers[str_replace(' ',
1114 ucwords(strtolower(str_replace('_',
1127 public static function getRequestHeaders() {
1128 if (function_exists('apache_request_headers')) {
1129 return apache_request_headers();
1137 * Determine whether this is an SSL request.
1139 * Note that we inline this function in install/civicrm.php, so if you change
1140 * this function, please go and change the code in the install script as well.
1142 public static function isSSL() {
1144 (isset($_SERVER['HTTPS']) &&
1145 !empty($_SERVER['HTTPS']) &&
1146 strtolower($_SERVER['HTTPS']) != 'off') ?
TRUE : FALSE;
1151 public static function redirectToSSL($abort = FALSE) {
1152 $config = CRM_Core_Config
::singleton();
1153 $req_headers = self
::getRequestHeaders();
1154 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'enableSSL') &&
1156 strtolower(CRM_Utils_Array
::value('X_FORWARDED_PROTO', $req_headers)) != 'https'
1158 // ensure that SSL is enabled on a civicrm url (for cookie reasons etc)
1159 $url = "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
1160 if (!self
::checkURL($url, TRUE)) {
1162 CRM_Core_Error
::fatal('HTTPS is not set up on this machine');
1165 CRM_Core_Session
::setStatus(ts('HTTPS is not set up on this machine'), ts('Warning'), 'alert');
1166 // admin should be the only one following this
1167 // since we dont want the user stuck in a bad place
1171 CRM_Utils_System
::redirect($url);
1176 * Get logged in user's IP address.
1178 * Get IP address from HTTP REMOTE_ADDR header. If the CMS is Drupal then use
1179 * the Drupal function as this also handles reverse proxies (based on proper
1180 * configuration in settings.php)
1182 * @param bool $strictIPV4
1183 * (optional) Whether to return only IPv4 addresses.
1186 * IP address of logged in user.
1188 public static function ipAddress($strictIPV4 = TRUE) {
1189 $address = CRM_Utils_Array
::value('REMOTE_ADDR', $_SERVER);
1191 $config = CRM_Core_Config
::singleton();
1192 if ($config->userSystem
->is_drupal
&& function_exists('ip_address')) {
1193 //drupal function handles the server being behind a proxy securely. We still have legacy ipn methods
1194 // that reach this point without bootstrapping hence the check that the fn exists
1195 $address = ip_address();
1199 if ($address == '::1') {
1200 $address = '127.0.0.1';
1203 // when we need to have strictly IPV4 ip address
1204 // convert ipV6 to ipV4
1206 // this converts 'IPV4 mapped IPV6 address' to IPV4
1207 if (filter_var($address, FILTER_VALIDATE_IP
, FILTER_FLAG_IPV6
) && strstr($address, '::ffff:')) {
1208 $address = ltrim($address, '::ffff:');
1216 * Get the referring / previous page URL.
1219 * The previous page URL
1221 public static function refererPath() {
1222 return CRM_Utils_Array
::value('HTTP_REFERER', $_SERVER);
1226 * Get the documentation base URL.
1229 * Base URL of the CRM documentation.
1231 public static function getDocBaseURL() {
1232 // FIXME: move this to configuration at some stage
1233 return 'http://book.civicrm.org/';
1237 * Returns wiki (alternate) documentation URL base.
1242 public static function getWikiBaseURL() {
1243 // FIXME: move this to configuration at some stage
1244 return 'http://wiki.civicrm.org/confluence/display/CRMDOC/';
1248 * Returns URL or link to documentation page, based on provided parameters.
1250 * For use in PHP code.
1251 * WARNING: Always returns URL, if ts function is not defined ($URLonly has
1254 * @param string $page
1255 * Title of documentation wiki page.
1256 * @param bool $URLonly
1257 * (optional) Whether to return URL only or full HTML link (default).
1258 * @param string $text
1259 * (optional) Text of HTML link (no effect if $URLonly = false).
1260 * @param string $title
1261 * (optional) Tooltip text for HTML link (no effect if $URLonly = false)
1262 * @param string $style
1263 * (optional) Style attribute value for HTML link (no effect if $URLonly = false)
1265 * @param null $resource
1268 * URL or link to documentation page, based on provided parameters.
1270 public static function docURL2($page, $URLonly = FALSE, $text = NULL, $title = NULL, $style = NULL, $resource = NULL) {
1271 // if ts function doesn't exist, it means that CiviCRM hasn't been fully initialised yet -
1272 // return just the URL, no matter what other parameters are defined
1273 if (!function_exists('ts')) {
1274 if ($resource == 'wiki') {
1275 $docBaseURL = self
::getWikiBaseURL();
1278 $docBaseURL = self
::getDocBaseURL();
1280 return $docBaseURL . str_replace(' ', '+', $page);
1285 'URLonly' => $URLonly,
1289 'resource' => $resource,
1291 return self
::docURL($params);
1296 * Returns URL or link to documentation page, based on provided parameters.
1298 * For use in templates code.
1300 * @param array $params
1301 * An array of parameters (see CRM_Utils_System::docURL2 method for names)
1303 * @return void|string
1304 * URL or link to documentation page, based on provided parameters.
1306 public static function docURL($params) {
1308 if (!isset($params['page'])) {
1312 if (CRM_Utils_Array
::value('resource', $params) == 'wiki') {
1313 $docBaseURL = self
::getWikiBaseURL();
1316 $docBaseURL = self
::getDocBaseURL();
1319 if (!isset($params['title']) or $params['title'] === NULL) {
1320 $params['title'] = ts('Opens documentation in a new window.');
1323 if (!isset($params['text']) or $params['text'] === NULL) {
1324 $params['text'] = ts('(learn more...)');
1327 if (!isset($params['style']) ||
$params['style'] === NULL) {
1331 $style = "style=\"{$params['style']}\"";
1334 $link = $docBaseURL . str_replace(' ', '+', $params['page']);
1336 if (isset($params['URLonly']) && $params['URLonly'] == TRUE) {
1340 return "<a href=\"{$link}\" $style target=\"_blank\" class=\"crm-doc-link no-popup\" title=\"{$params['title']}\">{$params['text']}</a>";
1345 * Get the locale set in the hosting CMS.
1348 * The used locale or null for none.
1350 public static function getUFLocale() {
1351 $config = CRM_Core_Config
::singleton();
1352 return $config->userSystem
->getUFLocale();
1356 * Execute external or internal URLs and return server response.
1358 * @param string $url
1360 * @param bool $addCookie
1361 * Whether to provide a cookie. Should be true to access internal URLs.
1364 * Response from URL.
1366 public static function getServerResponse($url, $addCookie = TRUE) {
1367 CRM_Core_TemporaryErrorScope
::ignoreException();
1368 require_once 'HTTP/Request.php';
1369 $request = new HTTP_Request($url);
1372 foreach ($_COOKIE as $name => $value) {
1373 $request->addCookie($name, $value);
1377 if (isset($_SERVER['AUTH_TYPE'])) {
1378 $request->setBasicAuth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
1381 $config = CRM_Core_Config
::singleton();
1382 if ($config->userFramework
== 'WordPress') {
1383 session_write_close();
1386 $request->sendRequest();
1387 $response = $request->getResponseBody();
1394 public static function isDBVersionValid(&$errorMessage) {
1395 $dbVersion = CRM_Core_BAO_Domain
::version();
1398 // if db.ver missing
1399 $errorMessage = ts('Version information found to be missing in database. You will need to determine the correct version corresponding to your current database state.');
1402 elseif (!CRM_Utils_System
::isVersionFormatValid($dbVersion)) {
1403 $errorMessage = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
1406 elseif (stripos($dbVersion, 'upgrade')) {
1407 // if db.ver indicates a partially upgraded db
1408 $upgradeUrl = CRM_Utils_System
::url("civicrm/upgrade", "reset=1");
1409 $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));
1413 $codeVersion = CRM_Utils_System
::version();
1415 // if db.ver < code.ver, time to upgrade
1416 if (version_compare($dbVersion, $codeVersion) < 0) {
1417 $upgradeUrl = CRM_Utils_System
::url("civicrm/upgrade", "reset=1");
1418 $errorMessage = ts('New codebase version detected. You might want to visit <a href=\'%1\'>upgrade screen</a> to upgrade the database.', array(1 => $upgradeUrl));
1422 // if db.ver > code.ver, sth really wrong
1423 if (version_compare($dbVersion, $codeVersion) > 0) {
1424 $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.',
1425 array(1 => $dbVersion, 2 => $codeVersion)
1427 $errorMessage .= "<p>" . ts('OR if this is a manual install from git, you might want to fix civicrm-version.php file.') . "</p>";
1431 // FIXME: there should be another check to make sure version is in valid format - X.Y.alpha_num
1437 * Exit with provided exit code.
1439 * @param int $status
1440 * (optional) Code with which to exit.
1442 public static function civiExit($status = 0) {
1443 // move things to CiviCRM cache as needed
1444 CRM_Core_Session
::storeSessionObjects();
1450 * Reset the various system caches and some important static variables.
1452 public static function flushCache() {
1453 // flush out all cache entries so we can reload new data
1454 // a bit aggressive, but livable for now
1455 $cache = CRM_Utils_Cache
::singleton();
1458 // also reset the various static memory caches
1460 // reset the memory or array cache
1461 CRM_Core_BAO_Cache
::deleteGroup('contact fields', NULL, FALSE);
1464 CRM_ACL_BAO_Cache
::resetCache();
1466 // reset various static arrays used here
1467 CRM_Contact_BAO_Contact
::$_importableFields = CRM_Contact_BAO_Contact
::$_exportableFields
1468 = CRM_Contribute_BAO_Contribution
::$_importableFields
1469 = CRM_Contribute_BAO_Contribution
::$_exportableFields
1470 = CRM_Pledge_BAO_Pledge
::$_exportableFields = CRM_Contribute_BAO_Query
::$_contributionFields
1471 = CRM_Core_BAO_CustomField
::$_importFields
1472 = CRM_Core_BAO_Cache
::$_cache = CRM_Core_DAO
::$_dbColumnValueCache = NULL;
1474 CRM_Core_OptionGroup
::flushAll();
1475 CRM_Utils_PseudoConstant
::flushAll();
1479 * Load CMS bootstrap.
1481 * @param array $params
1482 * Array with uid name and pass
1483 * @param bool $loadUser
1484 * Boolean load user or not.
1485 * @param bool $throwError
1488 public static function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
1489 if (!is_array($params)) {
1492 $config = CRM_Core_Config
::singleton();
1493 return $config->userSystem
->loadBootStrap($params, $loadUser, $throwError, $realPath);
1497 * Check if user is logged in.
1501 public static function isUserLoggedIn() {
1502 $config = CRM_Core_Config
::singleton();
1503 return $config->userSystem
->isUserLoggedIn();
1507 * Get current logged in user id.
1510 * ufId, currently logged in user uf id.
1512 public static function getLoggedInUfID() {
1513 $config = CRM_Core_Config
::singleton();
1514 return $config->userSystem
->getLoggedInUfID();
1519 public static function baseCMSURL() {
1520 static $_baseURL = NULL;
1522 $config = CRM_Core_Config
::singleton();
1523 $_baseURL = $userFrameworkBaseURL = $config->userFrameworkBaseURL
;
1525 if ($config->userFramework
== 'Joomla') {
1527 // we need to remove the administrator/ from the end
1528 $_baseURL = str_replace("/administrator/", "/", $userFrameworkBaseURL);
1532 global $civicrm_root;
1533 if (strpos($civicrm_root,
1534 DIRECTORY_SEPARATOR
. 'sites' .
1535 DIRECTORY_SEPARATOR
. 'all' .
1536 DIRECTORY_SEPARATOR
. 'modules'
1539 $startPos = strpos($civicrm_root,
1540 DIRECTORY_SEPARATOR
. 'sites' . DIRECTORY_SEPARATOR
1542 $endPos = strpos($civicrm_root,
1543 DIRECTORY_SEPARATOR
. 'modules' . DIRECTORY_SEPARATOR
1545 if ($startPos && $endPos) {
1546 // if component is in sites/SITENAME/modules
1547 $siteName = substr($civicrm_root,
1549 $endPos - $startPos - 7
1552 $_baseURL = $userFrameworkBaseURL . "sites/$siteName/";
1561 * Given a URL, return a relative URL if possible.
1563 * @param string $url
1566 public static function relativeURL($url) {
1567 // check if url is relative, if so return immediately
1568 if (substr($url, 0, 4) != 'http') {
1572 // make everything relative from the baseFilePath
1573 $baseURL = self
::baseCMSURL();
1575 // check if baseURL is a substr of $url, if so
1576 // return rest of string
1577 if (substr($url, 0, strlen($baseURL)) == $baseURL) {
1578 return substr($url, strlen($baseURL));
1581 // return the original value
1586 * Produce an absolute URL from a possibly-relative URL.
1588 * @param string $url
1589 * @param bool $removeLanguagePart
1593 public static function absoluteURL($url, $removeLanguagePart = FALSE) {
1594 // check if url is already absolute, if so return immediately
1595 if (substr($url, 0, 4) == 'http') {
1599 // make everything absolute from the baseFileURL
1600 $baseURL = self
::baseCMSURL();
1602 //CRM-7622: drop the language from the URL if requested (and it’s there)
1603 $config = CRM_Core_Config
::singleton();
1604 if ($removeLanguagePart) {
1605 $baseURL = self
::languageNegotiationURL($baseURL, FALSE, TRUE);
1608 return $baseURL . $url;
1612 * Clean url, replaces first '&' with '?'
1614 * @param string $url
1619 public static function cleanUrl($url) {
1624 if ($pos = strpos($url, '&')) {
1625 $url = substr_replace($url, '?', $pos, 1);
1632 * Format the url as per language Negotiation.
1634 * @param string $url
1636 * @param bool $addLanguagePart
1637 * @param bool $removeLanguagePart
1642 public static function languageNegotiationURL(
1644 $addLanguagePart = TRUE,
1645 $removeLanguagePart = FALSE
1647 $config = &CRM_Core_Config
::singleton();
1648 return $config->userSystem
->languageNegotiationURL($url, $addLanguagePart, $removeLanguagePart);
1652 * Append the contents of an 'extra' smarty template file if it is present in
1653 * the custom template directory. This does not work if there are
1654 * multiple custom template directories
1656 * @param string $fileName
1657 * The name of the tpl file that we are processing.
1658 * @param string $content
1659 * The current content string. May be modified by this function.
1660 * @param string $overideFileName
1661 * (optional) Sent by contribution/event reg/profile pages which uses a id
1662 * specific extra file name if present.
1664 public static function appendTPLFile(
1667 $overideFileName = NULL
1669 $template = CRM_Core_Smarty
::singleton();
1670 if ($overideFileName) {
1671 $additionalTPLFile = $overideFileName;
1674 $additionalTPLFile = str_replace('.tpl', '.extra.tpl', $fileName);
1677 if ($template->template_exists($additionalTPLFile)) {
1678 $content .= $template->fetch($additionalTPLFile);
1683 * Get a list of all files that are found within the directories
1684 * that are the result of appending the provided relative path to
1685 * each component of the PHP include path.
1687 * @author Ken Zalewski
1689 * @param string $relpath
1690 * A relative path, typically pointing to a directory with multiple class
1694 * An array of files that exist in one or more of the directories that are
1695 * referenced by the relative path when appended to each element of the PHP
1698 public static function listIncludeFiles($relpath) {
1699 $file_list = array();
1700 $inc_dirs = explode(PATH_SEPARATOR
, get_include_path());
1701 foreach ($inc_dirs as $inc_dir) {
1702 $target_dir = $inc_dir . DIRECTORY_SEPARATOR
. $relpath;
1703 if (is_dir($target_dir)) {
1704 $cur_list = scandir($target_dir);
1705 foreach ($cur_list as $fname) {
1706 if ($fname != '.' && $fname != '..') {
1707 $file_list[$fname] = $fname;
1714 // listIncludeFiles()
1717 * Get a list of all "plugins" (PHP classes that implement a piece of
1718 * functionality using a well-defined interface) that are found in a
1719 * particular CiviCRM directory (both custom and core are searched).
1721 * @author Ken Zalewski
1723 * @param string $relpath
1724 * A relative path referencing a directory that contains one or more
1726 * @param string $fext
1727 * (optional) Only files with this extension will be considered to be
1729 * @param array $skipList
1730 * (optional) List of files to skip.
1733 * List of plugins, where the plugin name is both the key and the value of
1736 public static function getPluginList($relpath, $fext = '.php', $skipList = array()) {
1737 $fext_len = strlen($fext);
1739 $inc_files = CRM_Utils_System
::listIncludeFiles($relpath);
1740 foreach ($inc_files as $inc_file) {
1741 if (substr($inc_file, 0 - $fext_len) == $fext) {
1742 $plugin_name = substr($inc_file, 0, 0 - $fext_len);
1743 if (!in_array($plugin_name, $skipList)) {
1744 $plugins[$plugin_name] = $plugin_name;
1754 public static function executeScheduledJobs() {
1755 $facility = new CRM_Core_JobManager();
1756 $facility->execute(FALSE);
1758 $redirectUrl = self
::url('civicrm/admin/job', 'reset=1');
1760 CRM_Core_Session
::setStatus(
1761 ts('Scheduled jobs have been executed according to individual timing settings. Please check log for messages.'),
1762 ts('Complete'), 'success');
1764 CRM_Utils_System
::redirect($redirectUrl);
1768 * Evaluate any tokens in a URL.
1770 * @param string|FALSE $url
1771 * @return string|FALSE
1773 public static function evalUrl($url) {
1774 if ($url === FALSE) {
1778 $config = CRM_Core_Config
::singleton();
1780 '{ver}' => CRM_Utils_System
::version(),
1781 '{uf}' => $config->userFramework
,
1782 '{php}' => phpversion(),
1783 '{sid}' => md5('sid_' . (defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: '') . '_' . $config->userFrameworkBaseURL
),
1784 '{baseUrl}' => $config->userFrameworkBaseURL
,
1785 '{lang}' => $config->lcMessages
,
1786 '{co}' => $config->defaultContactCountry
,
1788 foreach (array_keys($vars) as $k) {
1789 $vars[$k] = urlencode($vars[$k]);
1791 return strtr($url, $vars);
1797 * Determine whether this is a developmental system.
1801 public static function isDevelopment() {
1802 static $cache = NULL;
1803 if ($cache === NULL) {
1804 global $civicrm_root;
1805 $cache = file_exists("{$civicrm_root}/.svn") ||
file_exists("{$civicrm_root}/.git");
1813 public static function isInUpgradeMode() {
1814 $args = explode('/', $_GET['q']);
1815 $upgradeInProcess = CRM_Core_Session
::singleton()->get('isUpgradePending');
1816 if ((isset($args[1]) && $args[1] == 'upgrade') ||
$upgradeInProcess) {
1825 * Determine the standard URL for viewing or editing the specified link.
1827 * This function delegates the decision-making to (a) the hook system and
1828 * (b) the BAO system.
1830 * @param array $crudLinkSpec
1832 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
1833 * - entity_table: string, eg "civicrm_contact"
1835 * @return array|NULL
1836 * NULL if unavailable, or an array. array has keys:
1842 public static function createDefaultCrudLink($crudLinkSpec) {
1843 $crudLinkSpec['action'] = CRM_Utils_Array
::value('action', $crudLinkSpec, CRM_Core_Action
::VIEW
);
1844 $daoClass = CRM_Core_DAO_AllCoreTables
::getClassForTable($crudLinkSpec['entity_table']);
1849 $baoClass = str_replace('_DAO_', '_BAO_', $daoClass);
1850 if (!class_exists($baoClass)) {
1854 $bao = new $baoClass();
1855 $bao->id
= $crudLinkSpec['entity_id'];
1856 if (!$bao->find(TRUE)) {
1861 CRM_Utils_Hook
::crudLink($crudLinkSpec, $bao, $link);
1862 if (empty($link) && is_callable(array($bao, 'createDefaultCrudLink'))) {
1863 $link = $bao->createDefaultCrudLink($crudLinkSpec);
1866 if (!empty($link)) {
1867 if (!isset($link['url'])) {
1868 $link['url'] = self
::url($link['path'], $link['query'], TRUE, NULL, FALSE);