Merge pull request #16659 from demeritcowboy/name-label-print-report
[civicrm-core.git] / CRM / Utils / System.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
19 * System wide utilities.
091db908
CW
20 *
21 * Provides a collection of Civi utilities + access to the CMS-dependant utilities
22 *
23 * FIXME: This is a massive and random collection that could be split into smaller services
24 *
25 * @method static mixed permissionDenied() Show access denied screen.
26 * @method static mixed logout() Log out the current user.
27 * @method static mixed updateCategories() Clear CMS caches related to the user registration/profile forms.
0efdabe7 28 * @method static appendBreadCrumb(array $breadCrumbs) Append an additional breadcrumb tag to the existing breadcrumbs.
091db908
CW
29 * @method static resetBreadCrumb() Reset an additional breadcrumb tag to the existing breadcrumb.
30 * @method static addHTMLHead(string $bc) Append a string to the head of the HTML file.
31 * @method static string postURL(int $action) Determine the post URL for a form.
32 * @method static string|null getUFLocale() Get the locale of the CMS.
33 * @method static bool setUFLocale(string $civicrm_language) Set the locale of the CMS.
34 * @method static bool isUserLoggedIn() Check if user is logged in.
35 * @method static int getLoggedInUfID() Get current logged in user id.
36 * @method static setHttpHeader(string $name, string $value) Set http header.
37 * @method static array synchronizeUsers() Create CRM contacts for all existing CMS users.
303017a1 38 * @method static appendCoreResources(\Civi\Core\Event\GenericHookEvent $e) Callback for hook_civicrm_coreResourceList.
62c20d1e 39 * @method static alterAssetUrl(\Civi\Core\Event\GenericHookEvent $e) Callback for hook_civicrm_getAssetUrl.
6a488035
TO
40 */
41class CRM_Utils_System {
42
6714d8d2 43 public static $_callbacks = NULL;
6a488035 44
5af8c999 45 /**
50bfb460
SB
46 * @var string
47 * Page title
5af8c999 48 */
6714d8d2 49 public static $title = '';
5af8c999 50
091db908
CW
51 /**
52 * Access methods in the appropriate CMS class
53 *
54 * @param $name
55 * @param $arguments
56 * @return mixed
57 */
58 public static function __callStatic($name, $arguments) {
59 $userSystem = CRM_Core_Config::singleton()->userSystem;
be2fb01f 60 return call_user_func_array([$userSystem, $name], $arguments);
091db908
CW
61 }
62
6a488035 63 /**
9911500f 64 * Compose a new URL string from the current URL string.
7890c493 65 *
6a488035
TO
66 * Used by all the framework components, specifically,
67 * pager, sort and qfc
68 *
7890c493
RS
69 * @param string $urlVar
70 * The url variable being considered (i.e. crmPageID, crmSortID etc).
71 * @param bool $includeReset
72 * (optional) Whether to include the reset GET string (if present).
73 * @param bool $includeForce
74 * (optional) Whether to include the force GET string (if present).
414e3596 75 * @param string $path
7890c493 76 * (optional) The path to use for the new url.
f4aaa82a 77 * @param bool|string $absolute
7890c493 78 * (optional) Whether to return an absolute URL.
6a488035 79 *
7890c493
RS
80 * @return string
81 * The URL fragment.
6a488035 82 */
00be9182 83 public static function makeURL($urlVar, $includeReset = FALSE, $includeForce = TRUE, $path = NULL, $absolute = FALSE) {
6a488035
TO
84 if (empty($path)) {
85 $config = CRM_Core_Config::singleton();
9c1bc317 86 $path = $_GET[$config->userFrameworkURLVar] ?? NULL;
6a488035
TO
87 if (empty($path)) {
88 return '';
89 }
90 }
91
6714d8d2 92 return self::url(
3ab88a8c
DL
93 $path,
94 CRM_Utils_System::getLinksUrl($urlVar, $includeReset, $includeForce),
95 $absolute
96 );
6a488035
TO
97 }
98
99 /**
7890c493
RS
100 * Get the query string and clean it up.
101 *
9911500f 102 * Strips some variables that should not be propagated, specifically variables
7890c493 103 * like 'reset'. Also strips any side-affect actions (e.g. export).
6a488035
TO
104 *
105 * This function is copied mostly verbatim from Pager.php (_getLinksUrl)
106 *
7890c493
RS
107 * @param string $urlVar
108 * The URL variable being considered (e.g. crmPageID, crmSortID etc).
109 * @param bool $includeReset
9911500f
RS
110 * (optional) By default this is FALSE, meaning that the reset parameter
111 * is skipped. Set to TRUE to leave the reset parameter as-is.
7890c493 112 * @param bool $includeForce
9911500f 113 * (optional)
7890c493 114 * @param bool $skipUFVar
9911500f 115 * (optional)
6a488035
TO
116 *
117 * @return string
6a488035 118 */
00be9182 119 public static function getLinksUrl($urlVar, $includeReset = FALSE, $includeForce = TRUE, $skipUFVar = TRUE) {
6a488035 120 // Sort out query string to prevent messy urls
be2fb01f
CW
121 $querystring = [];
122 $qs = [];
123 $arrays = [];
6a488035
TO
124
125 if (!empty($_SERVER['QUERY_STRING'])) {
126 $qs = explode('&', str_replace('&amp;', '&', $_SERVER['QUERY_STRING']));
127 for ($i = 0, $cnt = count($qs); $i < $cnt; $i++) {
128 // check first if exist a pair
129 if (strstr($qs[$i], '=') !== FALSE) {
130 list($name, $value) = explode('=', $qs[$i]);
131 if ($name != $urlVar) {
132 $name = rawurldecode($name);
50bfb460 133 // check for arrays in parameters: site.php?foo[]=1&foo[]=2&foo[]=3
6a488035
TO
134 if ((strpos($name, '[') !== FALSE) &&
135 (strpos($name, ']') !== FALSE)
136 ) {
137 $arrays[] = $qs[$i];
138 }
139 else {
140 $qs[$name] = $value;
141 }
142 }
143 }
144 else {
145 $qs[$qs[$i]] = '';
146 }
147 unset($qs[$i]);
148 }
149 }
150
151 if ($includeForce) {
152 $qs['force'] = 1;
153 }
154
d8249fcb 155 // Ok this is a big assumption but usually works
9911500f
RS
156 // If we are in snippet mode, retain the 'section' param, if not, get rid
157 // of it.
d8249fcb
CW
158 if (!empty($qs['snippet'])) {
159 unset($qs['snippet']);
160 }
161 else {
162 unset($qs['section']);
163 }
6a488035
TO
164
165 if ($skipUFVar) {
166 $config = CRM_Core_Config::singleton();
167 unset($qs[$config->userFrameworkURLVar]);
168 }
169
170 foreach ($qs as $name => $value) {
171 if ($name != 'reset' || $includeReset) {
172 $querystring[] = $name . '=' . $value;
173 }
174 }
175
176 $querystring = array_merge($querystring, array_unique($arrays));
6a488035 177
fe010227 178 $url = implode('&', $querystring);
3ab88a8c 179 if ($urlVar) {
fe010227 180 $url .= (!empty($querystring) ? '&' : '') . $urlVar . '=';
3ab88a8c
DL
181 }
182
183 return $url;
6a488035
TO
184 }
185
186 /**
70599df6 187 * If we are using a theming system, invoke theme, else just print the content.
6a488035 188 *
7890c493
RS
189 * @param string $content
190 * The content that will be themed.
414e3596 191 * @param bool $print
7890c493
RS
192 * (optional) Are we displaying to the screen or bypassing theming?
193 * @param bool $maintenance
194 * (optional) For maintenance mode.
6a488035 195 *
a75c13cc 196 * @return string
6a488035 197 */
971d41b1 198 public static function theme(
6a488035 199 &$content,
e7292422 200 $print = FALSE,
6a488035
TO
201 $maintenance = FALSE
202 ) {
f3a87cf4 203 return CRM_Core_Config::singleton()->userSystem->theme($content, $print, $maintenance);
6a488035
TO
204 }
205
206 /**
7890c493 207 * Generate a query string if input is an array.
6a488035 208 *
7890c493 209 * @param array|string $query
70599df6 210 *
7890c493 211 * @return string
6a488035 212 */
00be9182 213 public static function makeQueryString($query) {
6a488035
TO
214 if (is_array($query)) {
215 $buf = '';
216 foreach ($query as $key => $value) {
217 $buf .= ($buf ? '&' : '') . urlencode($key) . '=' . urlencode($value);
218 }
219 $query = $buf;
220 }
221 return $query;
222 }
223
224 /**
7890c493 225 * Generate an internal CiviCRM URL.
6a488035 226 *
7890c493
RS
227 * @param string $path
228 * The path being linked to, such as "civicrm/add".
229 * @param array|string $query
230 * A query string to append to the link, or an array of key-value pairs.
231 * @param bool $absolute
232 * Whether to force the output to be an absolute link (beginning with a
9911500f 233 * URI-scheme such as 'http:'). Useful for links that will be displayed
7890c493
RS
234 * outside the site, such as in an RSS feed.
235 * @param string $fragment
236 * A fragment identifier (named anchor) to append to the link.
fe010227 237 * @param bool $htmlize
f77dfbae 238 * Whether to encode special html characters such as &.
fe010227 239 * @param bool $frontend
f77dfbae 240 * This link should be to the CMS front end (applies to WP & Joomla).
fe010227 241 * @param bool $forceBackend
f77dfbae 242 * This link should be to the CMS back end (applies to WP & Joomla).
70599df6 243 *
7890c493
RS
244 * @return string
245 * An HTML string containing a link to the given path.
6a488035 246 */
971d41b1 247 public static function url(
6a488035 248 $path = NULL,
e7292422 249 $query = NULL,
6a488035
TO
250 $absolute = FALSE,
251 $fragment = NULL,
e7292422 252 $htmlize = TRUE,
6a488035
TO
253 $frontend = FALSE,
254 $forceBackend = FALSE
255 ) {
256 $query = self::makeQueryString($query);
257
c80e2dbf
CW
258 // Legacy handling for when the system passes around html escaped strings
259 if (strstr($query, '&amp;')) {
260 $query = html_entity_decode($query);
261 }
262
263 // Extract fragment from path or query if munged together
264 if ($query && strstr($query, '#')) {
265 list($path, $fragment) = explode('#', $query);
266 }
267 if ($path && strstr($path, '#')) {
268 list($path, $fragment) = explode('#', $path);
269 }
270
271 // Extract query from path if munged together
272 if ($path && strstr($path, '?')) {
273 list($path, $extraQuery) = explode('?', $path);
274 $query = $extraQuery . ($query ? "&$query" : '');
6a488035
TO
275 }
276
277 $config = CRM_Core_Config::singleton();
c80e2dbf
CW
278 $url = $config->userSystem->url($path, $query, $absolute, $fragment, $frontend, $forceBackend);
279
280 if ($htmlize) {
281 $url = htmlentities($url);
282 }
283
284 return $url;
6a488035
TO
285 }
286
9df3628e
AM
287 /**
288 * Generates an extern url.
289 *
290 * @param string $path
291 * The extern path, such as "extern/url".
292 * @param string $query
293 * A query string to append to the link.
294 * @param string $fragment
295 * A fragment identifier (named anchor) to append to the link.
296 * @param bool $absolute
297 * Whether to force the output to be an absolute link (beginning with a
298 * URI-scheme such as 'http:').
299 * @param bool $isSSL
300 * NULL to autodetect. TRUE to force to SSL.
b4c75c15
SL
301 *
302 * @return string rawencoded URL.
9df3628e
AM
303 */
304 public static function externUrl($path = NULL, $query = NULL, $fragment = NULL, $absolute = TRUE, $isSSL = NULL) {
305 $query = self::makeQueryString($query);
306
307 $url = Civi::paths()->getUrl("[civicrm.root]/{$path}.php", $absolute ? 'absolute' : 'relative', $isSSL)
308 . ($query ? "?$query" : "")
309 . ($fragment ? "#$fragment" : "");
310
311 $parsedUrl = CRM_Utils_Url::parseUrl($url);
312 $event = \Civi\Core\Event\GenericHookEvent::create([
313 'url' => &$parsedUrl,
314 'path' => $path,
315 'query' => $query,
316 'fragment' => $fragment,
317 'absolute' => $absolute,
318 'isSSL' => $isSSL,
319 ]);
320 Civi::service('dispatcher')->dispatch('hook_civicrm_alterExternUrl', $event);
b4c75c15 321 return urldecode(CRM_Utils_Url::unparseUrl($event->url));
9df3628e
AM
322 }
323
42a40a1c 324 /**
325 * Path of the current page e.g. 'civicrm/contact/view'
326 *
327 * @return string|null
328 */
329 public static function getUrlPath() {
330 if (isset($_GET[CRM_Core_Config::singleton()->userFrameworkURLVar])) {
331 return $_GET[CRM_Core_Config::singleton()->userFrameworkURLVar];
332 }
333 return NULL;
334 }
335
5bc392e6 336 /**
70599df6 337 * Get href.
338 *
339 * @param string $text
340 * @param string $path
341 * @param string|array $query
5bc392e6 342 * @param bool $absolute
70599df6 343 * @param string $fragment
5bc392e6
EM
344 * @param bool $htmlize
345 * @param bool $frontend
346 * @param bool $forceBackend
347 *
348 * @return string
349 */
971d41b1 350 public static function href(
a3e55d9c 351 $text, $path = NULL, $query = NULL, $absolute = TRUE,
6a488035
TO
352 $fragment = NULL, $htmlize = TRUE, $frontend = FALSE, $forceBackend = FALSE
353 ) {
354 $url = self::url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
355 return "<a href=\"$url\">$text</a>";
356 }
357
6a488035 358 /**
70599df6 359 * What menu path are we currently on. Called for the primary tpl.
6a488035 360 *
a6c01b45
CW
361 * @return string
362 * the current menu path
6a488035 363 */
00be9182 364 public static function currentPath() {
6a488035
TO
365 $config = CRM_Core_Config::singleton();
366 return trim(CRM_Utils_Array::value($config->userFrameworkURLVar, $_GET), '/');
367 }
368
369 /**
70599df6 370 * Called from a template to compose a url.
6a488035 371 *
7890c493
RS
372 * @param array $params
373 * List of parameters.
6a488035 374 *
a6c01b45
CW
375 * @return string
376 * url
6a488035 377 */
00be9182 378 public static function crmURL($params) {
9c1bc317 379 $p = $params['p'] ?? NULL;
6a488035
TO
380 if (!isset($p)) {
381 $p = self::currentPath();
382 }
383
496e07aa
DL
384 return self::url(
385 $p,
6a488035
TO
386 CRM_Utils_Array::value('q', $params),
387 CRM_Utils_Array::value('a', $params, FALSE),
388 CRM_Utils_Array::value('f', $params),
389 CRM_Utils_Array::value('h', $params, TRUE),
390 CRM_Utils_Array::value('fe', $params, FALSE),
391 CRM_Utils_Array::value('fb', $params, FALSE)
392 );
393 }
394
395 /**
7890c493 396 * Sets the title of the page.
6a488035
TO
397 *
398 * @param string $title
091db908 399 * Document title - plain text only
6a488035 400 * @param string $pageTitle
091db908 401 * Page title (if different) - may include html
6a488035 402 */
00be9182 403 public static function setTitle($title, $pageTitle = NULL) {
5af8c999 404 self::$title = $title;
6a488035
TO
405 $config = CRM_Core_Config::singleton();
406 return $config->userSystem->setTitle($title, $pageTitle);
407 }
408
409 /**
7890c493 410 * Figures and sets the userContext.
6a488035 411 *
70599df6 412 * Uses the referrer if valid else uses the default.
7890c493
RS
413 *
414 * @param array $names
50bfb460 415 * Referrer should match any str in this array.
7890c493
RS
416 * @param string $default
417 * (optional) The default userContext if no match found.
6a488035 418 */
00be9182 419 public static function setUserContext($names, $default = NULL) {
6a488035
TO
420 $url = $default;
421
422 $session = CRM_Core_Session::singleton();
9c1bc317 423 $referer = $_SERVER['HTTP_REFERER'] ?? NULL;
6a488035
TO
424
425 if ($referer && !empty($names)) {
426 foreach ($names as $name) {
427 if (strstr($referer, $name)) {
428 $url = $referer;
429 break;
430 }
431 }
432 }
433
434 if ($url) {
435 $session->pushUserContext($url);
436 }
437 }
438
439 /**
7890c493 440 * Gets a class name for an object.
6a488035 441 *
7890c493
RS
442 * @param object $object
443 * Object whose class name is needed.
6a488035 444 *
7890c493
RS
445 * @return string
446 * The class name of the object.
6a488035 447 */
00be9182 448 public static function getClassName($object) {
6a488035
TO
449 return get_class($object);
450 }
451
452 /**
7890c493 453 * Redirect to another URL.
6a488035 454 *
7890c493
RS
455 * @param string $url
456 * The URL to provide to the browser via the Location header.
f9bdf062 457 * @param array $context
458 * Optional additional information for the hook.
6a488035 459 */
f9bdf062 460 public static function redirect($url = NULL, $context = []) {
6a488035
TO
461 if (!$url) {
462 $url = self::url('civicrm/dashboard', 'reset=1');
463 }
6a488035
TO
464 // replace the &amp; characters with &
465 // this is kinda hackish but not sure how to do it right
466 $url = str_replace('&amp;', '&', $url);
0a94ab7d 467
9c1bc317 468 $context['output'] = $_GET['snippet'] ?? NULL;
f9bdf062 469
470 $parsedUrl = CRM_Utils_Url::parseUrl($url);
471 CRM_Utils_Hook::alterRedirect($parsedUrl, $context);
472 $url = CRM_Utils_Url::unparseUrl($parsedUrl);
473
0a94ab7d 474 // If we are in a json context, respond appropriately
f9bdf062 475 if ($context['output'] === 'json') {
be2fb01f 476 CRM_Core_Page_AJAX::returnJsonResponse([
0a94ab7d
CW
477 'status' => 'redirect',
478 'userContext' => $url,
be2fb01f 479 ]);
0a94ab7d
CW
480 }
481
d42a224c 482 self::setHttpHeader('Location', $url);
6a488035
TO
483 self::civiExit();
484 }
485
486 /**
7890c493
RS
487 * Redirect to another URL using JavaScript.
488 *
489 * Use an html based file with javascript embedded to redirect to another url
6a488035
TO
490 * This prevent the too many redirect errors emitted by various browsers
491 *
7890c493
RS
492 * @param string $url
493 * (optional) The destination URL.
494 * @param string $title
495 * (optional) The page title to use for the redirect page.
496 * @param string $message
497 * (optional) The message to provide in the body of the redirect page.
6a488035 498 */
971d41b1 499 public static function jsRedirect(
e7292422
TO
500 $url = NULL,
501 $title = NULL,
6a488035
TO
502 $message = NULL
503 ) {
504 if (!$url) {
505 $url = self::url('civicrm/dashboard', 'reset=1');
506 }
507
508 if (!$title) {
509 $title = ts('CiviCRM task in progress');
510 }
511
512 if (!$message) {
513 $message = ts('A long running CiviCRM task is currently in progress. This message will be refreshed till the task is completed');
514 }
515
516 // replace the &amp; characters with &
517 // this is kinda hackish but not sure how to do it right
518 $url = str_replace('&amp;', '&', $url);
519
520 $template = CRM_Core_Smarty::singleton();
521 $template->assign('redirectURL', $url);
522 $template->assign('title', $title);
523 $template->assign('message', $message);
524
525 $html = $template->fetch('CRM/common/redirectJS.tpl');
526
527 echo $html;
528
529 self::civiExit();
530 }
531
6a488035 532 /**
7890c493 533 * Get the base URL of the system.
6a488035
TO
534 *
535 * @return string
6a488035 536 */
00be9182 537 public static function baseURL() {
6a488035
TO
538 $config = CRM_Core_Config::singleton();
539 return $config->userFrameworkBaseURL;
540 }
541
7890c493 542 /**
ad37ac8e 543 * Authenticate or abort.
544 *
545 * @param string $message
546 * @param bool $abort
547 *
548 * @return bool
7890c493 549 */
00be9182 550 public static function authenticateAbort($message, $abort) {
6a488035
TO
551 if ($abort) {
552 echo $message;
553 self::civiExit(0);
554 }
555 else {
556 return FALSE;
557 }
558 }
559
7890c493 560 /**
70599df6 561 * Authenticate key.
562 *
7890c493
RS
563 * @param bool $abort
564 * (optional) Whether to exit; defaults to true.
77b97be7
EM
565 *
566 * @return bool
7890c493 567 */
00be9182 568 public static function authenticateKey($abort = TRUE) {
6a488035
TO
569 // also make sure the key is sent and is valid
570 $key = trim(CRM_Utils_Array::value('key', $_REQUEST));
571
572 $docAdd = "More info at:" . CRM_Utils_System::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
573
574 if (!$key) {
0af0e4c9
DL
575 return self::authenticateAbort(
576 "ERROR: You need to send a valid key to execute this file. " . $docAdd . "\n",
6a488035
TO
577 $abort
578 );
579 }
580
581 $siteKey = defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : NULL;
582
0af0e4c9
DL
583 if (!$siteKey || empty($siteKey)) {
584 return self::authenticateAbort(
585 "ERROR: You need to set a valid site key in civicrm.settings.php. " . $docAdd . "\n",
6a488035
TO
586 $abort
587 );
588 }
589
590 if (strlen($siteKey) < 8) {
0af0e4c9
DL
591 return self::authenticateAbort(
592 "ERROR: Site key needs to be greater than 7 characters in civicrm.settings.php. " . $docAdd . "\n",
6a488035
TO
593 $abort
594 );
595 }
596
597 if ($key !== $siteKey) {
0af0e4c9
DL
598 return self::authenticateAbort(
599 "ERROR: Invalid key value sent. " . $docAdd . "\n",
6a488035
TO
600 $abort
601 );
602 }
603
604 return TRUE;
605 }
606
7890c493 607 /**
70599df6 608 * Authenticate script.
609 *
f4aaa82a 610 * @param bool $abort
70599df6 611 * @param string $name
612 * @param string $pass
f4aaa82a
EM
613 * @param bool $storeInSession
614 * @param bool $loadCMSBootstrap
615 * @param bool $requireKey
616 *
7890c493 617 * @return bool
7890c493 618 */
00be9182 619 public static function authenticateScript($abort = TRUE, $name = NULL, $pass = NULL, $storeInSession = TRUE, $loadCMSBootstrap = TRUE, $requireKey = TRUE) {
7890c493 620 // auth to make sure the user has a login/password to do a shell operation
6a488035
TO
621 // later on we'll link this to acl's
622 if (!$name) {
623 $name = trim(CRM_Utils_Array::value('name', $_REQUEST));
624 $pass = trim(CRM_Utils_Array::value('pass', $_REQUEST));
625 }
626
627 // its ok to have an empty password
628 if (!$name) {
0af0e4c9
DL
629 return self::authenticateAbort(
630 "ERROR: You need to send a valid user name and password to execute this file\n",
6a488035
TO
631 $abort
632 );
633 }
634
bec3fc7c 635 if ($requireKey && !self::authenticateKey($abort)) {
6a488035
TO
636 return FALSE;
637 }
638
639 $result = CRM_Utils_System::authenticate($name, $pass, $loadCMSBootstrap);
640 if (!$result) {
0af0e4c9
DL
641 return self::authenticateAbort(
642 "ERROR: Invalid username and/or password\n",
6a488035
TO
643 $abort
644 );
645 }
646 elseif ($storeInSession) {
647 // lets store contact id and user id in session
648 list($userID, $ufID, $randomNumber) = $result;
649 if ($userID && $ufID) {
bec3fc7c 650 $config = CRM_Core_Config::singleton();
be2fb01f 651 $config->userSystem->setUserSession([$userID, $ufID]);
6a488035
TO
652 }
653 else {
0af0e4c9
DL
654 return self::authenticateAbort(
655 "ERROR: Unexpected error, could not match userID and contactID",
6a488035
TO
656 $abort
657 );
658 }
659 }
660
661 return $result;
662 }
663
664 /**
7890c493 665 * Authenticate the user against the uf db.
6a488035 666 *
b44e3f84 667 * In case of successful authentication, returns an array consisting of
7890c493
RS
668 * (contactID, ufID, unique string). Returns FALSE if authentication is
669 * unsuccessful.
6a488035 670 *
7890c493
RS
671 * @param string $name
672 * The username.
673 * @param string $password
674 * The password.
675 * @param bool $loadCMSBootstrap
70599df6 676 * @param string $realPath
7890c493
RS
677 *
678 * @return false|array
6a488035 679 */
00be9182 680 public static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
6a488035 681 $config = CRM_Core_Config::singleton();
c1e1e8b8 682
7890c493
RS
683 /* Before we do any loading, let's start the session and write to it.
684 * We typically call authenticate only when we need to bootstrap the CMS
685 * directly via Civi and hence bypass the normal CMS auth and bootstrap
686 * process typically done in CLI and cron scripts. See: CRM-12648
dc1e9be8
TO
687 *
688 * Q: Can we move this to the userSystem class so that it can be tuned
689 * per-CMS? For example, when dealing with UnitTests UF, there's no
690 * userFrameworkDSN.
7890c493 691 */
c1e1e8b8 692 $session = CRM_Core_Session::singleton();
481a74f4 693 $session->set('civicrmInitSession', TRUE);
c1e1e8b8 694
dc1e9be8
TO
695 if ($config->userFrameworkDSN) {
696 $dbDrupal = DB::connect($config->userFrameworkDSN);
697 }
6a488035
TO
698 return $config->userSystem->authenticate($name, $password, $loadCMSBootstrap, $realPath);
699 }
700
701 /**
7890c493 702 * Set a message in the UF to display to a user.
6a488035 703 *
7890c493
RS
704 * @param string $message
705 * The message to set.
6a488035 706 */
00be9182 707 public static function setUFMessage($message) {
6a488035
TO
708 $config = CRM_Core_Config::singleton();
709 return $config->userSystem->setMessage($message);
710 }
711
7890c493
RS
712 /**
713 * Determine whether a value is null-ish.
714 *
70599df6 715 * @param mixed $value
7890c493 716 * The value to check for null.
70599df6 717 *
7890c493 718 * @return bool
7890c493 719 */
00be9182 720 public static function isNull($value) {
6a488035
TO
721 // FIXME: remove $value = 'null' string test when we upgrade our DAO code to handle passing null in a better way.
722 if (!isset($value) || $value === NULL || $value === '' || $value === 'null') {
723 return TRUE;
724 }
725 if (is_array($value)) {
26659f0c 726 // @todo Reuse of the $value variable = asking for trouble.
6a488035 727 foreach ($value as $key => $value) {
57f8e7f0 728 if (in_array($key, CRM_Core_DAO::acceptedSQLOperators(), TRUE) || !self::isNull($value)) {
6a488035
TO
729 return FALSE;
730 }
731 }
732 return TRUE;
733 }
734 return FALSE;
735 }
736
7890c493
RS
737 /**
738 * Obscure all but the last few digits of a credit card number.
739 *
740 * @param string $number
741 * The credit card number to obscure.
742 * @param int $keep
743 * (optional) The number of digits to preserve unmodified.
70599df6 744 *
7890c493
RS
745 * @return string
746 * The obscured credit card number.
7890c493 747 */
00be9182 748 public static function mungeCreditCard($number, $keep = 4) {
6a488035
TO
749 $number = trim($number);
750 if (empty($number)) {
751 return NULL;
752 }
753 $replace = str_repeat('*', strlen($number) - $keep);
754 return substr_replace($number, $replace, 0, -$keep);
755 }
756
414e3596 757 /**
7890c493
RS
758 * Determine which PHP modules are loaded.
759 *
760 * @return array
7890c493 761 */
c8f60166 762 private static function parsePHPModules() {
6a488035
TO
763 ob_start();
764 phpinfo(INFO_MODULES);
765 $s = ob_get_contents();
766 ob_end_clean();
767
353ffa53
TO
768 $s = strip_tags($s, '<h2><th><td>');
769 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/', "<info>\\1</info>", $s);
770 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/', "<info>\\1</info>", $s);
771 $vTmp = preg_split('/(<h2>[^<]+<\/h2>)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE);
be2fb01f 772 $vModules = [];
6a488035
TO
773 for ($i = 1; $i < count($vTmp); $i++) {
774 if (preg_match('/<h2>([^<]+)<\/h2>/', $vTmp[$i], $vMat)) {
775 $vName = trim($vMat[1]);
776 $vTmp2 = explode("\n", $vTmp[$i + 1]);
e7292422 777 foreach ($vTmp2 as $vOne) {
353ffa53 778 $vPat = '<info>([^<]+)<\/info>';
6a488035
TO
779 $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
780 $vPat2 = "/$vPat\s*$vPat/";
781 // 3cols
782 if (preg_match($vPat3, $vOne, $vMat)) {
be2fb01f 783 $vModules[$vName][trim($vMat[1])] = [trim($vMat[2]), trim($vMat[3])];
6a488035
TO
784 // 2cols
785 }
786 elseif (preg_match($vPat2, $vOne, $vMat)) {
787 $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
788 }
789 }
790 }
791 }
792 return $vModules;
793 }
794
7890c493
RS
795 /**
796 * Get a setting from a loaded PHP module.
ad37ac8e 797 *
798 * @param string $pModuleName
799 * @param string $pSetting
800 *
801 * @return mixed
7890c493 802 */
fcc5922d 803 public static function getModuleSetting($pModuleName, $pSetting) {
6a488035
TO
804 $vModules = self::parsePHPModules();
805 return $vModules[$pModuleName][$pSetting];
806 }
807
7890c493 808 /**
70599df6 809 * Do something no-one bothered to document.
810 *
811 * @param string $title
7890c493 812 * (optional)
f4aaa82a
EM
813 *
814 * @return mixed|string
7890c493 815 */
00be9182 816 public static function memory($title = NULL) {
6a488035
TO
817 static $pid = NULL;
818 if (!$pid) {
819 $pid = posix_getpid();
820 }
821
822 $memory = str_replace("\n", '', shell_exec("ps -p" . $pid . " -o rss="));
823 $memory .= ", " . time();
824 if ($title) {
825 CRM_Core_Error::debug_var($title, $memory);
826 }
827 return $memory;
828 }
829
7890c493 830 /**
70599df6 831 * Download something or other.
832 *
7890c493
RS
833 * @param string $name
834 * @param string $mimeType
70599df6 835 * @param string $buffer
7890c493
RS
836 * @param string $ext
837 * @param bool $output
f4aaa82a 838 * @param string $disposition
7890c493 839 */
971d41b1 840 public static function download(
a3e55d9c 841 $name, $mimeType, &$buffer,
6a488035 842 $ext = NULL,
8f176433
M
843 $output = TRUE,
844 $disposition = 'attachment'
6a488035
TO
845 ) {
846 $now = gmdate('D, d M Y H:i:s') . ' GMT';
847
d42a224c
CW
848 self::setHttpHeader('Content-Type', $mimeType);
849 self::setHttpHeader('Expires', $now);
6a488035 850
50bfb460 851 // lem9 & loic1: IE needs specific headers
8535cfc6 852 $isIE = empty($_SERVER['HTTP_USER_AGENT']) ? FALSE : strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE');
6a488035
TO
853 if ($ext) {
854 $fileString = "filename=\"{$name}.{$ext}\"";
855 }
856 else {
857 $fileString = "filename=\"{$name}\"";
858 }
859 if ($isIE) {
d42a224c
CW
860 self::setHttpHeader("Content-Disposition", "inline; $fileString");
861 self::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
862 self::setHttpHeader('Pragma', 'public');
6a488035
TO
863 }
864 else {
d42a224c
CW
865 self::setHttpHeader("Content-Disposition", "$disposition; $fileString");
866 self::setHttpHeader('Pragma', 'no-cache');
6a488035
TO
867 }
868
869 if ($output) {
870 print $buffer;
871 self::civiExit();
872 }
873 }
874
7890c493 875 /**
9911500f
RS
876 * Gather and print (and possibly log) amount of used memory.
877 *
878 * @param string $title
879 * @param bool $log
880 * (optional) Whether to log the memory usage information.
7890c493 881 */
00be9182 882 public static function xMemory($title = NULL, $log = FALSE) {
e7292422 883 $mem = (float ) xdebug_memory_usage() / (float ) (1024);
6a488035
TO
884 $mem = number_format($mem, 5) . ", " . time();
885 if ($log) {
886 echo "<p>$title: $mem<p>";
887 flush();
888 CRM_Core_Error::debug_var($title, $mem);
889 }
890 else {
891 echo "<p>$title: $mem<p>";
892 flush();
893 }
894 }
895
7890c493 896 /**
9911500f
RS
897 * Take a URL (or partial URL) and make it better.
898 *
899 * Currently, URLs pass straight through unchanged unless they are "seriously
900 * malformed" (see http://us2.php.net/parse_url).
901 *
7890c493
RS
902 * @param string $url
903 * The URL to operate on.
70599df6 904 *
9911500f
RS
905 * @return string
906 * The fixed URL.
7890c493 907 */
00be9182 908 public static function fixURL($url) {
6a488035
TO
909 $components = parse_url($url);
910
911 if (!$components) {
912 return NULL;
913 }
914
915 // at some point we'll add code here to make sure the url is not
50bfb460 916 // something that will mess up, so we need to clean it up here
6a488035
TO
917 return $url;
918 }
919
920 /**
7890c493 921 * Make sure a callback is valid in the current context.
6a488035 922 *
7890c493
RS
923 * @param string $callback
924 * Name of the function to check.
6a488035 925 *
7890c493 926 * @return bool
6a488035 927 */
00be9182 928 public static function validCallback($callback) {
6a488035 929 if (self::$_callbacks === NULL) {
be2fb01f 930 self::$_callbacks = [];
6a488035
TO
931 }
932
933 if (!array_key_exists($callback, self::$_callbacks)) {
934 if (strpos($callback, '::') !== FALSE) {
935 list($className, $methodName) = explode('::', $callback);
936 $fileName = str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
937 // ignore errors if any
e7292422 938 @include_once $fileName;
6a488035
TO
939 if (!class_exists($className)) {
940 self::$_callbacks[$callback] = FALSE;
941 }
942 else {
943 // instantiate the class
944 $object = new $className();
945 if (!method_exists($object, $methodName)) {
946 self::$_callbacks[$callback] = FALSE;
947 }
948 else {
949 self::$_callbacks[$callback] = TRUE;
950 }
951 }
952 }
953 else {
954 self::$_callbacks[$callback] = function_exists($callback);
955 }
956 }
957 return self::$_callbacks[$callback];
958 }
959
960 /**
7890c493
RS
961 * Like PHP's built-in explode(), but always return an array of $limit items.
962 *
963 * This serves as a wrapper to the PHP explode() function. In the event that
964 * PHP's explode() returns an array with fewer than $limit elements, pad
965 * the end of the array with NULLs.
966 *
967 * @param string $separator
968 * @param string $string
969 * @param int $limit
70599df6 970 *
7890c493 971 * @return string[]
6a488035 972 */
00be9182 973 public static function explode($separator, $string, $limit) {
6a488035
TO
974 $result = explode($separator, $string, $limit);
975 for ($i = count($result); $i < $limit; $i++) {
976 $result[$i] = NULL;
977 }
978 return $result;
979 }
980
7890c493 981 /**
70599df6 982 * Check url.
983 *
7890c493
RS
984 * @param string $url
985 * The URL to check.
986 * @param bool $addCookie
987 * (optional)
f4aaa82a
EM
988 *
989 * @return mixed
7890c493 990 */
00be9182 991 public static function checkURL($url, $addCookie = FALSE) {
6a488035
TO
992 // make a GET request to $url
993 $ch = curl_init($url);
994 if ($addCookie) {
995 curl_setopt($ch, CURLOPT_COOKIE, http_build_query($_COOKIE));
996 }
997 // it's quite alright to use a self-signed cert
998 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
999
1000 // lets capture the return stuff rather than echo
481a74f4 1001 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
6a488035 1002
8d1adeef
NG
1003 // CRM-13227, CRM-14744: only return the SSL error status
1004 return (curl_exec($ch) !== FALSE);
6a488035
TO
1005 }
1006
7890c493
RS
1007 /**
1008 * Assert that we are running on a particular PHP version.
1009 *
1010 * @param int $ver
1011 * The major version of PHP that is required.
1012 * @param bool $abort
414e3596 1013 * (optional) Whether to fatally abort if the version requirement is not
7890c493 1014 * met. Defaults to TRUE.
70599df6 1015 *
7890c493
RS
1016 * @return bool
1017 * Returns TRUE if the requirement is met, FALSE if the requirement is not
9911500f
RS
1018 * met and we're not aborting due to the failed requirement. If $abort is
1019 * TRUE and the requirement fails, this function does not return.
ee3db087
SL
1020 *
1021 * @throws CRM_Core_Exception
7890c493 1022 */
00be9182 1023 public static function checkPHPVersion($ver = 5, $abort = TRUE) {
6a488035
TO
1024 $phpVersion = substr(PHP_VERSION, 0, 1);
1025 if ($phpVersion >= $ver) {
1026 return TRUE;
1027 }
1028
1029 if ($abort) {
ee3db087 1030 throw new CRM_Core_Exception(ts('This feature requires PHP Version %1 or greater',
be2fb01f 1031 [1 => $ver]
353ffa53 1032 ));
6a488035
TO
1033 }
1034 return FALSE;
1035 }
1036
7890c493 1037 /**
70599df6 1038 * Format wiki url.
1039 *
1040 * @param string $string
f4aaa82a
EM
1041 * @param bool $encode
1042 *
7890c493 1043 * @return string
7890c493 1044 */
00be9182 1045 public static function formatWikiURL($string, $encode = FALSE) {
6a488035
TO
1046 $items = explode(' ', trim($string), 2);
1047 if (count($items) == 2) {
1048 $title = $items[1];
1049 }
1050 else {
1051 $title = $items[0];
1052 }
1053
1054 // fix for CRM-4044
1055 $url = $encode ? self::urlEncode($items[0]) : $items[0];
1056 return "<a href=\"$url\">$title</a>";
1057 }
1058
7890c493 1059 /**
70599df6 1060 * Encode url.
1061 *
7890c493 1062 * @param string $url
f4aaa82a
EM
1063 *
1064 * @return null|string
7890c493 1065 */
00be9182 1066 public static function urlEncode($url) {
6a488035
TO
1067 $items = parse_url($url);
1068 if ($items === FALSE) {
1069 return NULL;
1070 }
1071
a7488080 1072 if (empty($items['query'])) {
6a488035
TO
1073 return $url;
1074 }
1075
1076 $items['query'] = urlencode($items['query']);
1077
1078 $url = $items['scheme'] . '://';
a7488080 1079 if (!empty($items['user'])) {
6a488035
TO
1080 $url .= "{$items['user']}:{$items['pass']}@";
1081 }
1082
1083 $url .= $items['host'];
a7488080 1084 if (!empty($items['port'])) {
6a488035
TO
1085 $url .= ":{$items['port']}";
1086 }
1087
1088 $url .= "{$items['path']}?{$items['query']}";
a7488080 1089 if (!empty($items['fragment'])) {
6a488035
TO
1090 $url .= "#{$items['fragment']}";
1091 }
1092
1093 return $url;
1094 }
1095
1096 /**
7890c493 1097 * Return the running civicrm version.
6a488035 1098 *
7890c493
RS
1099 * @return string
1100 * civicrm version
ee3db087
SL
1101 *
1102 * @throws CRM_Core_Exception
6a488035 1103 */
00be9182 1104 public static function version() {
6a488035
TO
1105 static $version;
1106
1107 if (!$version) {
1108 $verFile = implode(DIRECTORY_SEPARATOR,
be2fb01f 1109 [dirname(__FILE__), '..', '..', 'xml', 'version.xml']
6a488035
TO
1110 );
1111 if (file_exists($verFile)) {
e48985ca 1112 $str = file_get_contents($verFile);
1113 $xmlObj = simplexml_load_string($str);
1114 $version = (string) $xmlObj->version_no;
6a488035
TO
1115 }
1116
1117 // pattern check
1118 if (!CRM_Utils_System::isVersionFormatValid($version)) {
ee3db087 1119 throw new CRM_Core_Exception('Unknown codebase version.');
6a488035
TO
1120 }
1121 }
1122
1123 return $version;
1124 }
1125
b769826b 1126 /**
3d469574 1127 * Gives the first two parts of the version string E.g. 6.1.
b769826b
CW
1128 *
1129 * @return string
1130 */
1131 public static function majorVersion() {
1132 list($a, $b) = explode('.', self::version());
1133 return "$a.$b";
1134 }
1135
7890c493
RS
1136 /**
1137 * Determines whether a string is a valid CiviCRM version string.
1138 *
1139 * @param string $version
1140 * Version string to be checked.
3d469574 1141 *
7890c493 1142 * @return bool
7890c493 1143 */
00be9182 1144 public static function isVersionFormatValid($version) {
6a488035
TO
1145 return preg_match("/^(\d{1,2}\.){2,3}(\d{1,2}|(alpha|beta)\d{1,2})(\.upgrade)?$/", $version);
1146 }
1147
7890c493
RS
1148 /**
1149 * Wraps or emulates PHP's getallheaders() function.
7890c493 1150 */
00be9182 1151 public static function getAllHeaders() {
6a488035
TO
1152 if (function_exists('getallheaders')) {
1153 return getallheaders();
1154 }
1155
1156 // emulate get all headers
1157 // http://www.php.net/manual/en/function.getallheaders.php#66335
be2fb01f 1158 $headers = [];
6a488035
TO
1159 foreach ($_SERVER as $name => $value) {
1160 if (substr($name, 0, 5) == 'HTTP_') {
1161 $headers[str_replace(' ',
1162 '-',
1163 ucwords(strtolower(str_replace('_',
353ffa53
TO
1164 ' ',
1165 substr($name, 5)
1166 )
1167 ))
6a488035
TO
1168 )] = $value;
1169 }
1170 }
1171 return $headers;
1172 }
1173
3d469574 1174 /**
1175 * Get request headers.
1176 *
1177 * @return array|false
1178 */
00be9182 1179 public static function getRequestHeaders() {
6a488035
TO
1180 if (function_exists('apache_request_headers')) {
1181 return apache_request_headers();
1182 }
1183 else {
1184 return $_SERVER;
1185 }
1186 }
1187
1188 /**
7890c493
RS
1189 * Determine whether this is an SSL request.
1190 *
1191 * Note that we inline this function in install/civicrm.php, so if you change
1192 * this function, please go and change the code in the install script as well.
6a488035 1193 */
e7292422 1194 public static function isSSL() {
fe0dbeda 1195 return !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off';
6a488035
TO
1196 }
1197
3d469574 1198 /**
1199 * Redirect to SSL.
1200 *
1201 * @param bool|FALSE $abort
1202 *
ee3db087 1203 * @throws \CRM_Core_Exception
3d469574 1204 */
00be9182 1205 public static function redirectToSSL($abort = FALSE) {
6a488035
TO
1206 $config = CRM_Core_Config::singleton();
1207 $req_headers = self::getRequestHeaders();
3e6b8905 1208 // FIXME: Shouldn't the X-Forwarded-Proto check be part of CRM_Utils_System::isSSL()?
aaffa79f 1209 if (Civi::settings()->get('enableSSL') &&
6a488035
TO
1210 !self::isSSL() &&
1211 strtolower(CRM_Utils_Array::value('X_FORWARDED_PROTO', $req_headers)) != 'https'
1212 ) {
1213 // ensure that SSL is enabled on a civicrm url (for cookie reasons etc)
1214 $url = "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
b12378a7
CB
1215 // @see https://lab.civicrm.org/dev/core/issues/425 if you're seeing this message.
1216 Civi::log()->warning('CiviCRM thinks site is not SSL, redirecting to {url}', ['url' => $url]);
6a488035
TO
1217 if (!self::checkURL($url, TRUE)) {
1218 if ($abort) {
ee3db087 1219 throw new CRM_Core_Exception('HTTPS is not set up on this machine');
6a488035
TO
1220 }
1221 else {
e7292422 1222 CRM_Core_Session::setStatus(ts('HTTPS is not set up on this machine'), ts('Warning'), 'alert');
6a488035
TO
1223 // admin should be the only one following this
1224 // since we dont want the user stuck in a bad place
1225 return;
1226 }
1227 }
1228 CRM_Utils_System::redirect($url);
1229 }
1230 }
1231
d424ffde 1232 /**
5df36634
PJ
1233 * Get logged in user's IP address.
1234 *
7890c493
RS
1235 * Get IP address from HTTP REMOTE_ADDR header. If the CMS is Drupal then use
1236 * the Drupal function as this also handles reverse proxies (based on proper
1237 * configuration in settings.php)
5df36634 1238 *
7890c493
RS
1239 * @param bool $strictIPV4
1240 * (optional) Whether to return only IPv4 addresses.
1241 *
1242 * @return string
1243 * IP address of logged in user.
5df36634 1244 */
00be9182 1245 public static function ipAddress($strictIPV4 = TRUE) {
9c1bc317 1246 $address = $_SERVER['REMOTE_ADDR'] ?? NULL;
6a488035
TO
1247
1248 $config = CRM_Core_Config::singleton();
414e3596 1249 if ($config->userSystem->is_drupal && function_exists('ip_address')) {
50bfb460 1250 // drupal function handles the server being behind a proxy securely. We still have legacy ipn methods
414e3596 1251 // that reach this point without bootstrapping hence the check that the fn exists
e7292422 1252 $address = ip_address();
6a488035
TO
1253 }
1254
1255 // hack for safari
1256 if ($address == '::1') {
1257 $address = '127.0.0.1';
1258 }
1259
5df36634
PJ
1260 // when we need to have strictly IPV4 ip address
1261 // convert ipV6 to ipV4
1262 if ($strictIPV4) {
1263 // this converts 'IPV4 mapped IPV6 address' to IPV4
1264 if (filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && strstr($address, '::ffff:')) {
1265 $address = ltrim($address, '::ffff:');
1266 }
1267 }
1268
6a488035
TO
1269 return $address;
1270 }
1271
1272 /**
7890c493 1273 * Get the referring / previous page URL.
6a488035 1274 *
7890c493
RS
1275 * @return string
1276 * The previous page URL
6a488035 1277 */
00be9182 1278 public static function refererPath() {
914d3734 1279 return $_SERVER['HTTP_REFERER'] ?? NULL;
6a488035
TO
1280 }
1281
1282 /**
7890c493 1283 * Get the documentation base URL.
6a488035 1284 *
7890c493
RS
1285 * @return string
1286 * Base URL of the CRM documentation.
6a488035 1287 */
00be9182 1288 public static function getDocBaseURL() {
6a488035 1289 // FIXME: move this to configuration at some stage
c15f87c1 1290 return 'https://docs.civicrm.org/';
6a488035
TO
1291 }
1292
1293 /**
7890c493 1294 * Returns wiki (alternate) documentation URL base.
6a488035 1295 *
a6c01b45
CW
1296 * @return string
1297 * documentation url
6a488035 1298 */
00be9182 1299 public static function getWikiBaseURL() {
6a488035
TO
1300 // FIXME: move this to configuration at some stage
1301 return 'http://wiki.civicrm.org/confluence/display/CRMDOC/';
1302 }
1303
1304 /**
1305 * Returns URL or link to documentation page, based on provided parameters.
7890c493 1306 *
6a488035 1307 * For use in PHP code.
7890c493
RS
1308 * WARNING: Always returns URL, if ts function is not defined ($URLonly has
1309 * no effect).
6a488035 1310 *
7890c493
RS
1311 * @param string $page
1312 * Title of documentation wiki page.
77855840 1313 * @param bool $URLonly
7890c493
RS
1314 * (optional) Whether to return URL only or full HTML link (default).
1315 * @param string $text
1316 * (optional) Text of HTML link (no effect if $URLonly = false).
1317 * @param string $title
1318 * (optional) Tooltip text for HTML link (no effect if $URLonly = false)
1319 * @param string $style
1320 * (optional) Style attribute value for HTML link (no effect if $URLonly = false)
6a488035 1321 *
f4aaa82a
EM
1322 * @param null $resource
1323 *
7890c493
RS
1324 * @return string
1325 * URL or link to documentation page, based on provided parameters.
6a488035 1326 */
00be9182 1327 public static function docURL2($page, $URLonly = FALSE, $text = NULL, $title = NULL, $style = NULL, $resource = NULL) {
6a488035
TO
1328 // if ts function doesn't exist, it means that CiviCRM hasn't been fully initialised yet -
1329 // return just the URL, no matter what other parameters are defined
1330 if (!function_exists('ts')) {
1331 if ($resource == 'wiki') {
e7292422 1332 $docBaseURL = self::getWikiBaseURL();
0db6c3e1
TO
1333 }
1334 else {
6a488035 1335 $docBaseURL = self::getDocBaseURL();
c15f87c1 1336 $page = self::formatDocUrl($page);
6a488035
TO
1337 }
1338 return $docBaseURL . str_replace(' ', '+', $page);
1339 }
1340 else {
be2fb01f 1341 $params = [
6a488035
TO
1342 'page' => $page,
1343 'URLonly' => $URLonly,
1344 'text' => $text,
1345 'title' => $title,
1346 'style' => $style,
1347 'resource' => $resource,
be2fb01f 1348 ];
6a488035
TO
1349 return self::docURL($params);
1350 }
1351 }
1352
1353 /**
1354 * Returns URL or link to documentation page, based on provided parameters.
7890c493 1355 *
6a488035
TO
1356 * For use in templates code.
1357 *
7890c493
RS
1358 * @param array $params
1359 * An array of parameters (see CRM_Utils_System::docURL2 method for names)
6a488035 1360 *
b8c71ffa 1361 * @return null|string
7890c493 1362 * URL or link to documentation page, based on provided parameters.
6a488035 1363 */
00be9182 1364 public static function docURL($params) {
6a488035
TO
1365
1366 if (!isset($params['page'])) {
c301f76e 1367 return NULL;
6a488035
TO
1368 }
1369
1370 if (CRM_Utils_Array::value('resource', $params) == 'wiki') {
1371 $docBaseURL = self::getWikiBaseURL();
0db6c3e1
TO
1372 }
1373 else {
6a488035 1374 $docBaseURL = self::getDocBaseURL();
c15f87c1 1375 $params['page'] = self::formatDocUrl($params['page']);
6a488035
TO
1376 }
1377
1378 if (!isset($params['title']) or $params['title'] === NULL) {
1379 $params['title'] = ts('Opens documentation in a new window.');
1380 }
1381
1382 if (!isset($params['text']) or $params['text'] === NULL) {
1383 $params['text'] = ts('(learn more...)');
1384 }
1385
1386 if (!isset($params['style']) || $params['style'] === NULL) {
1387 $style = '';
1388 }
1389 else {
1390 $style = "style=\"{$params['style']}\"";
1391 }
1392
1393 $link = $docBaseURL . str_replace(' ', '+', $params['page']);
1394
1395 if (isset($params['URLonly']) && $params['URLonly'] == TRUE) {
1396 return $link;
1397 }
1398 else {
16e71c83 1399 return "<a href=\"{$link}\" $style target=\"_blank\" class=\"crm-doc-link no-popup\" title=\"{$params['title']}\">{$params['text']}</a>";
6a488035
TO
1400 }
1401 }
1402
c15f87c1
CW
1403 /**
1404 * Add language and version parameters to the doc url.
1405 *
1406 * Note that this function may run before CiviCRM is initialized and so should not call ts() or perform any db lookups.
1407 *
1408 * @param $url
1409 * @return mixed
1410 */
1411 public static function formatDocUrl($url) {
8552370e 1412 return preg_replace('#^(user|sysadmin|dev)/#', '\1/en/stable/', $url);
c15f87c1
CW
1413 }
1414
7890c493
RS
1415 /**
1416 * Exit with provided exit code.
1417 *
1418 * @param int $status
1419 * (optional) Code with which to exit.
62e245e6 1420 *
68989e71 1421 * @param array $testParameters
7890c493 1422 */
68989e71 1423 public static function civiExit($status = 0, $testParameters = []) {
307d2406 1424
62e245e6 1425 if (CIVICRM_UF === 'UnitTests') {
68989e71 1426 throw new CRM_Core_Exception_PrematureExitException('civiExit called', $testParameters);
62e245e6 1427 }
d74139ea 1428 if ($status > 0) {
307d2406
MM
1429 http_response_code(500);
1430 }
6a488035
TO
1431 // move things to CiviCRM cache as needed
1432 CRM_Core_Session::storeSessionObjects();
1433
f2e906d7
JP
1434 if (Civi\Core\Container::isContainerBooted()) {
1435 Civi::dispatcher()->dispatch('civi.core.exit');
1436 }
1437
1438 $userSystem = CRM_Core_Config::singleton()->userSystem;
be2fb01f 1439 if (is_callable([$userSystem, 'onCiviExit'])) {
f2e906d7
JP
1440 $userSystem->onCiviExit();
1441 }
6a488035
TO
1442 exit($status);
1443 }
1444
1445 /**
7890c493 1446 * Reset the various system caches and some important static variables.
6a488035 1447 */
e7292422 1448 public static function flushCache() {
6a488035
TO
1449 // flush out all cache entries so we can reload new data
1450 // a bit aggressive, but livable for now
5aac553c 1451 CRM_Utils_Cache::singleton()->flush();
70423e0d
TO
1452
1453 // Traditionally, systems running on memory-backed caches were quite
1454 // zealous about destroying *all* memory-backed caches during a flush().
1455 // These flushes simulate that legacy behavior. However, they should probably
1456 // be removed at some point.
c33f1df1 1457 $localDrivers = ['CRM_Utils_Cache_ArrayCache', 'CRM_Utils_Cache_NoCache'];
70423e0d
TO
1458 if (Civi\Core\Container::isContainerBooted()
1459 && !in_array(get_class(CRM_Utils_Cache::singleton()), $localDrivers)) {
90cdaa0e 1460 Civi::cache('long')->flush();
5aac553c
TO
1461 Civi::cache('settings')->flush();
1462 Civi::cache('js_strings')->flush();
1463 Civi::cache('community_messages')->flush();
972b390e 1464 Civi::cache('groups')->flush();
96689db3 1465 Civi::cache('navigation')->flush();
792fce0b 1466 Civi::cache('customData')->flush();
81c4c148 1467 Civi::cache('contactTypes')->clear();
eb151aab 1468 Civi::cache('metadata')->clear();
5aac553c
TO
1469 CRM_Extension_System::singleton()->getCache()->flush();
1470 CRM_Cxn_CiviCxnHttp::singleton()->getCache()->flush();
1471 }
6a488035
TO
1472
1473 // also reset the various static memory caches
1474
1475 // reset the memory or array cache
9cdf85c1 1476 Civi::cache('fields')->flush();
6a488035
TO
1477
1478 // reset ACL cache
1479 CRM_ACL_BAO_Cache::resetCache();
1480
18f5b231 1481 // clear asset builder folder
1482 \Civi::service('asset_builder')->clear(FALSE);
1483
6a488035 1484 // reset various static arrays used here
c301f76e 1485 CRM_Contact_BAO_Contact::$_importableFields = CRM_Contact_BAO_Contact::$_exportableFields
971d41b1 1486 = CRM_Contribute_BAO_Contribution::$_importableFields
c301f76e 1487 = CRM_Contribute_BAO_Contribution::$_exportableFields
33a766c6 1488 = CRM_Pledge_BAO_Pledge::$_exportableFields
c301f76e 1489 = CRM_Core_BAO_CustomField::$_importFields
1490 = CRM_Core_BAO_Cache::$_cache = CRM_Core_DAO::$_dbColumnValueCache = NULL;
6a488035
TO
1491
1492 CRM_Core_OptionGroup::flushAll();
1493 CRM_Utils_PseudoConstant::flushAll();
1494 }
1495
1496 /**
7890c493 1497 * Load CMS bootstrap.
6a488035 1498 *
7890c493
RS
1499 * @param array $params
1500 * Array with uid name and pass
1501 * @param bool $loadUser
1502 * Boolean load user or not.
1503 * @param bool $throwError
3d469574 1504 * @param string $realPath
6a488035 1505 */
be2fb01f 1506 public static function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
6a488035 1507 if (!is_array($params)) {
be2fb01f 1508 $params = [];
6a488035
TO
1509 }
1510 $config = CRM_Core_Config::singleton();
49b60138
TO
1511 $result = $config->userSystem->loadBootStrap($params, $loadUser, $throwError, $realPath);
1512 if (is_callable([$config->userSystem, 'setMySQLTimeZone'])) {
1513 $config->userSystem->setMySQLTimeZone();
1514 }
1515 return $result;
6a488035
TO
1516 }
1517
70599df6 1518 /**
1519 * Get Base CMS url.
1520 *
1521 * @return mixed|string
1522 */
00be9182 1523 public static function baseCMSURL() {
6a488035
TO
1524 static $_baseURL = NULL;
1525 if (!$_baseURL) {
1526 $config = CRM_Core_Config::singleton();
1527 $_baseURL = $userFrameworkBaseURL = $config->userFrameworkBaseURL;
1528
1529 if ($config->userFramework == 'Joomla') {
1530 // gross hack
1531 // we need to remove the administrator/ from the end
1532 $_baseURL = str_replace("/administrator/", "/", $userFrameworkBaseURL);
1533 }
1534 else {
1535 // Drupal setting
1536 global $civicrm_root;
1537 if (strpos($civicrm_root,
1538 DIRECTORY_SEPARATOR . 'sites' .
1539 DIRECTORY_SEPARATOR . 'all' .
1540 DIRECTORY_SEPARATOR . 'modules'
353ffa53
TO
1541 ) === FALSE
1542 ) {
6a488035
TO
1543 $startPos = strpos($civicrm_root,
1544 DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR
1545 );
1546 $endPos = strpos($civicrm_root,
1547 DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR
1548 );
1549 if ($startPos && $endPos) {
1550 // if component is in sites/SITENAME/modules
1551 $siteName = substr($civicrm_root,
1552 $startPos + 7,
1553 $endPos - $startPos - 7
1554 );
1555
1556 $_baseURL = $userFrameworkBaseURL . "sites/$siteName/";
1557 }
1558 }
1559 }
1560 }
1561 return $_baseURL;
1562 }
1563
7890c493
RS
1564 /**
1565 * Given a URL, return a relative URL if possible.
1566 *
1567 * @param string $url
3d469574 1568 *
7890c493 1569 * @return string
7890c493 1570 */
00be9182 1571 public static function relativeURL($url) {
6a488035
TO
1572 // check if url is relative, if so return immediately
1573 if (substr($url, 0, 4) != 'http') {
1574 return $url;
1575 }
1576
1577 // make everything relative from the baseFilePath
1578 $baseURL = self::baseCMSURL();
1579
1580 // check if baseURL is a substr of $url, if so
1581 // return rest of string
1582 if (substr($url, 0, strlen($baseURL)) == $baseURL) {
1583 return substr($url, strlen($baseURL));
1584 }
1585
1586 // return the original value
1587 return $url;
1588 }
1589
7890c493
RS
1590 /**
1591 * Produce an absolute URL from a possibly-relative URL.
1592 *
1593 * @param string $url
f4aaa82a
EM
1594 * @param bool $removeLanguagePart
1595 *
7890c493 1596 * @return string
7890c493 1597 */
00be9182 1598 public static function absoluteURL($url, $removeLanguagePart = FALSE) {
6a488035
TO
1599 // check if url is already absolute, if so return immediately
1600 if (substr($url, 0, 4) == 'http') {
1601 return $url;
1602 }
1603
1604 // make everything absolute from the baseFileURL
1605 $baseURL = self::baseCMSURL();
1606
1607 //CRM-7622: drop the language from the URL if requested (and it’s there)
1608 $config = CRM_Core_Config::singleton();
1609 if ($removeLanguagePart) {
1610 $baseURL = self::languageNegotiationURL($baseURL, FALSE, TRUE);
1611 }
1612
1613 return $baseURL . $url;
1614 }
1615
1616 /**
3d469574 1617 * Clean url, replaces first '&' with '?'.
6a488035
TO
1618 *
1619 * @param string $url
1620 *
a6c01b45
CW
1621 * @return string
1622 * , clean url
6a488035 1623 */
00be9182 1624 public static function cleanUrl($url) {
6a488035
TO
1625 if (!$url) {
1626 return NULL;
1627 }
1628
1629 if ($pos = strpos($url, '&')) {
1630 $url = substr_replace($url, '?', $pos, 1);
1631 }
1632
1633 return $url;
1634 }
1635
1636 /**
1637 * Format the url as per language Negotiation.
1638 *
1639 * @param string $url
1640 *
f4aaa82a
EM
1641 * @param bool $addLanguagePart
1642 * @param bool $removeLanguagePart
1643 *
a6c01b45
CW
1644 * @return string
1645 * , formatted url.
6a488035 1646 */
971d41b1 1647 public static function languageNegotiationURL(
a3e55d9c 1648 $url,
6a488035
TO
1649 $addLanguagePart = TRUE,
1650 $removeLanguagePart = FALSE
1651 ) {
f3a87cf4 1652 return CRM_Core_Config::singleton()->userSystem->languageNegotiationURL($url, $addLanguagePart, $removeLanguagePart);
6a488035
TO
1653 }
1654
1655 /**
3d469574 1656 * Append the contents of an 'extra' smarty template file.
1657 *
1658 * It must be present in the custom template directory. This does not work if there are
6a488035
TO
1659 * multiple custom template directories
1660 *
9911500f
RS
1661 * @param string $fileName
1662 * The name of the tpl file that we are processing.
1663 * @param string $content
1664 * The current content string. May be modified by this function.
1665 * @param string $overideFileName
1666 * (optional) Sent by contribution/event reg/profile pages which uses a id
1667 * specific extra file name if present.
6a488035 1668 */
971d41b1 1669 public static function appendTPLFile(
a3e55d9c 1670 $fileName,
6a488035
TO
1671 &$content,
1672 $overideFileName = NULL
1673 ) {
1674 $template = CRM_Core_Smarty::singleton();
1675 if ($overideFileName) {
1676 $additionalTPLFile = $overideFileName;
1677 }
1678 else {
1679 $additionalTPLFile = str_replace('.tpl', '.extra.tpl', $fileName);
1680 }
1681
1682 if ($template->template_exists($additionalTPLFile)) {
1683 $content .= $template->fetch($additionalTPLFile);
1684 }
1685 }
1686
1687 /**
3d469574 1688 * Get a list of all files that are found within the directories.
1689 *
1690 * Files must be the result of appending the provided relative path to
6a488035
TO
1691 * each component of the PHP include path.
1692 *
1693 * @author Ken Zalewski
1694 *
9911500f
RS
1695 * @param string $relpath
1696 * A relative path, typically pointing to a directory with multiple class
1697 * files.
6a488035 1698 *
9911500f
RS
1699 * @return array
1700 * An array of files that exist in one or more of the directories that are
1701 * referenced by the relative path when appended to each element of the PHP
1702 * include path.
6a488035 1703 */
00be9182 1704 public static function listIncludeFiles($relpath) {
be2fb01f 1705 $file_list = [];
6a488035
TO
1706 $inc_dirs = explode(PATH_SEPARATOR, get_include_path());
1707 foreach ($inc_dirs as $inc_dir) {
1708 $target_dir = $inc_dir . DIRECTORY_SEPARATOR . $relpath;
1709 if (is_dir($target_dir)) {
1710 $cur_list = scandir($target_dir);
1711 foreach ($cur_list as $fname) {
1712 if ($fname != '.' && $fname != '..') {
1713 $file_list[$fname] = $fname;
1714 }
1715 }
1716 }
1717 }
1718 return $file_list;
1719 }
6a488035
TO
1720
1721 /**
3d469574 1722 * Get a list of all "plugins".
1723 *
1724 * (PHP classes that implement a piece of
6a488035
TO
1725 * functionality using a well-defined interface) that are found in a
1726 * particular CiviCRM directory (both custom and core are searched).
1727 *
1728 * @author Ken Zalewski
1729 *
9911500f
RS
1730 * @param string $relpath
1731 * A relative path referencing a directory that contains one or more
1732 * plugins.
1733 * @param string $fext
1734 * (optional) Only files with this extension will be considered to be
1735 * plugins.
1736 * @param array $skipList
1737 * (optional) List of files to skip.
6a488035 1738 *
9911500f
RS
1739 * @return array
1740 * List of plugins, where the plugin name is both the key and the value of
1741 * each element.
6a488035 1742 */
be2fb01f 1743 public static function getPluginList($relpath, $fext = '.php', $skipList = []) {
c490a46a 1744 $fext_len = strlen($fext);
be2fb01f 1745 $plugins = [];
6a488035
TO
1746 $inc_files = CRM_Utils_System::listIncludeFiles($relpath);
1747 foreach ($inc_files as $inc_file) {
1748 if (substr($inc_file, 0 - $fext_len) == $fext) {
1749 $plugin_name = substr($inc_file, 0, 0 - $fext_len);
1750 if (!in_array($plugin_name, $skipList)) {
1751 $plugins[$plugin_name] = $plugin_name;
1752 }
1753 }
1754 }
1755 return $plugins;
1756 }
6a488035 1757
3d469574 1758 /**
1759 * Execute scheduled jobs.
1760 */
00be9182 1761 public static function executeScheduledJobs() {
6a488035
TO
1762 $facility = new CRM_Core_JobManager();
1763 $facility->execute(FALSE);
1764
1765 $redirectUrl = self::url('civicrm/admin/job', 'reset=1');
1766
1767 CRM_Core_Session::setStatus(
1768 ts('Scheduled jobs have been executed according to individual timing settings. Please check log for messages.'),
1769 ts('Complete'), 'success');
1770
1771 CRM_Utils_System::redirect($redirectUrl);
1772 }
1773
efceedd4 1774 /**
9911500f 1775 * Evaluate any tokens in a URL.
efceedd4
TO
1776 *
1777 * @param string|FALSE $url
3d469574 1778 *
efceedd4
TO
1779 * @return string|FALSE
1780 */
1781 public static function evalUrl($url) {
202407d7
CW
1782 if (!$url || strpos($url, '{') === FALSE) {
1783 return $url;
efceedd4
TO
1784 }
1785 else {
1786 $config = CRM_Core_Config::singleton();
d59ab677 1787 $tsLocale = CRM_Core_I18n::getLocale();
be2fb01f 1788 $vars = [
efceedd4
TO
1789 '{ver}' => CRM_Utils_System::version(),
1790 '{uf}' => $config->userFramework,
1791 '{php}' => phpversion(),
202407d7 1792 '{sid}' => self::getSiteID(),
c4e76569 1793 '{baseUrl}' => $config->userFrameworkBaseURL,
d59ab677 1794 '{lang}' => $tsLocale,
c4e76569 1795 '{co}' => $config->defaultContactCountry,
be2fb01f 1796 ];
202407d7 1797 return strtr($url, array_map('urlencode', $vars));
efceedd4
TO
1798 }
1799 }
1800
202407d7 1801 /**
1ab26c95
CW
1802 * Returns the unique identifier for this site, as used by community messages.
1803 *
1804 * SiteID will be generated if it is not already stored in the settings table.
1805 *
202407d7
CW
1806 * @return string
1807 */
1808 public static function getSiteID() {
aaffa79f 1809 $sid = Civi::settings()->get('site_id');
1ab26c95
CW
1810 if (!$sid) {
1811 $config = CRM_Core_Config::singleton();
1812 $sid = md5('sid_' . (defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : '') . '_' . $config->userFrameworkBaseURL);
be2fb01f 1813 civicrm_api3('Setting', 'create', ['domain_id' => 'all', 'site_id' => $sid]);
1ab26c95
CW
1814 }
1815 return $sid;
202407d7 1816 }
efceedd4 1817
6a488035
TO
1818 /**
1819 * Determine whether this is a developmental system.
1820 *
1821 * @return bool
1822 */
00be9182 1823 public static function isDevelopment() {
6a488035
TO
1824 static $cache = NULL;
1825 if ($cache === NULL) {
1826 global $civicrm_root;
1827 $cache = file_exists("{$civicrm_root}/.svn") || file_exists("{$civicrm_root}/.git");
1828 }
1829 return $cache;
1830 }
5da97e99 1831
5bc392e6 1832 /**
3d469574 1833 * Is in upgrade mode.
1834 *
5bc392e6
EM
1835 * @return bool
1836 */
00be9182 1837 public static function isInUpgradeMode() {
40787e18 1838 $args = explode('/', CRM_Utils_Array::value('q', $_GET));
252e6dbc
PJ
1839 $upgradeInProcess = CRM_Core_Session::singleton()->get('isUpgradePending');
1840 if ((isset($args[1]) && $args[1] == 'upgrade') || $upgradeInProcess) {
1841 return TRUE;
1842 }
1843 else {
1844 return FALSE;
1845 }
1846 }
688ad538
TO
1847
1848 /**
fe482240 1849 * Determine the standard URL for viewing or editing the specified link.
688ad538
TO
1850 *
1851 * This function delegates the decision-making to (a) the hook system and
1852 * (b) the BAO system.
1853 *
77855840
TO
1854 * @param array $crudLinkSpec
1855 * With keys:.
16b10e64
CW
1856 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
1857 * - entity_table: string, eg "civicrm_contact"
1858 * - entity_id: int
3d469574 1859 *
72b3a70c
CW
1860 * @return array|NULL
1861 * NULL if unavailable, or an array. array has keys:
16b10e64
CW
1862 * - path: string
1863 * - query: array
1864 * - title: string
1865 * - url: string
688ad538 1866 */
00be9182 1867 public static function createDefaultCrudLink($crudLinkSpec) {
688ad538
TO
1868 $crudLinkSpec['action'] = CRM_Utils_Array::value('action', $crudLinkSpec, CRM_Core_Action::VIEW);
1869 $daoClass = CRM_Core_DAO_AllCoreTables::getClassForTable($crudLinkSpec['entity_table']);
1870 if (!$daoClass) {
1871 return NULL;
1872 }
1873
1874 $baoClass = str_replace('_DAO_', '_BAO_', $daoClass);
1875 if (!class_exists($baoClass)) {
1876 return NULL;
1877 }
1878
1879 $bao = new $baoClass();
1880 $bao->id = $crudLinkSpec['entity_id'];
1881 if (!$bao->find(TRUE)) {
1882 return NULL;
1883 }
1884
be2fb01f 1885 $link = [];
688ad538 1886 CRM_Utils_Hook::crudLink($crudLinkSpec, $bao, $link);
be2fb01f 1887 if (empty($link) && is_callable([$bao, 'createDefaultCrudLink'])) {
688ad538
TO
1888 $link = $bao->createDefaultCrudLink($crudLinkSpec);
1889 }
1890
1891 if (!empty($link)) {
1892 if (!isset($link['url'])) {
1893 $link['url'] = self::url($link['path'], $link['query'], TRUE, NULL, FALSE);
1894 }
1895 return $link;
1896 }
1897
1898 return NULL;
1899 }
96025800 1900
79dd7fe9
SL
1901 /**
1902 * Return an HTTP Response with appropriate content and status code set.
46dddc5c 1903 * @param \Psr\Http\Message\ResponseInterface $response
79dd7fe9 1904 */
46dddc5c 1905 public static function sendResponse(\Psr\Http\Message\ResponseInterface $response) {
90f6c8df 1906 $config = CRM_Core_Config::singleton()->userSystem->sendResponse($response);
79dd7fe9
SL
1907 }
1908
5bc392e6 1909}