3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
35 * System wide utilities.
37 * Provides a collection of Civi utilities + access to the CMS-dependant utilities
39 * FIXME: This is a massive and random collection that could be split into smaller services
41 * @method static mixed permissionDenied() Show access denied screen.
42 * @method static mixed logout() Log out the current user.
43 * @method static mixed updateCategories() Clear CMS caches related to the user registration/profile forms.
44 * @method static appendBreadCrumb(array $breadCrumbs) Append an additional breadcrumb tag to the existing breadcrumbs.
45 * @method static resetBreadCrumb() Reset an additional breadcrumb tag to the existing breadcrumb.
46 * @method static addHTMLHead(string $bc) Append a string to the head of the HTML file.
47 * @method static string postURL(int $action) Determine the post URL for a form.
48 * @method static string|null getUFLocale() Get the locale of the CMS.
49 * @method static bool setUFLocale(string $civicrm_language) Set the locale of the CMS.
50 * @method static bool isUserLoggedIn() Check if user is logged in.
51 * @method static int getLoggedInUfID() Get current logged in user id.
52 * @method static setHttpHeader(string $name, string $value) Set http header.
53 * @method static array synchronizeUsers() Create CRM contacts for all existing CMS users.
55 class CRM_Utils_System
{
57 public static $_callbacks = NULL;
63 public static $title = '';
66 * Access methods in the appropriate CMS class
72 public static function __callStatic($name, $arguments) {
73 $userSystem = CRM_Core_Config
::singleton()->userSystem
;
74 return call_user_func_array([$userSystem, $name], $arguments);
78 * Compose a new URL string from the current URL string.
80 * Used by all the framework components, specifically,
83 * @param string $urlVar
84 * The url variable being considered (i.e. crmPageID, crmSortID etc).
85 * @param bool $includeReset
86 * (optional) Whether to include the reset GET string (if present).
87 * @param bool $includeForce
88 * (optional) Whether to include the force GET string (if present).
90 * (optional) The path to use for the new url.
91 * @param bool|string $absolute
92 * (optional) Whether to return an absolute URL.
97 public static function makeURL($urlVar, $includeReset = FALSE, $includeForce = TRUE, $path = NULL, $absolute = FALSE) {
99 $config = CRM_Core_Config
::singleton();
100 $path = CRM_Utils_Array
::value($config->userFrameworkURLVar
, $_GET);
108 CRM_Utils_System
::getLinksUrl($urlVar, $includeReset, $includeForce),
114 * Get the query string and clean it up.
116 * Strips some variables that should not be propagated, specifically variables
117 * like 'reset'. Also strips any side-affect actions (e.g. export).
119 * This function is copied mostly verbatim from Pager.php (_getLinksUrl)
121 * @param string $urlVar
122 * The URL variable being considered (e.g. crmPageID, crmSortID etc).
123 * @param bool $includeReset
124 * (optional) By default this is FALSE, meaning that the reset parameter
125 * is skipped. Set to TRUE to leave the reset parameter as-is.
126 * @param bool $includeForce
128 * @param bool $skipUFVar
133 public static function getLinksUrl($urlVar, $includeReset = FALSE, $includeForce = TRUE, $skipUFVar = TRUE) {
134 // Sort out query string to prevent messy urls
139 if (!empty($_SERVER['QUERY_STRING'])) {
140 $qs = explode('&', str_replace('&', '&', $_SERVER['QUERY_STRING']));
141 for ($i = 0, $cnt = count($qs); $i < $cnt; $i++
) {
142 // check first if exist a pair
143 if (strstr($qs[$i], '=') !== FALSE) {
144 list($name, $value) = explode('=', $qs[$i]);
145 if ($name != $urlVar) {
146 $name = rawurldecode($name);
147 // check for arrays in parameters: site.php?foo[]=1&foo[]=2&foo[]=3
148 if ((strpos($name, '[') !== FALSE) &&
149 (strpos($name, ']') !== FALSE)
169 // Ok this is a big assumption but usually works
170 // If we are in snippet mode, retain the 'section' param, if not, get rid
172 if (!empty($qs['snippet'])) {
173 unset($qs['snippet']);
176 unset($qs['section']);
180 $config = CRM_Core_Config
::singleton();
181 unset($qs[$config->userFrameworkURLVar
]);
184 foreach ($qs as $name => $value) {
185 if ($name != 'reset' ||
$includeReset) {
186 $querystring[] = $name . '=' . $value;
190 $querystring = array_merge($querystring, array_unique($arrays));
192 $url = implode('&', $querystring);
194 $url .= (!empty($querystring) ?
'&' : '') . $urlVar . '=';
201 * If we are using a theming system, invoke theme, else just print the content.
203 * @param string $content
204 * The content that will be themed.
206 * (optional) Are we displaying to the screen or bypassing theming?
207 * @param bool $maintenance
208 * (optional) For maintenance mode.
212 public static function theme(
217 $config = &CRM_Core_Config
::singleton();
218 return $config->userSystem
->theme($content, $print, $maintenance);
222 * Generate a query string if input is an array.
224 * @param array|string $query
228 public static function makeQueryString($query) {
229 if (is_array($query)) {
231 foreach ($query as $key => $value) {
232 $buf .= ($buf ?
'&' : '') . urlencode($key) . '=' . urlencode($value);
240 * Generate an internal CiviCRM URL.
242 * @param string $path
243 * The path being linked to, such as "civicrm/add".
244 * @param array|string $query
245 * A query string to append to the link, or an array of key-value pairs.
246 * @param bool $absolute
247 * Whether to force the output to be an absolute link (beginning with a
248 * URI-scheme such as 'http:'). Useful for links that will be displayed
249 * outside the site, such as in an RSS feed.
250 * @param string $fragment
251 * A fragment identifier (named anchor) to append to the link.
252 * @param bool $htmlize
253 * Whether to encode special html characters such as &.
254 * @param bool $frontend
255 * This link should be to the CMS front end (applies to WP & Joomla).
256 * @param bool $forceBackend
257 * This link should be to the CMS back end (applies to WP & Joomla).
260 * An HTML string containing a link to the given path.
262 public static function url(
269 $forceBackend = FALSE
271 $query = self
::makeQueryString($query);
273 // Legacy handling for when the system passes around html escaped strings
274 if (strstr($query, '&')) {
275 $query = html_entity_decode($query);
278 // Extract fragment from path or query if munged together
279 if ($query && strstr($query, '#')) {
280 list($path, $fragment) = explode('#', $query);
282 if ($path && strstr($path, '#')) {
283 list($path, $fragment) = explode('#', $path);
286 // Extract query from path if munged together
287 if ($path && strstr($path, '?')) {
288 list($path, $extraQuery) = explode('?', $path);
289 $query = $extraQuery . ($query ?
"&$query" : '');
292 $config = CRM_Core_Config
::singleton();
293 $url = $config->userSystem
->url($path, $query, $absolute, $fragment, $frontend, $forceBackend);
296 $url = htmlentities($url);
303 * Path of the current page e.g. 'civicrm/contact/view'
305 * @return string|null
307 public static function getUrlPath() {
308 if (isset($_GET[CRM_Core_Config
::singleton()->userFrameworkURLVar
])) {
309 return $_GET[CRM_Core_Config
::singleton()->userFrameworkURLVar
];
317 * @param string $text
318 * @param string $path
319 * @param string|array $query
320 * @param bool $absolute
321 * @param string $fragment
322 * @param bool $htmlize
323 * @param bool $frontend
324 * @param bool $forceBackend
328 public static function href(
329 $text, $path = NULL, $query = NULL, $absolute = TRUE,
330 $fragment = NULL, $htmlize = TRUE, $frontend = FALSE, $forceBackend = FALSE
332 $url = self
::url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
333 return "<a href=\"$url\">$text</a>";
337 * What menu path are we currently on. Called for the primary tpl.
340 * the current menu path
342 public static function currentPath() {
343 $config = CRM_Core_Config
::singleton();
344 return trim(CRM_Utils_Array
::value($config->userFrameworkURLVar
, $_GET), '/');
348 * Called from a template to compose a url.
350 * @param array $params
351 * List of parameters.
356 public static function crmURL($params) {
357 $p = CRM_Utils_Array
::value('p', $params);
359 $p = self
::currentPath();
364 CRM_Utils_Array
::value('q', $params),
365 CRM_Utils_Array
::value('a', $params, FALSE),
366 CRM_Utils_Array
::value('f', $params),
367 CRM_Utils_Array
::value('h', $params, TRUE),
368 CRM_Utils_Array
::value('fe', $params, FALSE),
369 CRM_Utils_Array
::value('fb', $params, FALSE)
374 * Sets the title of the page.
376 * @param string $title
377 * Document title - plain text only
378 * @param string $pageTitle
379 * Page title (if different) - may include html
381 public static function setTitle($title, $pageTitle = NULL) {
382 self
::$title = $title;
383 $config = CRM_Core_Config
::singleton();
384 return $config->userSystem
->setTitle($title, $pageTitle);
388 * Figures and sets the userContext.
390 * Uses the referrer if valid else uses the default.
392 * @param array $names
393 * Referrer should match any str in this array.
394 * @param string $default
395 * (optional) The default userContext if no match found.
397 public static function setUserContext($names, $default = NULL) {
400 $session = CRM_Core_Session
::singleton();
401 $referer = CRM_Utils_Array
::value('HTTP_REFERER', $_SERVER);
403 if ($referer && !empty($names)) {
404 foreach ($names as $name) {
405 if (strstr($referer, $name)) {
413 $session->pushUserContext($url);
418 * Gets a class name for an object.
420 * @param object $object
421 * Object whose class name is needed.
424 * The class name of the object.
426 public static function getClassName($object) {
427 return get_class($object);
431 * Redirect to another URL.
434 * The URL to provide to the browser via the Location header.
435 * @param array $context
436 * Optional additional information for the hook.
438 public static function redirect($url = NULL, $context = []) {
440 $url = self
::url('civicrm/dashboard', 'reset=1');
442 // replace the & characters with &
443 // this is kinda hackish but not sure how to do it right
444 $url = str_replace('&', '&', $url);
446 $context['output'] = CRM_Utils_Array
::value('snippet', $_GET);
448 $parsedUrl = CRM_Utils_Url
::parseUrl($url);
449 CRM_Utils_Hook
::alterRedirect($parsedUrl, $context);
450 $url = CRM_Utils_Url
::unparseUrl($parsedUrl);
452 // If we are in a json context, respond appropriately
453 if ($context['output'] === 'json') {
454 CRM_Core_Page_AJAX
::returnJsonResponse([
455 'status' => 'redirect',
456 'userContext' => $url,
460 self
::setHttpHeader('Location', $url);
465 * Redirect to another URL using JavaScript.
467 * Use an html based file with javascript embedded to redirect to another url
468 * This prevent the too many redirect errors emitted by various browsers
471 * (optional) The destination URL.
472 * @param string $title
473 * (optional) The page title to use for the redirect page.
474 * @param string $message
475 * (optional) The message to provide in the body of the redirect page.
477 public static function jsRedirect(
483 $url = self
::url('civicrm/dashboard', 'reset=1');
487 $title = ts('CiviCRM task in progress');
491 $message = ts('A long running CiviCRM task is currently in progress. This message will be refreshed till the task is completed');
494 // replace the & characters with &
495 // this is kinda hackish but not sure how to do it right
496 $url = str_replace('&', '&', $url);
498 $template = CRM_Core_Smarty
::singleton();
499 $template->assign('redirectURL', $url);
500 $template->assign('title', $title);
501 $template->assign('message', $message);
503 $html = $template->fetch('CRM/common/redirectJS.tpl');
511 * Get the base URL of the system.
515 public static function baseURL() {
516 $config = CRM_Core_Config
::singleton();
517 return $config->userFrameworkBaseURL
;
521 * Authenticate or abort.
523 * @param string $message
528 public static function authenticateAbort($message, $abort) {
542 * (optional) Whether to exit; defaults to true.
546 public static function authenticateKey($abort = TRUE) {
547 // also make sure the key is sent and is valid
548 $key = trim(CRM_Utils_Array
::value('key', $_REQUEST));
550 $docAdd = "More info at:" . CRM_Utils_System
::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
553 return self
::authenticateAbort(
554 "ERROR: You need to send a valid key to execute this file. " . $docAdd . "\n",
559 $siteKey = defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: NULL;
561 if (!$siteKey ||
empty($siteKey)) {
562 return self
::authenticateAbort(
563 "ERROR: You need to set a valid site key in civicrm.settings.php. " . $docAdd . "\n",
568 if (strlen($siteKey) < 8) {
569 return self
::authenticateAbort(
570 "ERROR: Site key needs to be greater than 7 characters in civicrm.settings.php. " . $docAdd . "\n",
575 if ($key !== $siteKey) {
576 return self
::authenticateAbort(
577 "ERROR: Invalid key value sent. " . $docAdd . "\n",
586 * Authenticate script.
589 * @param string $name
590 * @param string $pass
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([$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
654 * @param string $realPath
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 * Q: Can we move this to the userSystem class so that it can be tuned
667 * per-CMS? For example, when dealing with UnitTests UF, there's no
670 $session = CRM_Core_Session
::singleton();
671 $session->set('civicrmInitSession', TRUE);
673 if ($config->userFrameworkDSN
) {
674 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
676 return $config->userSystem
->authenticate($name, $password, $loadCMSBootstrap, $realPath);
680 * Set a message in the UF to display to a user.
682 * @param string $message
683 * The message to set.
685 public static function setUFMessage($message) {
686 $config = CRM_Core_Config
::singleton();
687 return $config->userSystem
->setMessage($message);
691 * Determine whether a value is null-ish.
693 * @param mixed $value
694 * The value to check for null.
698 public static function isNull($value) {
699 // FIXME: remove $value = 'null' string test when we upgrade our DAO code to handle passing null in a better way.
700 if (!isset($value) ||
$value === NULL ||
$value === '' ||
$value === 'null') {
703 if (is_array($value)) {
704 // @todo Reuse of the $value variable = asking for trouble.
705 foreach ($value as $key => $value) {
706 if (in_array($key, CRM_Core_DAO
::acceptedSQLOperators(), TRUE) ||
!self
::isNull($value)) {
716 * Obscure all but the last few digits of a credit card number.
718 * @param string $number
719 * The credit card number to obscure.
721 * (optional) The number of digits to preserve unmodified.
724 * The obscured credit card number.
726 public static function mungeCreditCard($number, $keep = 4) {
727 $number = trim($number);
728 if (empty($number)) {
731 $replace = str_repeat('*', strlen($number) - $keep);
732 return substr_replace($number, $replace, 0, -$keep);
736 * Determine which PHP modules are loaded.
740 private static function parsePHPModules() {
742 phpinfo(INFO_MODULES
);
743 $s = ob_get_contents();
746 $s = strip_tags($s, '<h2><th><td>');
747 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/', "<info>\\1</info>", $s);
748 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/', "<info>\\1</info>", $s);
749 $vTmp = preg_split('/(<h2>[^<]+<\/h2>)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE
);
751 for ($i = 1; $i < count($vTmp); $i++
) {
752 if (preg_match('/<h2>([^<]+)<\/h2>/', $vTmp[$i], $vMat)) {
753 $vName = trim($vMat[1]);
754 $vTmp2 = explode("\n", $vTmp[$i +
1]);
755 foreach ($vTmp2 as $vOne) {
756 $vPat = '<info>([^<]+)<\/info>';
757 $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
758 $vPat2 = "/$vPat\s*$vPat/";
760 if (preg_match($vPat3, $vOne, $vMat)) {
761 $vModules[$vName][trim($vMat[1])] = [trim($vMat[2]), trim($vMat[3])];
764 elseif (preg_match($vPat2, $vOne, $vMat)) {
765 $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
774 * Get a setting from a loaded PHP module.
776 * @param string $pModuleName
777 * @param string $pSetting
781 public static function getModuleSetting($pModuleName, $pSetting) {
782 $vModules = self
::parsePHPModules();
783 return $vModules[$pModuleName][$pSetting];
787 * Do something no-one bothered to document.
789 * @param string $title
792 * @return mixed|string
794 public static function memory($title = NULL) {
797 $pid = posix_getpid();
800 $memory = str_replace("\n", '', shell_exec("ps -p" . $pid . " -o rss="));
801 $memory .= ", " . time();
803 CRM_Core_Error
::debug_var($title, $memory);
809 * Download something or other.
811 * @param string $name
812 * @param string $mimeType
813 * @param string $buffer
815 * @param bool $output
816 * @param string $disposition
818 public static function download(
819 $name, $mimeType, &$buffer,
822 $disposition = 'attachment'
824 $now = gmdate('D, d M Y H:i:s') . ' GMT';
826 self
::setHttpHeader('Content-Type', $mimeType);
827 self
::setHttpHeader('Expires', $now);
829 // lem9 & loic1: IE needs specific headers
830 $isIE = strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE');
832 $fileString = "filename=\"{$name}.{$ext}\"";
835 $fileString = "filename=\"{$name}\"";
838 self
::setHttpHeader("Content-Disposition", "inline; $fileString");
839 self
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
840 self
::setHttpHeader('Pragma', 'public');
843 self
::setHttpHeader("Content-Disposition", "$disposition; $fileString");
844 self
::setHttpHeader('Pragma', 'no-cache');
854 * Gather and print (and possibly log) amount of used memory.
856 * @param string $title
858 * (optional) Whether to log the memory usage information.
860 public static function xMemory($title = NULL, $log = FALSE) {
861 $mem = (float ) xdebug_memory_usage() / (float ) (1024);
862 $mem = number_format($mem, 5) . ", " . time();
864 echo "<p>$title: $mem<p>";
866 CRM_Core_Error
::debug_var($title, $mem);
869 echo "<p>$title: $mem<p>";
875 * Take a URL (or partial URL) and make it better.
877 * Currently, URLs pass straight through unchanged unless they are "seriously
878 * malformed" (see http://us2.php.net/parse_url).
881 * The URL to operate on.
886 public static function fixURL($url) {
887 $components = parse_url($url);
893 // at some point we'll add code here to make sure the url is not
894 // something that will mess up, so we need to clean it up here
899 * Make sure a callback is valid in the current context.
901 * @param string $callback
902 * Name of the function to check.
906 public static function validCallback($callback) {
907 if (self
::$_callbacks === NULL) {
908 self
::$_callbacks = [];
911 if (!array_key_exists($callback, self
::$_callbacks)) {
912 if (strpos($callback, '::') !== FALSE) {
913 list($className, $methodName) = explode('::', $callback);
914 $fileName = str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
915 // ignore errors if any
916 @include_once
$fileName;
917 if (!class_exists($className)) {
918 self
::$_callbacks[$callback] = FALSE;
921 // instantiate the class
922 $object = new $className();
923 if (!method_exists($object, $methodName)) {
924 self
::$_callbacks[$callback] = FALSE;
927 self
::$_callbacks[$callback] = TRUE;
932 self
::$_callbacks[$callback] = function_exists($callback);
935 return self
::$_callbacks[$callback];
939 * Like PHP's built-in explode(), but always return an array of $limit items.
941 * This serves as a wrapper to the PHP explode() function. In the event that
942 * PHP's explode() returns an array with fewer than $limit elements, pad
943 * the end of the array with NULLs.
945 * @param string $separator
946 * @param string $string
951 public static function explode($separator, $string, $limit) {
952 $result = explode($separator, $string, $limit);
953 for ($i = count($result); $i < $limit; $i++
) {
964 * @param bool $addCookie
969 public static function checkURL($url, $addCookie = FALSE) {
970 // make a GET request to $url
971 $ch = curl_init($url);
973 curl_setopt($ch, CURLOPT_COOKIE
, http_build_query($_COOKIE));
975 // it's quite alright to use a self-signed cert
976 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, 0);
978 // lets capture the return stuff rather than echo
979 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, TRUE);
981 // CRM-13227, CRM-14744: only return the SSL error status
982 return (curl_exec($ch) !== FALSE);
986 * Assert that we are running on a particular PHP version.
989 * The major version of PHP that is required.
991 * (optional) Whether to fatally abort if the version requirement is not
992 * met. Defaults to TRUE.
995 * Returns TRUE if the requirement is met, FALSE if the requirement is not
996 * met and we're not aborting due to the failed requirement. If $abort is
997 * TRUE and the requirement fails, this function does not return.
999 public static function checkPHPVersion($ver = 5, $abort = TRUE) {
1000 $phpVersion = substr(PHP_VERSION
, 0, 1);
1001 if ($phpVersion >= $ver) {
1006 CRM_Core_Error
::fatal(ts('This feature requires PHP Version %1 or greater',
1016 * @param string $string
1017 * @param bool $encode
1021 public static function formatWikiURL($string, $encode = FALSE) {
1022 $items = explode(' ', trim($string), 2);
1023 if (count($items) == 2) {
1031 $url = $encode ? self
::urlEncode($items[0]) : $items[0];
1032 return "<a href=\"$url\">$title</a>";
1038 * @param string $url
1040 * @return null|string
1042 public static function urlEncode($url) {
1043 $items = parse_url($url);
1044 if ($items === FALSE) {
1048 if (empty($items['query'])) {
1052 $items['query'] = urlencode($items['query']);
1054 $url = $items['scheme'] . '://';
1055 if (!empty($items['user'])) {
1056 $url .= "{$items['user']}:{$items['pass']}@";
1059 $url .= $items['host'];
1060 if (!empty($items['port'])) {
1061 $url .= ":{$items['port']}";
1064 $url .= "{$items['path']}?{$items['query']}";
1065 if (!empty($items['fragment'])) {
1066 $url .= "#{$items['fragment']}";
1073 * Return the running civicrm version.
1078 public static function version() {
1082 $verFile = implode(DIRECTORY_SEPARATOR
,
1083 [dirname(__FILE__
), '..', '..', 'xml', 'version.xml']
1085 if (file_exists($verFile)) {
1086 $str = file_get_contents($verFile);
1087 $xmlObj = simplexml_load_string($str);
1088 $version = (string) $xmlObj->version_no
;
1092 if (!CRM_Utils_System
::isVersionFormatValid($version)) {
1093 CRM_Core_Error
::fatal('Unknown codebase version.');
1101 * Gives the first two parts of the version string E.g. 6.1.
1105 public static function majorVersion() {
1106 list($a, $b) = explode('.', self
::version());
1111 * Determines whether a string is a valid CiviCRM version string.
1113 * @param string $version
1114 * Version string to be checked.
1118 public static function isVersionFormatValid($version) {
1119 return preg_match("/^(\d{1,2}\.){2,3}(\d{1,2}|(alpha|beta)\d{1,2})(\.upgrade)?$/", $version);
1123 * Wraps or emulates PHP's getallheaders() function.
1125 public static function getAllHeaders() {
1126 if (function_exists('getallheaders')) {
1127 return getallheaders();
1130 // emulate get all headers
1131 // http://www.php.net/manual/en/function.getallheaders.php#66335
1133 foreach ($_SERVER as $name => $value) {
1134 if (substr($name, 0, 5) == 'HTTP_') {
1135 $headers[str_replace(' ',
1137 ucwords(strtolower(str_replace('_',
1149 * Get request headers.
1151 * @return array|false
1153 public static function getRequestHeaders() {
1154 if (function_exists('apache_request_headers')) {
1155 return apache_request_headers();
1163 * Determine whether this is an SSL request.
1165 * Note that we inline this function in install/civicrm.php, so if you change
1166 * this function, please go and change the code in the install script as well.
1168 public static function isSSL() {
1169 return (isset($_SERVER['HTTPS']) &&
1170 !empty($_SERVER['HTTPS']) &&
1171 strtolower($_SERVER['HTTPS']) != 'off') ?
TRUE : FALSE;
1177 * @param bool|FALSE $abort
1179 * @throws \Exception
1181 public static function redirectToSSL($abort = FALSE) {
1182 $config = CRM_Core_Config
::singleton();
1183 $req_headers = self
::getRequestHeaders();
1184 // FIXME: Shouldn't the X-Forwarded-Proto check be part of CRM_Utils_System::isSSL()?
1185 if (Civi
::settings()->get('enableSSL') &&
1187 strtolower(CRM_Utils_Array
::value('X_FORWARDED_PROTO', $req_headers)) != 'https'
1189 // ensure that SSL is enabled on a civicrm url (for cookie reasons etc)
1190 $url = "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
1191 // @see https://lab.civicrm.org/dev/core/issues/425 if you're seeing this message.
1192 Civi
::log()->warning('CiviCRM thinks site is not SSL, redirecting to {url}', ['url' => $url]);
1193 if (!self
::checkURL($url, TRUE)) {
1195 CRM_Core_Error
::fatal('HTTPS is not set up on this machine');
1198 CRM_Core_Session
::setStatus(ts('HTTPS is not set up on this machine'), ts('Warning'), 'alert');
1199 // admin should be the only one following this
1200 // since we dont want the user stuck in a bad place
1204 CRM_Utils_System
::redirect($url);
1209 * Get logged in user's IP address.
1211 * Get IP address from HTTP REMOTE_ADDR header. If the CMS is Drupal then use
1212 * the Drupal function as this also handles reverse proxies (based on proper
1213 * configuration in settings.php)
1215 * @param bool $strictIPV4
1216 * (optional) Whether to return only IPv4 addresses.
1219 * IP address of logged in user.
1221 public static function ipAddress($strictIPV4 = TRUE) {
1222 $address = CRM_Utils_Array
::value('REMOTE_ADDR', $_SERVER);
1224 $config = CRM_Core_Config
::singleton();
1225 if ($config->userSystem
->is_drupal
&& function_exists('ip_address')) {
1226 // drupal function handles the server being behind a proxy securely. We still have legacy ipn methods
1227 // that reach this point without bootstrapping hence the check that the fn exists
1228 $address = ip_address();
1232 if ($address == '::1') {
1233 $address = '127.0.0.1';
1236 // when we need to have strictly IPV4 ip address
1237 // convert ipV6 to ipV4
1239 // this converts 'IPV4 mapped IPV6 address' to IPV4
1240 if (filter_var($address, FILTER_VALIDATE_IP
, FILTER_FLAG_IPV6
) && strstr($address, '::ffff:')) {
1241 $address = ltrim($address, '::ffff:');
1249 * Get the referring / previous page URL.
1252 * The previous page URL
1254 public static function refererPath() {
1255 return CRM_Utils_Array
::value('HTTP_REFERER', $_SERVER);
1259 * Get the documentation base URL.
1262 * Base URL of the CRM documentation.
1264 public static function getDocBaseURL() {
1265 // FIXME: move this to configuration at some stage
1266 return 'https://docs.civicrm.org/';
1270 * Returns wiki (alternate) documentation URL base.
1275 public static function getWikiBaseURL() {
1276 // FIXME: move this to configuration at some stage
1277 return 'http://wiki.civicrm.org/confluence/display/CRMDOC/';
1281 * Returns URL or link to documentation page, based on provided parameters.
1283 * For use in PHP code.
1284 * WARNING: Always returns URL, if ts function is not defined ($URLonly has
1287 * @param string $page
1288 * Title of documentation wiki page.
1289 * @param bool $URLonly
1290 * (optional) Whether to return URL only or full HTML link (default).
1291 * @param string $text
1292 * (optional) Text of HTML link (no effect if $URLonly = false).
1293 * @param string $title
1294 * (optional) Tooltip text for HTML link (no effect if $URLonly = false)
1295 * @param string $style
1296 * (optional) Style attribute value for HTML link (no effect if $URLonly = false)
1298 * @param null $resource
1301 * URL or link to documentation page, based on provided parameters.
1303 public static function docURL2($page, $URLonly = FALSE, $text = NULL, $title = NULL, $style = NULL, $resource = NULL) {
1304 // if ts function doesn't exist, it means that CiviCRM hasn't been fully initialised yet -
1305 // return just the URL, no matter what other parameters are defined
1306 if (!function_exists('ts')) {
1307 if ($resource == 'wiki') {
1308 $docBaseURL = self
::getWikiBaseURL();
1311 $docBaseURL = self
::getDocBaseURL();
1312 $page = self
::formatDocUrl($page);
1314 return $docBaseURL . str_replace(' ', '+', $page);
1319 'URLonly' => $URLonly,
1323 'resource' => $resource,
1325 return self
::docURL($params);
1330 * Returns URL or link to documentation page, based on provided parameters.
1332 * For use in templates code.
1334 * @param array $params
1335 * An array of parameters (see CRM_Utils_System::docURL2 method for names)
1337 * @return null|string
1338 * URL or link to documentation page, based on provided parameters.
1340 public static function docURL($params) {
1342 if (!isset($params['page'])) {
1346 if (CRM_Utils_Array
::value('resource', $params) == 'wiki') {
1347 $docBaseURL = self
::getWikiBaseURL();
1350 $docBaseURL = self
::getDocBaseURL();
1351 $params['page'] = self
::formatDocUrl($params['page']);
1354 if (!isset($params['title']) or $params['title'] === NULL) {
1355 $params['title'] = ts('Opens documentation in a new window.');
1358 if (!isset($params['text']) or $params['text'] === NULL) {
1359 $params['text'] = ts('(learn more...)');
1362 if (!isset($params['style']) ||
$params['style'] === NULL) {
1366 $style = "style=\"{$params['style']}\"";
1369 $link = $docBaseURL . str_replace(' ', '+', $params['page']);
1371 if (isset($params['URLonly']) && $params['URLonly'] == TRUE) {
1375 return "<a href=\"{$link}\" $style target=\"_blank\" class=\"crm-doc-link no-popup\" title=\"{$params['title']}\">{$params['text']}</a>";
1380 * Add language and version parameters to the doc url.
1382 * Note that this function may run before CiviCRM is initialized and so should not call ts() or perform any db lookups.
1387 public static function formatDocUrl($url) {
1388 return preg_replace('#^user/#', 'user/en/stable/', $url);
1392 * Exit with provided exit code.
1394 * @param int $status
1395 * (optional) Code with which to exit.
1397 public static function civiExit($status = 0) {
1400 http_response_code(500);
1402 // move things to CiviCRM cache as needed
1403 CRM_Core_Session
::storeSessionObjects();
1405 if (Civi\Core\Container
::isContainerBooted()) {
1406 Civi
::dispatcher()->dispatch('civi.core.exit');
1409 $userSystem = CRM_Core_Config
::singleton()->userSystem
;
1410 if (is_callable([$userSystem, 'onCiviExit'])) {
1411 $userSystem->onCiviExit();
1417 * Reset the various system caches and some important static variables.
1419 public static function flushCache() {
1420 // flush out all cache entries so we can reload new data
1421 // a bit aggressive, but livable for now
1422 CRM_Utils_Cache
::singleton()->flush();
1424 // Traditionally, systems running on memory-backed caches were quite
1425 // zealous about destroying *all* memory-backed caches during a flush().
1426 // These flushes simulate that legacy behavior. However, they should probably
1427 // be removed at some point.
1428 $localDrivers = ['CRM_Utils_Cache_Arraycache', 'CRM_Utils_Cache_NoCache'];
1429 if (Civi\Core\Container
::isContainerBooted()
1430 && !in_array(get_class(CRM_Utils_Cache
::singleton()), $localDrivers)) {
1431 Civi
::cache('long')->flush();
1432 Civi
::cache('settings')->flush();
1433 Civi
::cache('js_strings')->flush();
1434 Civi
::cache('community_messages')->flush();
1435 CRM_Extension_System
::singleton()->getCache()->flush();
1436 CRM_Cxn_CiviCxnHttp
::singleton()->getCache()->flush();
1439 // also reset the various static memory caches
1441 // reset the memory or array cache
1442 CRM_Core_BAO_Cache
::deleteGroup('contact fields', NULL, FALSE);
1445 CRM_ACL_BAO_Cache
::resetCache();
1447 // reset various static arrays used here
1448 CRM_Contact_BAO_Contact
::$_importableFields = CRM_Contact_BAO_Contact
::$_exportableFields
1449 = CRM_Contribute_BAO_Contribution
::$_importableFields
1450 = CRM_Contribute_BAO_Contribution
::$_exportableFields
1451 = CRM_Pledge_BAO_Pledge
::$_exportableFields
1452 = CRM_Core_BAO_CustomField
::$_importFields
1453 = CRM_Core_BAO_Cache
::$_cache = CRM_Core_DAO
::$_dbColumnValueCache = NULL;
1455 CRM_Core_OptionGroup
::flushAll();
1456 CRM_Utils_PseudoConstant
::flushAll();
1460 * Load CMS bootstrap.
1462 * @param array $params
1463 * Array with uid name and pass
1464 * @param bool $loadUser
1465 * Boolean load user or not.
1466 * @param bool $throwError
1467 * @param string $realPath
1469 public static function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
1470 if (!is_array($params)) {
1473 $config = CRM_Core_Config
::singleton();
1474 $result = $config->userSystem
->loadBootStrap($params, $loadUser, $throwError, $realPath);
1475 if (is_callable([$config->userSystem
, 'setMySQLTimeZone'])) {
1476 $config->userSystem
->setMySQLTimeZone();
1484 * @return mixed|string
1486 public static function baseCMSURL() {
1487 static $_baseURL = NULL;
1489 $config = CRM_Core_Config
::singleton();
1490 $_baseURL = $userFrameworkBaseURL = $config->userFrameworkBaseURL
;
1492 if ($config->userFramework
== 'Joomla') {
1494 // we need to remove the administrator/ from the end
1495 $_baseURL = str_replace("/administrator/", "/", $userFrameworkBaseURL);
1499 global $civicrm_root;
1500 if (strpos($civicrm_root,
1501 DIRECTORY_SEPARATOR
. 'sites' .
1502 DIRECTORY_SEPARATOR
. 'all' .
1503 DIRECTORY_SEPARATOR
. 'modules'
1506 $startPos = strpos($civicrm_root,
1507 DIRECTORY_SEPARATOR
. 'sites' . DIRECTORY_SEPARATOR
1509 $endPos = strpos($civicrm_root,
1510 DIRECTORY_SEPARATOR
. 'modules' . DIRECTORY_SEPARATOR
1512 if ($startPos && $endPos) {
1513 // if component is in sites/SITENAME/modules
1514 $siteName = substr($civicrm_root,
1516 $endPos - $startPos - 7
1519 $_baseURL = $userFrameworkBaseURL . "sites/$siteName/";
1528 * Given a URL, return a relative URL if possible.
1530 * @param string $url
1534 public static function relativeURL($url) {
1535 // check if url is relative, if so return immediately
1536 if (substr($url, 0, 4) != 'http') {
1540 // make everything relative from the baseFilePath
1541 $baseURL = self
::baseCMSURL();
1543 // check if baseURL is a substr of $url, if so
1544 // return rest of string
1545 if (substr($url, 0, strlen($baseURL)) == $baseURL) {
1546 return substr($url, strlen($baseURL));
1549 // return the original value
1554 * Produce an absolute URL from a possibly-relative URL.
1556 * @param string $url
1557 * @param bool $removeLanguagePart
1561 public static function absoluteURL($url, $removeLanguagePart = FALSE) {
1562 // check if url is already absolute, if so return immediately
1563 if (substr($url, 0, 4) == 'http') {
1567 // make everything absolute from the baseFileURL
1568 $baseURL = self
::baseCMSURL();
1570 //CRM-7622: drop the language from the URL if requested (and it’s there)
1571 $config = CRM_Core_Config
::singleton();
1572 if ($removeLanguagePart) {
1573 $baseURL = self
::languageNegotiationURL($baseURL, FALSE, TRUE);
1576 return $baseURL . $url;
1580 * Clean url, replaces first '&' with '?'.
1582 * @param string $url
1587 public static function cleanUrl($url) {
1592 if ($pos = strpos($url, '&')) {
1593 $url = substr_replace($url, '?', $pos, 1);
1600 * Format the url as per language Negotiation.
1602 * @param string $url
1604 * @param bool $addLanguagePart
1605 * @param bool $removeLanguagePart
1610 public static function languageNegotiationURL(
1612 $addLanguagePart = TRUE,
1613 $removeLanguagePart = FALSE
1615 $config = &CRM_Core_Config
::singleton();
1616 return $config->userSystem
->languageNegotiationURL($url, $addLanguagePart, $removeLanguagePart);
1620 * Append the contents of an 'extra' smarty template file.
1622 * It must be present in the custom template directory. This does not work if there are
1623 * multiple custom template directories
1625 * @param string $fileName
1626 * The name of the tpl file that we are processing.
1627 * @param string $content
1628 * The current content string. May be modified by this function.
1629 * @param string $overideFileName
1630 * (optional) Sent by contribution/event reg/profile pages which uses a id
1631 * specific extra file name if present.
1633 public static function appendTPLFile(
1636 $overideFileName = NULL
1638 $template = CRM_Core_Smarty
::singleton();
1639 if ($overideFileName) {
1640 $additionalTPLFile = $overideFileName;
1643 $additionalTPLFile = str_replace('.tpl', '.extra.tpl', $fileName);
1646 if ($template->template_exists($additionalTPLFile)) {
1647 $content .= $template->fetch($additionalTPLFile);
1652 * Get a list of all files that are found within the directories.
1654 * Files must be the result of appending the provided relative path to
1655 * each component of the PHP include path.
1657 * @author Ken Zalewski
1659 * @param string $relpath
1660 * A relative path, typically pointing to a directory with multiple class
1664 * An array of files that exist in one or more of the directories that are
1665 * referenced by the relative path when appended to each element of the PHP
1668 public static function listIncludeFiles($relpath) {
1670 $inc_dirs = explode(PATH_SEPARATOR
, get_include_path());
1671 foreach ($inc_dirs as $inc_dir) {
1672 $target_dir = $inc_dir . DIRECTORY_SEPARATOR
. $relpath;
1673 if (is_dir($target_dir)) {
1674 $cur_list = scandir($target_dir);
1675 foreach ($cur_list as $fname) {
1676 if ($fname != '.' && $fname != '..') {
1677 $file_list[$fname] = $fname;
1686 * Get a list of all "plugins".
1688 * (PHP classes that implement a piece of
1689 * functionality using a well-defined interface) that are found in a
1690 * particular CiviCRM directory (both custom and core are searched).
1692 * @author Ken Zalewski
1694 * @param string $relpath
1695 * A relative path referencing a directory that contains one or more
1697 * @param string $fext
1698 * (optional) Only files with this extension will be considered to be
1700 * @param array $skipList
1701 * (optional) List of files to skip.
1704 * List of plugins, where the plugin name is both the key and the value of
1707 public static function getPluginList($relpath, $fext = '.php', $skipList = []) {
1708 $fext_len = strlen($fext);
1710 $inc_files = CRM_Utils_System
::listIncludeFiles($relpath);
1711 foreach ($inc_files as $inc_file) {
1712 if (substr($inc_file, 0 - $fext_len) == $fext) {
1713 $plugin_name = substr($inc_file, 0, 0 - $fext_len);
1714 if (!in_array($plugin_name, $skipList)) {
1715 $plugins[$plugin_name] = $plugin_name;
1723 * Execute scheduled jobs.
1725 public static function executeScheduledJobs() {
1726 $facility = new CRM_Core_JobManager();
1727 $facility->execute(FALSE);
1729 $redirectUrl = self
::url('civicrm/admin/job', 'reset=1');
1731 CRM_Core_Session
::setStatus(
1732 ts('Scheduled jobs have been executed according to individual timing settings. Please check log for messages.'),
1733 ts('Complete'), 'success');
1735 CRM_Utils_System
::redirect($redirectUrl);
1739 * Evaluate any tokens in a URL.
1741 * @param string|FALSE $url
1743 * @return string|FALSE
1745 public static function evalUrl($url) {
1746 if (!$url ||
strpos($url, '{') === FALSE) {
1750 $config = CRM_Core_Config
::singleton();
1752 '{ver}' => CRM_Utils_System
::version(),
1753 '{uf}' => $config->userFramework
,
1754 '{php}' => phpversion(),
1755 '{sid}' => self
::getSiteID(),
1756 '{baseUrl}' => $config->userFrameworkBaseURL
,
1757 '{lang}' => $config->lcMessages
,
1758 '{co}' => $config->defaultContactCountry
,
1760 return strtr($url, array_map('urlencode', $vars));
1765 * Returns the unique identifier for this site, as used by community messages.
1767 * SiteID will be generated if it is not already stored in the settings table.
1771 public static function getSiteID() {
1772 $sid = Civi
::settings()->get('site_id');
1774 $config = CRM_Core_Config
::singleton();
1775 $sid = md5('sid_' . (defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: '') . '_' . $config->userFrameworkBaseURL
);
1776 civicrm_api3('Setting', 'create', ['domain_id' => 'all', 'site_id' => $sid]);
1782 * Determine whether this is a developmental system.
1786 public static function isDevelopment() {
1787 static $cache = NULL;
1788 if ($cache === NULL) {
1789 global $civicrm_root;
1790 $cache = file_exists("{$civicrm_root}/.svn") ||
file_exists("{$civicrm_root}/.git");
1796 * Is in upgrade mode.
1800 public static function isInUpgradeMode() {
1801 $args = explode('/', CRM_Utils_Array
::value('q', $_GET));
1802 $upgradeInProcess = CRM_Core_Session
::singleton()->get('isUpgradePending');
1803 if ((isset($args[1]) && $args[1] == 'upgrade') ||
$upgradeInProcess) {
1812 * Determine the standard URL for viewing or editing the specified link.
1814 * This function delegates the decision-making to (a) the hook system and
1815 * (b) the BAO system.
1817 * @param array $crudLinkSpec
1819 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
1820 * - entity_table: string, eg "civicrm_contact"
1823 * @return array|NULL
1824 * NULL if unavailable, or an array. array has keys:
1830 public static function createDefaultCrudLink($crudLinkSpec) {
1831 $crudLinkSpec['action'] = CRM_Utils_Array
::value('action', $crudLinkSpec, CRM_Core_Action
::VIEW
);
1832 $daoClass = CRM_Core_DAO_AllCoreTables
::getClassForTable($crudLinkSpec['entity_table']);
1837 $baoClass = str_replace('_DAO_', '_BAO_', $daoClass);
1838 if (!class_exists($baoClass)) {
1842 $bao = new $baoClass();
1843 $bao->id
= $crudLinkSpec['entity_id'];
1844 if (!$bao->find(TRUE)) {
1849 CRM_Utils_Hook
::crudLink($crudLinkSpec, $bao, $link);
1850 if (empty($link) && is_callable([$bao, 'createDefaultCrudLink'])) {
1851 $link = $bao->createDefaultCrudLink($crudLinkSpec);
1854 if (!empty($link)) {
1855 if (!isset($link['url'])) {
1856 $link['url'] = self
::url($link['path'], $link['query'], TRUE, NULL, FALSE);