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