3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
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
35 * System wide utilities.
37 class CRM_Utils_System
{
39 static $_callbacks = NULL;
48 * Compose a new URL string from the current URL string.
50 * Used by all the framework components, specifically,
53 * @param string $urlVar
54 * The url variable being considered (i.e. crmPageID, crmSortID etc).
55 * @param bool $includeReset
56 * (optional) Whether to include the reset GET string (if present).
57 * @param bool $includeForce
58 * (optional) Whether to include the force GET string (if present).
60 * (optional) The path to use for the new url.
61 * @param bool|string $absolute
62 * (optional) Whether to return an absolute URL.
67 public static function makeURL($urlVar, $includeReset = FALSE, $includeForce = TRUE, $path = NULL, $absolute = FALSE) {
69 $config = CRM_Core_Config
::singleton();
70 $path = CRM_Utils_Array
::value($config->userFrameworkURLVar
, $_GET);
79 CRM_Utils_System
::getLinksUrl($urlVar, $includeReset, $includeForce),
85 * Get the query string and clean it up.
87 * Strips some variables that should not be propagated, specifically variables
88 * like 'reset'. Also strips any side-affect actions (e.g. export).
90 * This function is copied mostly verbatim from Pager.php (_getLinksUrl)
92 * @param string $urlVar
93 * The URL variable being considered (e.g. crmPageID, crmSortID etc).
94 * @param bool $includeReset
95 * (optional) By default this is FALSE, meaning that the reset parameter
96 * is skipped. Set to TRUE to leave the reset parameter as-is.
97 * @param bool $includeForce
99 * @param bool $skipUFVar
104 public static function getLinksUrl($urlVar, $includeReset = FALSE, $includeForce = TRUE, $skipUFVar = TRUE) {
105 // Sort out query string to prevent messy urls
106 $querystring = array();
110 if (!empty($_SERVER['QUERY_STRING'])) {
111 $qs = explode('&', str_replace('&', '&', $_SERVER['QUERY_STRING']));
112 for ($i = 0, $cnt = count($qs); $i < $cnt; $i++
) {
113 // check first if exist a pair
114 if (strstr($qs[$i], '=') !== FALSE) {
115 list($name, $value) = explode('=', $qs[$i]);
116 if ($name != $urlVar) {
117 $name = rawurldecode($name);
118 // check for arrays in parameters: site.php?foo[]=1&foo[]=2&foo[]=3
119 if ((strpos($name, '[') !== FALSE) &&
120 (strpos($name, ']') !== FALSE)
140 // Ok this is a big assumption but usually works
141 // If we are in snippet mode, retain the 'section' param, if not, get rid
143 if (!empty($qs['snippet'])) {
144 unset($qs['snippet']);
147 unset($qs['section']);
151 $config = CRM_Core_Config
::singleton();
152 unset($qs[$config->userFrameworkURLVar
]);
155 foreach ($qs as $name => $value) {
156 if ($name != 'reset' ||
$includeReset) {
157 $querystring[] = $name . '=' . $value;
161 $querystring = array_merge($querystring, array_unique($arrays));
163 $url = implode('&', $querystring);
165 $url .= (!empty($querystring) ?
'&' : '') . $urlVar . '=';
172 * If we are using a theming system, invoke theme, else just print the
175 * @param string $content
176 * The content that will be themed.
178 * (optional) Are we displaying to the screen or bypassing theming?
179 * @param bool $maintenance
180 * (optional) For maintenance mode.
184 public static function theme(
189 $config = &CRM_Core_Config
::singleton();
190 return $config->userSystem
->theme($content, $print, $maintenance);
194 * Generate a query string if input is an array.
196 * @param array|string $query
199 public static function makeQueryString($query) {
200 if (is_array($query)) {
202 foreach ($query as $key => $value) {
203 $buf .= ($buf ?
'&' : '') . urlencode($key) . '=' . urlencode($value);
211 * Generate an internal CiviCRM URL.
213 * @param string $path
214 * The path being linked to, such as "civicrm/add".
215 * @param array|string $query
216 * A query string to append to the link, or an array of key-value pairs.
217 * @param bool $absolute
218 * Whether to force the output to be an absolute link (beginning with a
219 * URI-scheme such as 'http:'). Useful for links that will be displayed
220 * outside the site, such as in an RSS feed.
221 * @param string $fragment
222 * A fragment identifier (named anchor) to append to the link.
224 * @param bool $htmlize
225 * @param bool $frontend
226 * @param bool $forceBackend
228 * An HTML string containing a link to the given path.
230 public static function url(
237 $forceBackend = FALSE
239 $query = self
::makeQueryString($query);
241 // we have a valid query and it has not yet been transformed
242 if ($htmlize && !empty($query) && strpos($query, '&') === FALSE) {
243 $query = htmlentities($query);
246 $config = CRM_Core_Config
::singleton();
247 return $config->userSystem
->url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
254 * @param bool $absolute
255 * @param null $fragment
256 * @param bool $htmlize
257 * @param bool $frontend
258 * @param bool $forceBackend
262 public static function href(
263 $text, $path = NULL, $query = NULL, $absolute = TRUE,
264 $fragment = NULL, $htmlize = TRUE, $frontend = FALSE, $forceBackend = FALSE
266 $url = self
::url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
267 return "<a href=\"$url\">$text</a>";
273 public static function permissionDenied() {
274 $config = CRM_Core_Config
::singleton();
275 return $config->userSystem
->permissionDenied();
281 public static function logout() {
282 $config = CRM_Core_Config
::singleton();
283 return $config->userSystem
->logout();
287 * this is a very drupal specific function for now.
289 public static function updateCategories() {
290 $config = CRM_Core_Config
::singleton();
291 if ($config->userSystem
->is_drupal
) {
292 $config->userSystem
->updateCategories();
297 * What menu path are we currently on. Called for the primary tpl
300 * the current menu path
302 public static function currentPath() {
303 $config = CRM_Core_Config
::singleton();
304 return trim(CRM_Utils_Array
::value($config->userFrameworkURLVar
, $_GET), '/');
308 * called from a template to compose a url.
310 * @param array $params
311 * List of parameters.
316 public static function crmURL($params) {
317 $p = CRM_Utils_Array
::value('p', $params);
319 $p = self
::currentPath();
324 CRM_Utils_Array
::value('q', $params),
325 CRM_Utils_Array
::value('a', $params, FALSE),
326 CRM_Utils_Array
::value('f', $params),
327 CRM_Utils_Array
::value('h', $params, TRUE),
328 CRM_Utils_Array
::value('fe', $params, FALSE),
329 CRM_Utils_Array
::value('fb', $params, FALSE)
334 * Sets the title of the page.
336 * @param string $title
337 * @param string $pageTitle
339 public static function setTitle($title, $pageTitle = NULL) {
340 self
::$title = $title;
341 $config = CRM_Core_Config
::singleton();
342 return $config->userSystem
->setTitle($title, $pageTitle);
346 * Figures and sets the userContext.
348 * Uses the referer if valid else uses the default.
350 * @param array $names
351 * Referrer should match any str in this array.
352 * @param string $default
353 * (optional) The default userContext if no match found.
355 public static function setUserContext($names, $default = NULL) {
358 $session = CRM_Core_Session
::singleton();
359 $referer = CRM_Utils_Array
::value('HTTP_REFERER', $_SERVER);
361 if ($referer && !empty($names)) {
362 foreach ($names as $name) {
363 if (strstr($referer, $name)) {
371 $session->pushUserContext($url);
376 * Gets a class name for an object.
378 * @param object $object
379 * Object whose class name is needed.
382 * The class name of the object.
384 public static function getClassName($object) {
385 return get_class($object);
389 * Redirect to another URL.
392 * The URL to provide to the browser via the Location header.
394 public static function redirect($url = NULL) {
396 $url = self
::url('civicrm/dashboard', 'reset=1');
398 // replace the & characters with &
399 // this is kinda hackish but not sure how to do it right
400 $url = str_replace('&', '&', $url);
402 // If we are in a json context, respond appropriately
403 if (CRM_Utils_Array
::value('snippet', $_GET) === 'json') {
404 CRM_Core_Page_AJAX
::returnJsonResponse(array(
405 'status' => 'redirect',
406 'userContext' => $url,
410 self
::setHttpHeader('Location', $url);
415 * Redirect to another URL using JavaScript.
417 * Use an html based file with javascript embedded to redirect to another url
418 * This prevent the too many redirect errors emitted by various browsers
421 * (optional) The destination URL.
422 * @param string $title
423 * (optional) The page title to use for the redirect page.
424 * @param string $message
425 * (optional) The message to provide in the body of the redirect page.
427 public static function jsRedirect(
433 $url = self
::url('civicrm/dashboard', 'reset=1');
437 $title = ts('CiviCRM task in progress');
441 $message = ts('A long running CiviCRM task is currently in progress. This message will be refreshed till the task is completed');
444 // replace the & characters with &
445 // this is kinda hackish but not sure how to do it right
446 $url = str_replace('&', '&', $url);
448 $template = CRM_Core_Smarty
::singleton();
449 $template->assign('redirectURL', $url);
450 $template->assign('title', $title);
451 $template->assign('message', $message);
453 $html = $template->fetch('CRM/common/redirectJS.tpl');
461 * Append an additional breadcrumb tag to the existing breadcrumbs.
463 * @param $breadCrumbs
465 public static function appendBreadCrumb($breadCrumbs) {
466 $config = CRM_Core_Config
::singleton();
467 return $config->userSystem
->appendBreadCrumb($breadCrumbs);
471 * Reset an additional breadcrumb tag to the existing breadcrumb.
473 public static function resetBreadCrumb() {
474 $config = CRM_Core_Config
::singleton();
475 return $config->userSystem
->resetBreadCrumb();
479 * Append a string to the head of the HTML file.
483 public static function addHTMLHead($bc) {
484 $config = CRM_Core_Config
::singleton();
485 return $config->userSystem
->addHTMLHead($bc);
489 * Determine the post URL for a form.
492 * The default action if one is pre-specified.
495 * The URL to post the form.
497 public static function postURL($action) {
498 $config = CRM_Core_Config
::singleton();
499 return $config->userSystem
->postURL($action);
503 * Get the base URL of the system.
507 public static function baseURL() {
508 $config = CRM_Core_Config
::singleton();
509 return $config->userFrameworkBaseURL
;
514 public static function authenticateAbort($message, $abort) {
526 * (optional) Whether to exit; defaults to true.
530 public static function authenticateKey($abort = TRUE) {
531 // also make sure the key is sent and is valid
532 $key = trim(CRM_Utils_Array
::value('key', $_REQUEST));
534 $docAdd = "More info at:" . CRM_Utils_System
::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
537 return self
::authenticateAbort(
538 "ERROR: You need to send a valid key to execute this file. " . $docAdd . "\n",
543 $siteKey = defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: NULL;
545 if (!$siteKey ||
empty($siteKey)) {
546 return self
::authenticateAbort(
547 "ERROR: You need to set a valid site key in civicrm.settings.php. " . $docAdd . "\n",
552 if (strlen($siteKey) < 8) {
553 return self
::authenticateAbort(
554 "ERROR: Site key needs to be greater than 7 characters in civicrm.settings.php. " . $docAdd . "\n",
559 if ($key !== $siteKey) {
560 return self
::authenticateAbort(
561 "ERROR: Invalid key value sent. " . $docAdd . "\n",
573 * @param bool $storeInSession
574 * @param bool $loadCMSBootstrap
575 * @param bool $requireKey
579 public static function authenticateScript($abort = TRUE, $name = NULL, $pass = NULL, $storeInSession = TRUE, $loadCMSBootstrap = TRUE, $requireKey = TRUE) {
580 // auth to make sure the user has a login/password to do a shell operation
581 // later on we'll link this to acl's
583 $name = trim(CRM_Utils_Array
::value('name', $_REQUEST));
584 $pass = trim(CRM_Utils_Array
::value('pass', $_REQUEST));
587 // its ok to have an empty password
589 return self
::authenticateAbort(
590 "ERROR: You need to send a valid user name and password to execute this file\n",
595 if ($requireKey && !self
::authenticateKey($abort)) {
599 $result = CRM_Utils_System
::authenticate($name, $pass, $loadCMSBootstrap);
601 return self
::authenticateAbort(
602 "ERROR: Invalid username and/or password\n",
606 elseif ($storeInSession) {
607 // lets store contact id and user id in session
608 list($userID, $ufID, $randomNumber) = $result;
609 if ($userID && $ufID) {
610 $config = CRM_Core_Config
::singleton();
611 $config->userSystem
->setUserSession(array($userID, $ufID));
614 return self
::authenticateAbort(
615 "ERROR: Unexpected error, could not match userID and contactID",
625 * Authenticate the user against the uf db.
627 * In case of successful authentication, returns an array consisting of
628 * (contactID, ufID, unique string). Returns FALSE if authentication is
631 * @param string $name
633 * @param string $password
635 * @param bool $loadCMSBootstrap
638 * @return false|array
640 public static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
641 $config = CRM_Core_Config
::singleton();
643 /* Before we do any loading, let's start the session and write to it.
644 * We typically call authenticate only when we need to bootstrap the CMS
645 * directly via Civi and hence bypass the normal CMS auth and bootstrap
646 * process typically done in CLI and cron scripts. See: CRM-12648
648 * Q: Can we move this to the userSystem class so that it can be tuned
649 * per-CMS? For example, when dealing with UnitTests UF, there's no
652 $session = CRM_Core_Session
::singleton();
653 $session->set('civicrmInitSession', TRUE);
655 if ($config->userFrameworkDSN
) {
656 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
658 return $config->userSystem
->authenticate($name, $password, $loadCMSBootstrap, $realPath);
662 * Set a message in the UF to display to a user.
664 * @param string $message
665 * The message to set.
667 public static function setUFMessage($message) {
668 $config = CRM_Core_Config
::singleton();
669 return $config->userSystem
->setMessage($message);
674 * Determine whether a value is null-ish.
677 * The value to check for null.
680 public static function isNull($value) {
681 // FIXME: remove $value = 'null' string test when we upgrade our DAO code to handle passing null in a better way.
682 if (!isset($value) ||
$value === NULL ||
$value === '' ||
$value === 'null') {
685 if (is_array($value)) {
686 // @todo Reuse of the $value variable = asking for trouble.
687 foreach ($value as $key => $value) {
688 if (!self
::isNull($value)) {
698 * Obscure all but the last few digits of a credit card number.
700 * @param string $number
701 * The credit card number to obscure.
703 * (optional) The number of digits to preserve unmodified.
705 * The obscured credit card number.
707 public static function mungeCreditCard($number, $keep = 4) {
708 $number = trim($number);
709 if (empty($number)) {
712 $replace = str_repeat('*', strlen($number) - $keep);
713 return substr_replace($number, $replace, 0, -$keep);
717 * Determine which PHP modules are loaded.
721 private static function parsePHPModules() {
723 phpinfo(INFO_MODULES
);
724 $s = ob_get_contents();
727 $s = strip_tags($s, '<h2><th><td>');
728 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/', "<info>\\1</info>", $s);
729 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/', "<info>\\1</info>", $s);
730 $vTmp = preg_split('/(<h2>[^<]+<\/h2>)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE
);
732 for ($i = 1; $i < count($vTmp); $i++
) {
733 if (preg_match('/<h2>([^<]+)<\/h2>/', $vTmp[$i], $vMat)) {
734 $vName = trim($vMat[1]);
735 $vTmp2 = explode("\n", $vTmp[$i +
1]);
736 foreach ($vTmp2 as $vOne) {
737 $vPat = '<info>([^<]+)<\/info>';
738 $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
739 $vPat2 = "/$vPat\s*$vPat/";
741 if (preg_match($vPat3, $vOne, $vMat)) {
742 $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]), trim($vMat[3]));
745 elseif (preg_match($vPat2, $vOne, $vMat)) {
746 $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
755 * Get a setting from a loaded PHP module.
757 public static function getModuleSetting($pModuleName, $pSetting) {
758 $vModules = self
::parsePHPModules();
759 return $vModules[$pModuleName][$pSetting];
766 * @return mixed|string
768 public static function memory($title = NULL) {
771 $pid = posix_getpid();
774 $memory = str_replace("\n", '', shell_exec("ps -p" . $pid . " -o rss="));
775 $memory .= ", " . time();
777 CRM_Core_Error
::debug_var($title, $memory);
783 * @param string $name
784 * @param string $mimeType
787 * @param bool $output
788 * @param string $disposition
790 public static function download(
791 $name, $mimeType, &$buffer,
794 $disposition = 'attachment'
796 $now = gmdate('D, d M Y H:i:s') . ' GMT';
798 self
::setHttpHeader('Content-Type', $mimeType);
799 self
::setHttpHeader('Expires', $now);
801 // lem9 & loic1: IE needs specific headers
802 $isIE = strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE');
804 $fileString = "filename=\"{$name}.{$ext}\"";
807 $fileString = "filename=\"{$name}\"";
810 self
::setHttpHeader("Content-Disposition", "inline; $fileString");
811 self
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
812 self
::setHttpHeader('Pragma', 'public');
815 self
::setHttpHeader("Content-Disposition", "$disposition; $fileString");
816 self
::setHttpHeader('Pragma', 'no-cache');
826 * Gather and print (and possibly log) amount of used memory.
828 * @param string $title
830 * (optional) Whether to log the memory usage information.
832 public static function xMemory($title = NULL, $log = FALSE) {
833 $mem = (float ) xdebug_memory_usage() / (float ) (1024);
834 $mem = number_format($mem, 5) . ", " . time();
836 echo "<p>$title: $mem<p>";
838 CRM_Core_Error
::debug_var($title, $mem);
841 echo "<p>$title: $mem<p>";
847 * Take a URL (or partial URL) and make it better.
849 * Currently, URLs pass straight through unchanged unless they are "seriously
850 * malformed" (see http://us2.php.net/parse_url).
853 * The URL to operate on.
857 public static function fixURL($url) {
858 $components = parse_url($url);
864 // at some point we'll add code here to make sure the url is not
865 // something that will mess up, so we need to clean it up here
870 * Make sure a callback is valid in the current context.
872 * @param string $callback
873 * Name of the function to check.
877 public static function validCallback($callback) {
878 if (self
::$_callbacks === NULL) {
879 self
::$_callbacks = array();
882 if (!array_key_exists($callback, self
::$_callbacks)) {
883 if (strpos($callback, '::') !== FALSE) {
884 list($className, $methodName) = explode('::', $callback);
885 $fileName = str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
886 // ignore errors if any
887 @include_once
$fileName;
888 if (!class_exists($className)) {
889 self
::$_callbacks[$callback] = FALSE;
892 // instantiate the class
893 $object = new $className();
894 if (!method_exists($object, $methodName)) {
895 self
::$_callbacks[$callback] = FALSE;
898 self
::$_callbacks[$callback] = TRUE;
903 self
::$_callbacks[$callback] = function_exists($callback);
906 return self
::$_callbacks[$callback];
910 * Like PHP's built-in explode(), but always return an array of $limit items.
912 * This serves as a wrapper to the PHP explode() function. In the event that
913 * PHP's explode() returns an array with fewer than $limit elements, pad
914 * the end of the array with NULLs.
916 * @param string $separator
917 * @param string $string
921 public static function explode($separator, $string, $limit) {
922 $result = explode($separator, $string, $limit);
923 for ($i = count($result); $i < $limit; $i++
) {
932 * @param bool $addCookie
937 public static function checkURL($url, $addCookie = FALSE) {
938 // make a GET request to $url
939 $ch = curl_init($url);
941 curl_setopt($ch, CURLOPT_COOKIE
, http_build_query($_COOKIE));
943 // it's quite alright to use a self-signed cert
944 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, 0);
946 // lets capture the return stuff rather than echo
947 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, TRUE);
949 // CRM-13227, CRM-14744: only return the SSL error status
950 return (curl_exec($ch) !== FALSE);
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 public 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',
982 * @param bool $encode
986 public static function formatWikiURL($string, $encode = FALSE) {
987 $items = explode(' ', trim($string), 2);
988 if (count($items) == 2) {
996 $url = $encode ? self
::urlEncode($items[0]) : $items[0];
997 return "<a href=\"$url\">$title</a>";
1001 * @param string $url
1003 * @return null|string
1005 public static function urlEncode($url) {
1006 $items = parse_url($url);
1007 if ($items === FALSE) {
1011 if (empty($items['query'])) {
1015 $items['query'] = urlencode($items['query']);
1017 $url = $items['scheme'] . '://';
1018 if (!empty($items['user'])) {
1019 $url .= "{$items['user']}:{$items['pass']}@";
1022 $url .= $items['host'];
1023 if (!empty($items['port'])) {
1024 $url .= ":{$items['port']}";
1027 $url .= "{$items['path']}?{$items['query']}";
1028 if (!empty($items['fragment'])) {
1029 $url .= "#{$items['fragment']}";
1036 * Return the running civicrm version.
1041 public static function version() {
1045 $verFile = implode(DIRECTORY_SEPARATOR
,
1046 array(dirname(__FILE__
), '..', '..', 'civicrm-version.php')
1048 if (file_exists($verFile)) {
1049 require_once $verFile;
1050 if (function_exists('civicrmVersion')) {
1051 $info = civicrmVersion();
1052 $version = $info['version'];
1056 // svn installs don't have version.txt by default. In that case version.xml should help -
1057 $verFile = implode(DIRECTORY_SEPARATOR
,
1058 array(dirname(__FILE__
), '..', '..', 'xml', 'version.xml')
1060 if (file_exists($verFile)) {
1061 $str = file_get_contents($verFile);
1062 $xmlObj = simplexml_load_string($str);
1063 $version = (string) $xmlObj->version_no
;
1068 if (!CRM_Utils_System
::isVersionFormatValid($version)) {
1069 CRM_Core_Error
::fatal('Unknown codebase version.');
1077 * Determines whether a string is a valid CiviCRM version string.
1079 * @param string $version
1080 * Version string to be checked.
1083 public static function isVersionFormatValid($version) {
1084 return preg_match("/^(\d{1,2}\.){2,3}(\d{1,2}|(alpha|beta)\d{1,2})(\.upgrade)?$/", $version);
1088 * Wraps or emulates PHP's getallheaders() function.
1090 public static function getAllHeaders() {
1091 if (function_exists('getallheaders')) {
1092 return getallheaders();
1095 // emulate get all headers
1096 // http://www.php.net/manual/en/function.getallheaders.php#66335
1098 foreach ($_SERVER as $name => $value) {
1099 if (substr($name, 0, 5) == 'HTTP_') {
1100 $headers[str_replace(' ',
1102 ucwords(strtolower(str_replace('_',
1113 public static function getRequestHeaders() {
1114 if (function_exists('apache_request_headers')) {
1115 return apache_request_headers();
1123 * Determine whether this is an SSL request.
1125 * Note that we inline this function in install/civicrm.php, so if you change
1126 * this function, please go and change the code in the install script as well.
1128 public static function isSSL() {
1130 (isset($_SERVER['HTTPS']) &&
1131 !empty($_SERVER['HTTPS']) &&
1132 strtolower($_SERVER['HTTPS']) != 'off') ?
TRUE : FALSE;
1135 public static function redirectToSSL($abort = FALSE) {
1136 $config = CRM_Core_Config
::singleton();
1137 $req_headers = self
::getRequestHeaders();
1138 // FIXME: Shouldn't the X-Forwarded-Proto check be part of CRM_Utils_System::isSSL()?
1139 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'enableSSL') &&
1141 strtolower(CRM_Utils_Array
::value('X_FORWARDED_PROTO', $req_headers)) != 'https'
1143 // ensure that SSL is enabled on a civicrm url (for cookie reasons etc)
1144 $url = "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
1145 if (!self
::checkURL($url, TRUE)) {
1147 CRM_Core_Error
::fatal('HTTPS is not set up on this machine');
1150 CRM_Core_Session
::setStatus(ts('HTTPS is not set up on this machine'), ts('Warning'), 'alert');
1151 // admin should be the only one following this
1152 // since we dont want the user stuck in a bad place
1156 CRM_Utils_System
::redirect($url);
1161 * Get logged in user's IP address.
1163 * Get IP address from HTTP REMOTE_ADDR header. If the CMS is Drupal then use
1164 * the Drupal function as this also handles reverse proxies (based on proper
1165 * configuration in settings.php)
1167 * @param bool $strictIPV4
1168 * (optional) Whether to return only IPv4 addresses.
1171 * IP address of logged in user.
1173 public static function ipAddress($strictIPV4 = TRUE) {
1174 $address = CRM_Utils_Array
::value('REMOTE_ADDR', $_SERVER);
1176 $config = CRM_Core_Config
::singleton();
1177 if ($config->userSystem
->is_drupal
&& function_exists('ip_address')) {
1178 // drupal function handles the server being behind a proxy securely. We still have legacy ipn methods
1179 // that reach this point without bootstrapping hence the check that the fn exists
1180 $address = ip_address();
1184 if ($address == '::1') {
1185 $address = '127.0.0.1';
1188 // when we need to have strictly IPV4 ip address
1189 // convert ipV6 to ipV4
1191 // this converts 'IPV4 mapped IPV6 address' to IPV4
1192 if (filter_var($address, FILTER_VALIDATE_IP
, FILTER_FLAG_IPV6
) && strstr($address, '::ffff:')) {
1193 $address = ltrim($address, '::ffff:');
1201 * Get the referring / previous page URL.
1204 * The previous page URL
1206 public 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.
1216 public static function getDocBaseURL() {
1217 // FIXME: move this to configuration at some stage
1218 return 'http://book.civicrm.org/';
1222 * Returns wiki (alternate) documentation URL base.
1227 public static function getWikiBaseURL() {
1228 // FIXME: move this to configuration at some stage
1229 return 'http://wiki.civicrm.org/confluence/display/CRMDOC/';
1233 * Returns URL or link to documentation page, based on provided parameters.
1235 * For use in PHP code.
1236 * WARNING: Always returns URL, if ts function is not defined ($URLonly has
1239 * @param string $page
1240 * Title of documentation wiki page.
1241 * @param bool $URLonly
1242 * (optional) Whether to return URL only or full HTML link (default).
1243 * @param string $text
1244 * (optional) Text of HTML link (no effect if $URLonly = false).
1245 * @param string $title
1246 * (optional) Tooltip text for HTML link (no effect if $URLonly = false)
1247 * @param string $style
1248 * (optional) Style attribute value for HTML link (no effect if $URLonly = false)
1250 * @param null $resource
1253 * URL or link to documentation page, based on provided parameters.
1255 public 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();
1263 $docBaseURL = self
::getDocBaseURL();
1265 return $docBaseURL . str_replace(' ', '+', $page);
1270 'URLonly' => $URLonly,
1274 'resource' => $resource,
1276 return self
::docURL($params);
1281 * Returns URL or link to documentation page, based on provided parameters.
1283 * For use in templates code.
1285 * @param array $params
1286 * An array of parameters (see CRM_Utils_System::docURL2 method for names)
1288 * @return null|string
1289 * URL or link to documentation page, based on provided parameters.
1291 public static function docURL($params) {
1293 if (!isset($params['page'])) {
1297 if (CRM_Utils_Array
::value('resource', $params) == 'wiki') {
1298 $docBaseURL = self
::getWikiBaseURL();
1301 $docBaseURL = self
::getDocBaseURL();
1304 if (!isset($params['title']) or $params['title'] === NULL) {
1305 $params['title'] = ts('Opens documentation in a new window.');
1308 if (!isset($params['text']) or $params['text'] === NULL) {
1309 $params['text'] = ts('(learn more...)');
1312 if (!isset($params['style']) ||
$params['style'] === NULL) {
1316 $style = "style=\"{$params['style']}\"";
1319 $link = $docBaseURL . str_replace(' ', '+', $params['page']);
1321 if (isset($params['URLonly']) && $params['URLonly'] == TRUE) {
1325 return "<a href=\"{$link}\" $style target=\"_blank\" class=\"crm-doc-link no-popup\" title=\"{$params['title']}\">{$params['text']}</a>";
1330 * Get the locale of the hosting CMS.
1333 * The used locale or null for none.
1335 public static function getUFLocale() {
1336 $config = CRM_Core_Config
::singleton();
1337 return $config->userSystem
->getUFLocale();
1341 * Set the locale of the hosting CMS.
1343 * For example, a mailing will want to change the CMS language so that
1344 * URLs are in the correct language (such as the Drupal language prefix).
1346 * @param string $civicrm_language
1347 * An array of parameters (see CRM_Utils_System::docURL2 method for names)
1350 * Returns whether the locale was successfully changed.
1352 public static function setUFLocale($civicrm_language) {
1353 $config = CRM_Core_Config
::singleton();
1354 return $config->userSystem
->setUFLocale($civicrm_language);
1358 * Execute external or internal URLs and return server response.
1360 * @param string $url
1362 * @param bool $addCookie
1363 * Whether to provide a cookie. Should be true to access internal URLs.
1366 * Response from URL.
1368 public static function getServerResponse($url, $addCookie = TRUE) {
1369 CRM_Core_TemporaryErrorScope
::ignoreException();
1370 require_once 'HTTP/Request.php';
1371 $request = new HTTP_Request($url);
1374 foreach ($_COOKIE as $name => $value) {
1375 $request->addCookie($name, $value);
1379 if (isset($_SERVER['AUTH_TYPE'])) {
1380 $request->setBasicAuth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
1383 $config = CRM_Core_Config
::singleton();
1384 if ($config->userFramework
== 'WordPress') {
1385 session_write_close();
1388 $request->sendRequest();
1389 $response = $request->getResponseBody();
1395 * Exit with provided exit code.
1397 * @param int $status
1398 * (optional) Code with which to exit.
1400 public static function civiExit($status = 0) {
1401 // move things to CiviCRM cache as needed
1402 CRM_Core_Session
::storeSessionObjects();
1408 * Reset the various system caches and some important static variables.
1410 public static function flushCache() {
1411 // flush out all cache entries so we can reload new data
1412 // a bit aggressive, but livable for now
1413 $cache = CRM_Utils_Cache
::singleton();
1416 // also reset the various static memory caches
1418 // reset the memory or array cache
1419 CRM_Core_BAO_Cache
::deleteGroup('contact fields', NULL, FALSE);
1422 CRM_ACL_BAO_Cache
::resetCache();
1424 // reset various static arrays used here
1425 CRM_Contact_BAO_Contact
::$_importableFields = CRM_Contact_BAO_Contact
::$_exportableFields
1426 = CRM_Contribute_BAO_Contribution
::$_importableFields
1427 = CRM_Contribute_BAO_Contribution
::$_exportableFields
1428 = CRM_Pledge_BAO_Pledge
::$_exportableFields = CRM_Contribute_BAO_Query
::$_contributionFields
1429 = CRM_Core_BAO_CustomField
::$_importFields
1430 = CRM_Core_BAO_Cache
::$_cache = CRM_Core_DAO
::$_dbColumnValueCache = NULL;
1432 CRM_Core_OptionGroup
::flushAll();
1433 CRM_Utils_PseudoConstant
::flushAll();
1437 * Load CMS bootstrap.
1439 * @param array $params
1440 * Array with uid name and pass
1441 * @param bool $loadUser
1442 * Boolean load user or not.
1443 * @param bool $throwError
1446 public static function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
1447 if (!is_array($params)) {
1450 $config = CRM_Core_Config
::singleton();
1451 return $config->userSystem
->loadBootStrap($params, $loadUser, $throwError, $realPath);
1455 * Check if user is logged in.
1459 public static function isUserLoggedIn() {
1460 $config = CRM_Core_Config
::singleton();
1461 return $config->userSystem
->isUserLoggedIn();
1465 * Get current logged in user id.
1468 * ufId, currently logged in user uf id.
1470 public static function getLoggedInUfID() {
1471 $config = CRM_Core_Config
::singleton();
1472 return $config->userSystem
->getLoggedInUfID();
1475 public static function baseCMSURL() {
1476 static $_baseURL = NULL;
1478 $config = CRM_Core_Config
::singleton();
1479 $_baseURL = $userFrameworkBaseURL = $config->userFrameworkBaseURL
;
1481 if ($config->userFramework
== 'Joomla') {
1483 // we need to remove the administrator/ from the end
1484 $_baseURL = str_replace("/administrator/", "/", $userFrameworkBaseURL);
1488 global $civicrm_root;
1489 if (strpos($civicrm_root,
1490 DIRECTORY_SEPARATOR
. 'sites' .
1491 DIRECTORY_SEPARATOR
. 'all' .
1492 DIRECTORY_SEPARATOR
. 'modules'
1495 $startPos = strpos($civicrm_root,
1496 DIRECTORY_SEPARATOR
. 'sites' . DIRECTORY_SEPARATOR
1498 $endPos = strpos($civicrm_root,
1499 DIRECTORY_SEPARATOR
. 'modules' . DIRECTORY_SEPARATOR
1501 if ($startPos && $endPos) {
1502 // if component is in sites/SITENAME/modules
1503 $siteName = substr($civicrm_root,
1505 $endPos - $startPos - 7
1508 $_baseURL = $userFrameworkBaseURL . "sites/$siteName/";
1517 * Given a URL, return a relative URL if possible.
1519 * @param string $url
1522 public static function relativeURL($url) {
1523 // check if url is relative, if so return immediately
1524 if (substr($url, 0, 4) != 'http') {
1528 // make everything relative from the baseFilePath
1529 $baseURL = self
::baseCMSURL();
1531 // check if baseURL is a substr of $url, if so
1532 // return rest of string
1533 if (substr($url, 0, strlen($baseURL)) == $baseURL) {
1534 return substr($url, strlen($baseURL));
1537 // return the original value
1542 * Produce an absolute URL from a possibly-relative URL.
1544 * @param string $url
1545 * @param bool $removeLanguagePart
1549 public static function absoluteURL($url, $removeLanguagePart = FALSE) {
1550 // check if url is already absolute, if so return immediately
1551 if (substr($url, 0, 4) == 'http') {
1555 // make everything absolute from the baseFileURL
1556 $baseURL = self
::baseCMSURL();
1558 //CRM-7622: drop the language from the URL if requested (and it’s there)
1559 $config = CRM_Core_Config
::singleton();
1560 if ($removeLanguagePart) {
1561 $baseURL = self
::languageNegotiationURL($baseURL, FALSE, TRUE);
1564 return $baseURL . $url;
1568 * Clean url, replaces first '&' with '?'
1570 * @param string $url
1575 public static function cleanUrl($url) {
1580 if ($pos = strpos($url, '&')) {
1581 $url = substr_replace($url, '?', $pos, 1);
1588 * Format the url as per language Negotiation.
1590 * @param string $url
1592 * @param bool $addLanguagePart
1593 * @param bool $removeLanguagePart
1598 public static function languageNegotiationURL(
1600 $addLanguagePart = TRUE,
1601 $removeLanguagePart = FALSE
1603 $config = &CRM_Core_Config
::singleton();
1604 return $config->userSystem
->languageNegotiationURL($url, $addLanguagePart, $removeLanguagePart);
1608 * Append the contents of an 'extra' smarty template file if it is present in
1609 * the custom template directory. This does not work if there are
1610 * multiple custom template directories
1612 * @param string $fileName
1613 * The name of the tpl file that we are processing.
1614 * @param string $content
1615 * The current content string. May be modified by this function.
1616 * @param string $overideFileName
1617 * (optional) Sent by contribution/event reg/profile pages which uses a id
1618 * specific extra file name if present.
1620 public static function appendTPLFile(
1623 $overideFileName = NULL
1625 $template = CRM_Core_Smarty
::singleton();
1626 if ($overideFileName) {
1627 $additionalTPLFile = $overideFileName;
1630 $additionalTPLFile = str_replace('.tpl', '.extra.tpl', $fileName);
1633 if ($template->template_exists($additionalTPLFile)) {
1634 $content .= $template->fetch($additionalTPLFile);
1639 * Get a list of all files that are found within the directories
1640 * that are the result of appending the provided relative path to
1641 * each component of the PHP include path.
1643 * @author Ken Zalewski
1645 * @param string $relpath
1646 * A relative path, typically pointing to a directory with multiple class
1650 * An array of files that exist in one or more of the directories that are
1651 * referenced by the relative path when appended to each element of the PHP
1654 public static function listIncludeFiles($relpath) {
1655 $file_list = array();
1656 $inc_dirs = explode(PATH_SEPARATOR
, get_include_path());
1657 foreach ($inc_dirs as $inc_dir) {
1658 $target_dir = $inc_dir . DIRECTORY_SEPARATOR
. $relpath;
1659 if (is_dir($target_dir)) {
1660 $cur_list = scandir($target_dir);
1661 foreach ($cur_list as $fname) {
1662 if ($fname != '.' && $fname != '..') {
1663 $file_list[$fname] = $fname;
1672 * Get a list of all "plugins" (PHP classes that implement a piece of
1673 * functionality using a well-defined interface) that are found in a
1674 * particular CiviCRM directory (both custom and core are searched).
1676 * @author Ken Zalewski
1678 * @param string $relpath
1679 * A relative path referencing a directory that contains one or more
1681 * @param string $fext
1682 * (optional) Only files with this extension will be considered to be
1684 * @param array $skipList
1685 * (optional) List of files to skip.
1688 * List of plugins, where the plugin name is both the key and the value of
1691 public static function getPluginList($relpath, $fext = '.php', $skipList = array()) {
1692 $fext_len = strlen($fext);
1694 $inc_files = CRM_Utils_System
::listIncludeFiles($relpath);
1695 foreach ($inc_files as $inc_file) {
1696 if (substr($inc_file, 0 - $fext_len) == $fext) {
1697 $plugin_name = substr($inc_file, 0, 0 - $fext_len);
1698 if (!in_array($plugin_name, $skipList)) {
1699 $plugins[$plugin_name] = $plugin_name;
1706 public static function executeScheduledJobs() {
1707 $facility = new CRM_Core_JobManager();
1708 $facility->execute(FALSE);
1710 $redirectUrl = self
::url('civicrm/admin/job', 'reset=1');
1712 CRM_Core_Session
::setStatus(
1713 ts('Scheduled jobs have been executed according to individual timing settings. Please check log for messages.'),
1714 ts('Complete'), 'success');
1716 CRM_Utils_System
::redirect($redirectUrl);
1720 * Evaluate any tokens in a URL.
1722 * @param string|FALSE $url
1723 * @return string|FALSE
1725 public static function evalUrl($url) {
1726 if (!$url ||
strpos($url, '{') === FALSE) {
1730 $config = CRM_Core_Config
::singleton();
1732 '{ver}' => CRM_Utils_System
::version(),
1733 '{uf}' => $config->userFramework
,
1734 '{php}' => phpversion(),
1735 '{sid}' => self
::getSiteID(),
1736 '{baseUrl}' => $config->userFrameworkBaseURL
,
1737 '{lang}' => $config->lcMessages
,
1738 '{co}' => $config->defaultContactCountry
,
1740 return strtr($url, array_map('urlencode', $vars));
1745 * Returns the unique identifier for this site, as used by community messages.
1747 * SiteID will be generated if it is not already stored in the settings table.
1751 public static function getSiteID() {
1752 $sid = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'site_id');
1754 $config = CRM_Core_Config
::singleton();
1755 $sid = md5('sid_' . (defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: '') . '_' . $config->userFrameworkBaseURL
);
1756 civicrm_api3('Setting', 'create', array('domain_id' => 'all', 'site_id' => $sid));
1762 * Determine whether this is a developmental system.
1766 public static function isDevelopment() {
1767 static $cache = NULL;
1768 if ($cache === NULL) {
1769 global $civicrm_root;
1770 $cache = file_exists("{$civicrm_root}/.svn") ||
file_exists("{$civicrm_root}/.git");
1778 public static function isInUpgradeMode() {
1779 $args = explode('/', CRM_Utils_Array
::value('q', $_GET));
1780 $upgradeInProcess = CRM_Core_Session
::singleton()->get('isUpgradePending');
1781 if ((isset($args[1]) && $args[1] == 'upgrade') ||
$upgradeInProcess) {
1790 * Determine the standard URL for viewing or editing the specified link.
1792 * This function delegates the decision-making to (a) the hook system and
1793 * (b) the BAO system.
1795 * @param array $crudLinkSpec
1797 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
1798 * - entity_table: string, eg "civicrm_contact"
1800 * @return array|NULL
1801 * NULL if unavailable, or an array. array has keys:
1807 public static function createDefaultCrudLink($crudLinkSpec) {
1808 $crudLinkSpec['action'] = CRM_Utils_Array
::value('action', $crudLinkSpec, CRM_Core_Action
::VIEW
);
1809 $daoClass = CRM_Core_DAO_AllCoreTables
::getClassForTable($crudLinkSpec['entity_table']);
1814 $baoClass = str_replace('_DAO_', '_BAO_', $daoClass);
1815 if (!class_exists($baoClass)) {
1819 $bao = new $baoClass();
1820 $bao->id
= $crudLinkSpec['entity_id'];
1821 if (!$bao->find(TRUE)) {
1826 CRM_Utils_Hook
::crudLink($crudLinkSpec, $bao, $link);
1827 if (empty($link) && is_callable(array($bao, 'createDefaultCrudLink'))) {
1828 $link = $bao->createDefaultCrudLink($crudLinkSpec);
1831 if (!empty($link)) {
1832 if (!isset($link['url'])) {
1833 $link['url'] = self
::url($link['path'], $link['query'], TRUE, NULL, FALSE);
1842 * @param string $name
1843 * @param string $value
1845 public static function setHttpHeader($name, $value) {
1846 CRM_Core_Config
::singleton()->userSystem
->setHttpHeader($name, $value);