Merge pull request #17079 from yashodha/dev-1704
[civicrm-core.git] / CRM / Utils / System.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * System wide utilities.
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.
28 * @method static appendBreadCrumb(array $breadCrumbs) Append an additional breadcrumb tag to the existing breadcrumbs.
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.
38 * @method static appendCoreResources(\Civi\Core\Event\GenericHookEvent $e) Callback for hook_civicrm_coreResourceList.
39 * @method static alterAssetUrl(\Civi\Core\Event\GenericHookEvent $e) Callback for hook_civicrm_getAssetUrl.
40 */
41 class CRM_Utils_System {
42
43 public static $_callbacks = NULL;
44
45 /**
46 * @var string
47 * Page title
48 */
49 public static $title = '';
50
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;
60 return call_user_func_array([$userSystem, $name], $arguments);
61 }
62
63 /**
64 * Compose a new URL string from the current URL string.
65 *
66 * Used by all the framework components, specifically,
67 * pager, sort and qfc
68 *
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).
75 * @param string $path
76 * (optional) The path to use for the new url.
77 * @param bool|string $absolute
78 * (optional) Whether to return an absolute URL.
79 *
80 * @return string
81 * The URL fragment.
82 */
83 public static function makeURL($urlVar, $includeReset = FALSE, $includeForce = TRUE, $path = NULL, $absolute = FALSE) {
84 $path = $path ?: CRM_Utils_System::currentPath();
85 if (!$path) {
86 return '';
87 }
88
89 return self::url(
90 $path,
91 CRM_Utils_System::getLinksUrl($urlVar, $includeReset, $includeForce),
92 $absolute
93 );
94 }
95
96 /**
97 * Get the query string and clean it up.
98 *
99 * Strips some variables that should not be propagated, specifically variables
100 * like 'reset'. Also strips any side-affect actions (e.g. export).
101 *
102 * This function is copied mostly verbatim from Pager.php (_getLinksUrl)
103 *
104 * @param string $urlVar
105 * The URL variable being considered (e.g. crmPageID, crmSortID etc).
106 * @param bool $includeReset
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.
109 * @param bool $includeForce
110 * (optional)
111 * @param bool $skipUFVar
112 * (optional)
113 *
114 * @return string
115 */
116 public static function getLinksUrl($urlVar, $includeReset = FALSE, $includeForce = TRUE, $skipUFVar = TRUE) {
117 // Sort out query string to prevent messy urls
118 $querystring = [];
119 $qs = [];
120 $arrays = [];
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);
130 // check for arrays in parameters: site.php?foo[]=1&foo[]=2&foo[]=3
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
152 // Ok this is a big assumption but usually works
153 // If we are in snippet mode, retain the 'section' param, if not, get rid
154 // of it.
155 if (!empty($qs['snippet'])) {
156 unset($qs['snippet']);
157 }
158 else {
159 unset($qs['section']);
160 }
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));
174
175 $url = implode('&', $querystring);
176 if ($urlVar) {
177 $url .= (!empty($querystring) ? '&' : '') . $urlVar . '=';
178 }
179
180 return $url;
181 }
182
183 /**
184 * If we are using a theming system, invoke theme, else just print the content.
185 *
186 * @param string $content
187 * The content that will be themed.
188 * @param bool $print
189 * (optional) Are we displaying to the screen or bypassing theming?
190 * @param bool $maintenance
191 * (optional) For maintenance mode.
192 *
193 * @return string
194 */
195 public static function theme(
196 &$content,
197 $print = FALSE,
198 $maintenance = FALSE
199 ) {
200 return CRM_Core_Config::singleton()->userSystem->theme($content, $print, $maintenance);
201 }
202
203 /**
204 * Generate a query string if input is an array.
205 *
206 * @param array|string $query
207 *
208 * @return string
209 */
210 public static function makeQueryString($query) {
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 /**
222 * Generate an internal CiviCRM URL.
223 *
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
230 * URI-scheme such as 'http:'). Useful for links that will be displayed
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.
234 * @param bool $htmlize
235 * Whether to encode special html characters such as &.
236 * @param bool $frontend
237 * This link should be to the CMS front end (applies to WP & Joomla).
238 * @param bool $forceBackend
239 * This link should be to the CMS back end (applies to WP & Joomla).
240 *
241 * @return string
242 * An HTML string containing a link to the given path.
243 */
244 public static function url(
245 $path = NULL,
246 $query = NULL,
247 $absolute = FALSE,
248 $fragment = NULL,
249 $htmlize = TRUE,
250 $frontend = FALSE,
251 $forceBackend = FALSE
252 ) {
253 $query = self::makeQueryString($query);
254
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" : '');
272 }
273
274 $config = CRM_Core_Config::singleton();
275 $url = $config->userSystem->url($path, $query, $absolute, $fragment, $frontend, $forceBackend);
276
277 if ($htmlize) {
278 $url = htmlentities($url);
279 }
280
281 return $url;
282 }
283
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.
298 *
299 * @return string rawencoded URL.
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 ]);
317 Civi::dispatcher()->dispatch('hook_civicrm_alterExternUrl', $event);
318 return urldecode(CRM_Utils_Url::unparseUrl($event->url));
319 }
320
321 /**
322 * @deprecated
323 * @see \CRM_Utils_System::currentPath
324 *
325 * @return string|null
326 */
327 public static function getUrlPath() {
328 CRM_Core_Error::deprecatedFunctionWarning('CRM_Utils_System::currentPath');
329 return self::currentPath();
330 }
331
332 /**
333 * Get href.
334 *
335 * @param string $text
336 * @param string $path
337 * @param string|array $query
338 * @param bool $absolute
339 * @param string $fragment
340 * @param bool $htmlize
341 * @param bool $frontend
342 * @param bool $forceBackend
343 *
344 * @return string
345 */
346 public static function href(
347 $text, $path = NULL, $query = NULL, $absolute = TRUE,
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
354 /**
355 * Path of the current page e.g. 'civicrm/contact/view'
356 *
357 * @return string|null
358 * the current menu path
359 */
360 public static function currentPath() {
361 $config = CRM_Core_Config::singleton();
362 return isset($_GET[$config->userFrameworkURLVar]) ? trim($_GET[$config->userFrameworkURLVar], '/') : NULL;
363 }
364
365 /**
366 * Called from a template to compose a url.
367 *
368 * @param array $params
369 * List of parameters.
370 *
371 * @return string
372 * url
373 */
374 public static function crmURL($params) {
375 $p = $params['p'] ?? NULL;
376 if (!isset($p)) {
377 $p = self::currentPath();
378 }
379
380 return self::url(
381 $p,
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 /**
392 * Sets the title of the page.
393 *
394 * @param string $title
395 * Document title - plain text only
396 * @param string $pageTitle
397 * Page title (if different) - may include html
398 */
399 public static function setTitle($title, $pageTitle = NULL) {
400 self::$title = $title;
401 $config = CRM_Core_Config::singleton();
402 return $config->userSystem->setTitle($title, $pageTitle);
403 }
404
405 /**
406 * Figures and sets the userContext.
407 *
408 * Uses the referrer if valid else uses the default.
409 *
410 * @param array $names
411 * Referrer should match any str in this array.
412 * @param string $default
413 * (optional) The default userContext if no match found.
414 */
415 public static function setUserContext($names, $default = NULL) {
416 $url = $default;
417
418 $session = CRM_Core_Session::singleton();
419 $referer = $_SERVER['HTTP_REFERER'] ?? NULL;
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 /**
436 * Gets a class name for an object.
437 *
438 * @param object $object
439 * Object whose class name is needed.
440 *
441 * @return string
442 * The class name of the object.
443 */
444 public static function getClassName($object) {
445 return get_class($object);
446 }
447
448 /**
449 * Redirect to another URL.
450 *
451 * @param string $url
452 * The URL to provide to the browser via the Location header.
453 * @param array $context
454 * Optional additional information for the hook.
455 */
456 public static function redirect($url = NULL, $context = []) {
457 if (!$url) {
458 $url = self::url('civicrm/dashboard', 'reset=1');
459 }
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);
463
464 $context['output'] = $_GET['snippet'] ?? NULL;
465
466 $parsedUrl = CRM_Utils_Url::parseUrl($url);
467 CRM_Utils_Hook::alterRedirect($parsedUrl, $context);
468 $url = CRM_Utils_Url::unparseUrl($parsedUrl);
469
470 // If we are in a json context, respond appropriately
471 if ($context['output'] === 'json') {
472 CRM_Core_Page_AJAX::returnJsonResponse([
473 'status' => 'redirect',
474 'userContext' => $url,
475 ]);
476 }
477
478 self::setHttpHeader('Location', $url);
479 self::civiExit();
480 }
481
482 /**
483 * Redirect to another URL using JavaScript.
484 *
485 * Use an html based file with javascript embedded to redirect to another url
486 * This prevent the too many redirect errors emitted by various browsers
487 *
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.
494 */
495 public static function jsRedirect(
496 $url = NULL,
497 $title = NULL,
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
528 /**
529 * Get the base URL of the system.
530 *
531 * @return string
532 */
533 public static function baseURL() {
534 $config = CRM_Core_Config::singleton();
535 return $config->userFrameworkBaseURL;
536 }
537
538 /**
539 * Authenticate or abort.
540 *
541 * @param string $message
542 * @param bool $abort
543 *
544 * @return bool
545 */
546 public static function authenticateAbort($message, $abort) {
547 if ($abort) {
548 echo $message;
549 self::civiExit(0);
550 }
551 else {
552 return FALSE;
553 }
554 }
555
556 /**
557 * Authenticate key.
558 *
559 * @param bool $abort
560 * (optional) Whether to exit; defaults to true.
561 *
562 * @return bool
563 */
564 public static function authenticateKey($abort = TRUE) {
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) {
571 return self::authenticateAbort(
572 "ERROR: You need to send a valid key to execute this file. " . $docAdd . "\n",
573 $abort
574 );
575 }
576
577 $siteKey = defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : NULL;
578
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",
582 $abort
583 );
584 }
585
586 if (strlen($siteKey) < 8) {
587 return self::authenticateAbort(
588 "ERROR: Site key needs to be greater than 7 characters in civicrm.settings.php. " . $docAdd . "\n",
589 $abort
590 );
591 }
592
593 if ($key !== $siteKey) {
594 return self::authenticateAbort(
595 "ERROR: Invalid key value sent. " . $docAdd . "\n",
596 $abort
597 );
598 }
599
600 return TRUE;
601 }
602
603 /**
604 * Authenticate script.
605 *
606 * @param bool $abort
607 * @param string $name
608 * @param string $pass
609 * @param bool $storeInSession
610 * @param bool $loadCMSBootstrap
611 * @param bool $requireKey
612 *
613 * @return bool
614 */
615 public static function authenticateScript($abort = TRUE, $name = NULL, $pass = NULL, $storeInSession = TRUE, $loadCMSBootstrap = TRUE, $requireKey = TRUE) {
616 // auth to make sure the user has a login/password to do a shell operation
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) {
625 return self::authenticateAbort(
626 "ERROR: You need to send a valid user name and password to execute this file\n",
627 $abort
628 );
629 }
630
631 if ($requireKey && !self::authenticateKey($abort)) {
632 return FALSE;
633 }
634
635 $result = CRM_Utils_System::authenticate($name, $pass, $loadCMSBootstrap);
636 if (!$result) {
637 return self::authenticateAbort(
638 "ERROR: Invalid username and/or password\n",
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) {
646 $config = CRM_Core_Config::singleton();
647 $config->userSystem->setUserSession([$userID, $ufID]);
648 }
649 else {
650 return self::authenticateAbort(
651 "ERROR: Unexpected error, could not match userID and contactID",
652 $abort
653 );
654 }
655 }
656
657 return $result;
658 }
659
660 /**
661 * Authenticate the user against the uf db.
662 *
663 * In case of successful authentication, returns an array consisting of
664 * (contactID, ufID, unique string). Returns FALSE if authentication is
665 * unsuccessful.
666 *
667 * @param string $name
668 * The username.
669 * @param string $password
670 * The password.
671 * @param bool $loadCMSBootstrap
672 * @param string $realPath
673 *
674 * @return false|array
675 */
676 public static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
677 $config = CRM_Core_Config::singleton();
678
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
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.
687 */
688 $session = CRM_Core_Session::singleton();
689 $session->set('civicrmInitSession', TRUE);
690
691 if ($config->userFrameworkDSN) {
692 $dbDrupal = DB::connect($config->userFrameworkDSN);
693 }
694 return $config->userSystem->authenticate($name, $password, $loadCMSBootstrap, $realPath);
695 }
696
697 /**
698 * Set a message in the UF to display to a user.
699 *
700 * @param string $message
701 * The message to set.
702 */
703 public static function setUFMessage($message) {
704 $config = CRM_Core_Config::singleton();
705 return $config->userSystem->setMessage($message);
706 }
707
708 /**
709 * Determine whether a value is null-ish.
710 *
711 * @param mixed $value
712 * The value to check for null.
713 *
714 * @return bool
715 */
716 public static function isNull($value) {
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)) {
722 // @todo Reuse of the $value variable = asking for trouble.
723 foreach ($value as $key => $value) {
724 if (in_array($key, CRM_Core_DAO::acceptedSQLOperators(), TRUE) || !self::isNull($value)) {
725 return FALSE;
726 }
727 }
728 return TRUE;
729 }
730 return FALSE;
731 }
732
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.
740 *
741 * @return string
742 * The obscured credit card number.
743 */
744 public static function mungeCreditCard($number, $keep = 4) {
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
753 /**
754 * Determine which PHP modules are loaded.
755 *
756 * @return array
757 */
758 private static function parsePHPModules() {
759 ob_start();
760 phpinfo(INFO_MODULES);
761 $s = ob_get_contents();
762 ob_end_clean();
763
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);
768 $vModules = [];
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]);
773 foreach ($vTmp2 as $vOne) {
774 $vPat = '<info>([^<]+)<\/info>';
775 $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
776 $vPat2 = "/$vPat\s*$vPat/";
777 // 3cols
778 if (preg_match($vPat3, $vOne, $vMat)) {
779 $vModules[$vName][trim($vMat[1])] = [trim($vMat[2]), trim($vMat[3])];
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
791 /**
792 * Get a setting from a loaded PHP module.
793 *
794 * @param string $pModuleName
795 * @param string $pSetting
796 *
797 * @return mixed
798 */
799 public static function getModuleSetting($pModuleName, $pSetting) {
800 $vModules = self::parsePHPModules();
801 return $vModules[$pModuleName][$pSetting];
802 }
803
804 /**
805 * Do something no-one bothered to document.
806 *
807 * @param string $title
808 * (optional)
809 *
810 * @return mixed|string
811 */
812 public static function memory($title = NULL) {
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
826 /**
827 * Download something or other.
828 *
829 * @param string $name
830 * @param string $mimeType
831 * @param string $buffer
832 * @param string $ext
833 * @param bool $output
834 * @param string $disposition
835 */
836 public static function download(
837 $name, $mimeType, &$buffer,
838 $ext = NULL,
839 $output = TRUE,
840 $disposition = 'attachment'
841 ) {
842 $now = gmdate('D, d M Y H:i:s') . ' GMT';
843
844 self::setHttpHeader('Content-Type', $mimeType);
845 self::setHttpHeader('Expires', $now);
846
847 // lem9 & loic1: IE needs specific headers
848 $isIE = empty($_SERVER['HTTP_USER_AGENT']) ? FALSE : strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE');
849 if ($ext) {
850 $fileString = "filename=\"{$name}.{$ext}\"";
851 }
852 else {
853 $fileString = "filename=\"{$name}\"";
854 }
855 if ($isIE) {
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');
859 }
860 else {
861 self::setHttpHeader("Content-Disposition", "$disposition; $fileString");
862 self::setHttpHeader('Pragma', 'no-cache');
863 }
864
865 if ($output) {
866 print $buffer;
867 self::civiExit();
868 }
869 }
870
871 /**
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.
877 */
878 public static function xMemory($title = NULL, $log = FALSE) {
879 $mem = (float ) xdebug_memory_usage() / (float ) (1024);
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
892 /**
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 *
898 * @param string $url
899 * The URL to operate on.
900 *
901 * @return string
902 * The fixed URL.
903 */
904 public static function fixURL($url) {
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
912 // something that will mess up, so we need to clean it up here
913 return $url;
914 }
915
916 /**
917 * Make sure a callback is valid in the current context.
918 *
919 * @param string $callback
920 * Name of the function to check.
921 *
922 * @return bool
923 */
924 public static function validCallback($callback) {
925 if (self::$_callbacks === NULL) {
926 self::$_callbacks = [];
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
934 @include_once $fileName;
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 /**
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
966 *
967 * @return string[]
968 */
969 public static function explode($separator, $string, $limit) {
970 $result = explode($separator, $string, $limit);
971 for ($i = count($result); $i < $limit; $i++) {
972 $result[$i] = NULL;
973 }
974 return $result;
975 }
976
977 /**
978 * Check url.
979 *
980 * @param string $url
981 * The URL to check.
982 * @param bool $addCookie
983 * (optional)
984 *
985 * @return mixed
986 */
987 public static function checkURL($url, $addCookie = FALSE) {
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
997 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
998
999 // CRM-13227, CRM-14744: only return the SSL error status
1000 return (curl_exec($ch) !== FALSE);
1001 }
1002
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
1009 * (optional) Whether to fatally abort if the version requirement is not
1010 * met. Defaults to TRUE.
1011 *
1012 * @return bool
1013 * Returns TRUE if the requirement is met, FALSE if the requirement is not
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.
1016 *
1017 * @throws CRM_Core_Exception
1018 */
1019 public static function checkPHPVersion($ver = 5, $abort = TRUE) {
1020 $phpVersion = substr(PHP_VERSION, 0, 1);
1021 if ($phpVersion >= $ver) {
1022 return TRUE;
1023 }
1024
1025 if ($abort) {
1026 throw new CRM_Core_Exception(ts('This feature requires PHP Version %1 or greater',
1027 [1 => $ver]
1028 ));
1029 }
1030 return FALSE;
1031 }
1032
1033 /**
1034 * Format wiki url.
1035 *
1036 * @param string $string
1037 * @param bool $encode
1038 *
1039 * @return string
1040 */
1041 public static function formatWikiURL($string, $encode = FALSE) {
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
1055 /**
1056 * Encode url.
1057 *
1058 * @param string $url
1059 *
1060 * @return null|string
1061 */
1062 public static function urlEncode($url) {
1063 $items = parse_url($url);
1064 if ($items === FALSE) {
1065 return NULL;
1066 }
1067
1068 if (empty($items['query'])) {
1069 return $url;
1070 }
1071
1072 $items['query'] = urlencode($items['query']);
1073
1074 $url = $items['scheme'] . '://';
1075 if (!empty($items['user'])) {
1076 $url .= "{$items['user']}:{$items['pass']}@";
1077 }
1078
1079 $url .= $items['host'];
1080 if (!empty($items['port'])) {
1081 $url .= ":{$items['port']}";
1082 }
1083
1084 $url .= "{$items['path']}?{$items['query']}";
1085 if (!empty($items['fragment'])) {
1086 $url .= "#{$items['fragment']}";
1087 }
1088
1089 return $url;
1090 }
1091
1092 /**
1093 * Return the running civicrm version.
1094 *
1095 * @return string
1096 * civicrm version
1097 *
1098 * @throws CRM_Core_Exception
1099 */
1100 public static function version() {
1101 static $version;
1102
1103 if (!$version) {
1104 $verFile = implode(DIRECTORY_SEPARATOR,
1105 [dirname(__FILE__), '..', '..', 'xml', 'version.xml']
1106 );
1107 if (file_exists($verFile)) {
1108 $str = file_get_contents($verFile);
1109 $xmlObj = simplexml_load_string($str);
1110 $version = (string) $xmlObj->version_no;
1111 }
1112
1113 // pattern check
1114 if (!CRM_Utils_System::isVersionFormatValid($version)) {
1115 throw new CRM_Core_Exception('Unknown codebase version.');
1116 }
1117 }
1118
1119 return $version;
1120 }
1121
1122 /**
1123 * Gives the first two parts of the version string E.g. 6.1.
1124 *
1125 * @return string
1126 */
1127 public static function majorVersion() {
1128 list($a, $b) = explode('.', self::version());
1129 return "$a.$b";
1130 }
1131
1132 /**
1133 * Determines whether a string is a valid CiviCRM version string.
1134 *
1135 * @param string $version
1136 * Version string to be checked.
1137 *
1138 * @return bool
1139 */
1140 public static function isVersionFormatValid($version) {
1141 return preg_match("/^(\d{1,2}\.){2,3}(\d{1,2}|(alpha|beta)\d{1,2})(\.upgrade)?$/", $version);
1142 }
1143
1144 /**
1145 * Wraps or emulates PHP's getallheaders() function.
1146 */
1147 public static function getAllHeaders() {
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
1154 $headers = [];
1155 foreach ($_SERVER as $name => $value) {
1156 if (substr($name, 0, 5) == 'HTTP_') {
1157 $headers[str_replace(' ',
1158 '-',
1159 ucwords(strtolower(str_replace('_',
1160 ' ',
1161 substr($name, 5)
1162 )
1163 ))
1164 )] = $value;
1165 }
1166 }
1167 return $headers;
1168 }
1169
1170 /**
1171 * Get request headers.
1172 *
1173 * @return array|false
1174 */
1175 public static function getRequestHeaders() {
1176 if (function_exists('apache_request_headers')) {
1177 return apache_request_headers();
1178 }
1179 else {
1180 return $_SERVER;
1181 }
1182 }
1183
1184 /**
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.
1189 */
1190 public static function isSSL() {
1191 return !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off';
1192 }
1193
1194 /**
1195 * Redirect to SSL.
1196 *
1197 * @param bool|FALSE $abort
1198 *
1199 * @throws \CRM_Core_Exception
1200 */
1201 public static function redirectToSSL($abort = FALSE) {
1202 $config = CRM_Core_Config::singleton();
1203 $req_headers = self::getRequestHeaders();
1204 // FIXME: Shouldn't the X-Forwarded-Proto check be part of CRM_Utils_System::isSSL()?
1205 if (Civi::settings()->get('enableSSL') &&
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']}";
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]);
1213 if (!self::checkURL($url, TRUE)) {
1214 if ($abort) {
1215 throw new CRM_Core_Exception('HTTPS is not set up on this machine');
1216 }
1217 else {
1218 CRM_Core_Session::setStatus(ts('HTTPS is not set up on this machine'), ts('Warning'), 'alert');
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
1228 /**
1229 * Get logged in user's IP address.
1230 *
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)
1234 *
1235 * @param bool $strictIPV4
1236 * (optional) Whether to return only IPv4 addresses.
1237 *
1238 * @return string
1239 * IP address of logged in user.
1240 */
1241 public static function ipAddress($strictIPV4 = TRUE) {
1242 $address = $_SERVER['REMOTE_ADDR'] ?? NULL;
1243
1244 $config = CRM_Core_Config::singleton();
1245 if ($config->userSystem->is_drupal && function_exists('ip_address')) {
1246 // drupal function handles the server being behind a proxy securely. We still have legacy ipn methods
1247 // that reach this point without bootstrapping hence the check that the fn exists
1248 $address = ip_address();
1249 }
1250
1251 // hack for safari
1252 if ($address == '::1') {
1253 $address = '127.0.0.1';
1254 }
1255
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
1265 return $address;
1266 }
1267
1268 /**
1269 * Get the referring / previous page URL.
1270 *
1271 * @return string
1272 * The previous page URL
1273 */
1274 public static function refererPath() {
1275 return $_SERVER['HTTP_REFERER'] ?? NULL;
1276 }
1277
1278 /**
1279 * Get the documentation base URL.
1280 *
1281 * @return string
1282 * Base URL of the CRM documentation.
1283 */
1284 public static function getDocBaseURL() {
1285 // FIXME: move this to configuration at some stage
1286 return 'https://docs.civicrm.org/';
1287 }
1288
1289 /**
1290 * Returns wiki (alternate) documentation URL base.
1291 *
1292 * @return string
1293 * documentation url
1294 */
1295 public static function getWikiBaseURL() {
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.
1302 *
1303 * For use in PHP code.
1304 * WARNING: Always returns URL, if ts function is not defined ($URLonly has
1305 * no effect).
1306 *
1307 * @param string $page
1308 * Title of documentation wiki page.
1309 * @param bool $URLonly
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)
1317 *
1318 * @param null $resource
1319 *
1320 * @return string
1321 * URL or link to documentation page, based on provided parameters.
1322 */
1323 public static function docURL2($page, $URLonly = FALSE, $text = NULL, $title = NULL, $style = NULL, $resource = NULL) {
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') {
1328 $docBaseURL = self::getWikiBaseURL();
1329 }
1330 else {
1331 $docBaseURL = self::getDocBaseURL();
1332 $page = self::formatDocUrl($page);
1333 }
1334 return $docBaseURL . str_replace(' ', '+', $page);
1335 }
1336 else {
1337 $params = [
1338 'page' => $page,
1339 'URLonly' => $URLonly,
1340 'text' => $text,
1341 'title' => $title,
1342 'style' => $style,
1343 'resource' => $resource,
1344 ];
1345 return self::docURL($params);
1346 }
1347 }
1348
1349 /**
1350 * Returns URL or link to documentation page, based on provided parameters.
1351 *
1352 * For use in templates code.
1353 *
1354 * @param array $params
1355 * An array of parameters (see CRM_Utils_System::docURL2 method for names)
1356 *
1357 * @return null|string
1358 * URL or link to documentation page, based on provided parameters.
1359 */
1360 public static function docURL($params) {
1361
1362 if (!isset($params['page'])) {
1363 return NULL;
1364 }
1365
1366 if (CRM_Utils_Array::value('resource', $params) == 'wiki') {
1367 $docBaseURL = self::getWikiBaseURL();
1368 }
1369 else {
1370 $docBaseURL = self::getDocBaseURL();
1371 $params['page'] = self::formatDocUrl($params['page']);
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 {
1395 return "<a href=\"{$link}\" $style target=\"_blank\" class=\"crm-doc-link no-popup\" title=\"{$params['title']}\">{$params['text']}</a>";
1396 }
1397 }
1398
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) {
1408 return preg_replace('#^(user|sysadmin|dev)/#', '\1/en/stable/', $url);
1409 }
1410
1411 /**
1412 * Exit with provided exit code.
1413 *
1414 * @param int $status
1415 * (optional) Code with which to exit.
1416 *
1417 * @param array $testParameters
1418 */
1419 public static function civiExit($status = 0, $testParameters = []) {
1420
1421 if (CIVICRM_UF === 'UnitTests') {
1422 throw new CRM_Core_Exception_PrematureExitException('civiExit called', $testParameters);
1423 }
1424 if ($status > 0) {
1425 http_response_code(500);
1426 }
1427 // move things to CiviCRM cache as needed
1428 CRM_Core_Session::storeSessionObjects();
1429
1430 if (Civi\Core\Container::isContainerBooted()) {
1431 Civi::dispatcher()->dispatch('civi.core.exit');
1432 }
1433
1434 $userSystem = CRM_Core_Config::singleton()->userSystem;
1435 if (is_callable([$userSystem, 'onCiviExit'])) {
1436 $userSystem->onCiviExit();
1437 }
1438 exit($status);
1439 }
1440
1441 /**
1442 * Reset the various system caches and some important static variables.
1443 */
1444 public static function flushCache() {
1445 // flush out all cache entries so we can reload new data
1446 // a bit aggressive, but livable for now
1447 CRM_Utils_Cache::singleton()->flush();
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.
1453 $localDrivers = ['CRM_Utils_Cache_ArrayCache', 'CRM_Utils_Cache_NoCache'];
1454 if (Civi\Core\Container::isContainerBooted()
1455 && !in_array(get_class(CRM_Utils_Cache::singleton()), $localDrivers)) {
1456 Civi::cache('long')->flush();
1457 Civi::cache('settings')->flush();
1458 Civi::cache('js_strings')->flush();
1459 Civi::cache('community_messages')->flush();
1460 Civi::cache('groups')->flush();
1461 Civi::cache('navigation')->flush();
1462 Civi::cache('customData')->flush();
1463 Civi::cache('contactTypes')->clear();
1464 Civi::cache('metadata')->clear();
1465 CRM_Extension_System::singleton()->getCache()->flush();
1466 CRM_Cxn_CiviCxnHttp::singleton()->getCache()->flush();
1467 }
1468
1469 // also reset the various static memory caches
1470
1471 // reset the memory or array cache
1472 Civi::cache('fields')->flush();
1473
1474 // reset ACL cache
1475 CRM_ACL_BAO_Cache::resetCache();
1476
1477 // clear asset builder folder
1478 \Civi::service('asset_builder')->clear(FALSE);
1479
1480 // reset various static arrays used here
1481 CRM_Contact_BAO_Contact::$_importableFields = CRM_Contact_BAO_Contact::$_exportableFields
1482 = CRM_Contribute_BAO_Contribution::$_importableFields
1483 = CRM_Contribute_BAO_Contribution::$_exportableFields
1484 = CRM_Pledge_BAO_Pledge::$_exportableFields
1485 = CRM_Core_BAO_CustomField::$_importFields
1486 = CRM_Core_BAO_Cache::$_cache = CRM_Core_DAO::$_dbColumnValueCache = NULL;
1487
1488 CRM_Core_OptionGroup::flushAll();
1489 CRM_Utils_PseudoConstant::flushAll();
1490 }
1491
1492 /**
1493 * Load CMS bootstrap.
1494 *
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
1500 * @param string $realPath
1501 */
1502 public static function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
1503 if (!is_array($params)) {
1504 $params = [];
1505 }
1506 $config = CRM_Core_Config::singleton();
1507 $result = $config->userSystem->loadBootStrap($params, $loadUser, $throwError, $realPath);
1508 if (is_callable([$config->userSystem, 'setMySQLTimeZone'])) {
1509 $config->userSystem->setMySQLTimeZone();
1510 }
1511 return $result;
1512 }
1513
1514 /**
1515 * Get Base CMS url.
1516 *
1517 * @return mixed|string
1518 */
1519 public static function baseCMSURL() {
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'
1537 ) === FALSE
1538 ) {
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
1560 /**
1561 * Given a URL, return a relative URL if possible.
1562 *
1563 * @param string $url
1564 *
1565 * @return string
1566 */
1567 public static function relativeURL($url) {
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
1586 /**
1587 * Produce an absolute URL from a possibly-relative URL.
1588 *
1589 * @param string $url
1590 * @param bool $removeLanguagePart
1591 *
1592 * @return string
1593 */
1594 public static function absoluteURL($url, $removeLanguagePart = FALSE) {
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 /**
1613 * Clean url, replaces first '&' with '?'.
1614 *
1615 * @param string $url
1616 *
1617 * @return string
1618 * , clean url
1619 */
1620 public static function cleanUrl($url) {
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 *
1637 * @param bool $addLanguagePart
1638 * @param bool $removeLanguagePart
1639 *
1640 * @return string
1641 * , formatted url.
1642 */
1643 public static function languageNegotiationURL(
1644 $url,
1645 $addLanguagePart = TRUE,
1646 $removeLanguagePart = FALSE
1647 ) {
1648 return CRM_Core_Config::singleton()->userSystem->languageNegotiationURL($url, $addLanguagePart, $removeLanguagePart);
1649 }
1650
1651 /**
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
1655 * multiple custom template directories
1656 *
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.
1664 */
1665 public static function appendTPLFile(
1666 $fileName,
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 /**
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
1687 * each component of the PHP include path.
1688 *
1689 * @author Ken Zalewski
1690 *
1691 * @param string $relpath
1692 * A relative path, typically pointing to a directory with multiple class
1693 * files.
1694 *
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.
1699 */
1700 public static function listIncludeFiles($relpath) {
1701 $file_list = [];
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 }
1716
1717 /**
1718 * Get a list of all "plugins".
1719 *
1720 * (PHP classes that implement a piece of
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 *
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.
1734 *
1735 * @return array
1736 * List of plugins, where the plugin name is both the key and the value of
1737 * each element.
1738 */
1739 public static function getPluginList($relpath, $fext = '.php', $skipList = []) {
1740 $fext_len = strlen($fext);
1741 $plugins = [];
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 }
1753
1754 /**
1755 * Execute scheduled jobs.
1756 */
1757 public static function executeScheduledJobs() {
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
1770 /**
1771 * Evaluate any tokens in a URL.
1772 *
1773 * @param string|FALSE $url
1774 *
1775 * @return string|FALSE
1776 */
1777 public static function evalUrl($url) {
1778 if (!$url || strpos($url, '{') === FALSE) {
1779 return $url;
1780 }
1781 else {
1782 $config = CRM_Core_Config::singleton();
1783 $tsLocale = CRM_Core_I18n::getLocale();
1784 $vars = [
1785 '{ver}' => CRM_Utils_System::version(),
1786 '{uf}' => $config->userFramework,
1787 '{php}' => phpversion(),
1788 '{sid}' => self::getSiteID(),
1789 '{baseUrl}' => $config->userFrameworkBaseURL,
1790 '{lang}' => $tsLocale,
1791 '{co}' => $config->defaultContactCountry,
1792 ];
1793 return strtr($url, array_map('urlencode', $vars));
1794 }
1795 }
1796
1797 /**
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 *
1802 * @return string
1803 */
1804 public static function getSiteID() {
1805 $sid = Civi::settings()->get('site_id');
1806 if (!$sid) {
1807 $config = CRM_Core_Config::singleton();
1808 $sid = md5('sid_' . (defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : '') . '_' . $config->userFrameworkBaseURL);
1809 civicrm_api3('Setting', 'create', ['domain_id' => 'all', 'site_id' => $sid]);
1810 }
1811 return $sid;
1812 }
1813
1814 /**
1815 * Determine whether this is a developmental system.
1816 *
1817 * @return bool
1818 */
1819 public static function isDevelopment() {
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 }
1827
1828 /**
1829 * Is in upgrade mode.
1830 *
1831 * @return bool
1832 */
1833 public static function isInUpgradeMode() {
1834 $args = explode('/', CRM_Utils_Array::value('q', $_GET));
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 }
1843
1844 /**
1845 * Determine the standard URL for viewing or editing the specified link.
1846 *
1847 * This function delegates the decision-making to (a) the hook system and
1848 * (b) the BAO system.
1849 *
1850 * @param array $crudLinkSpec
1851 * With keys:.
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
1855 *
1856 * @return array|NULL
1857 * NULL if unavailable, or an array. array has keys:
1858 * - path: string
1859 * - query: array
1860 * - title: string
1861 * - url: string
1862 */
1863 public static function createDefaultCrudLink($crudLinkSpec) {
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
1881 $link = [];
1882 CRM_Utils_Hook::crudLink($crudLinkSpec, $bao, $link);
1883 if (empty($link) && is_callable([$bao, 'createDefaultCrudLink'])) {
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 }
1896
1897 /**
1898 * Return an HTTP Response with appropriate content and status code set.
1899 * @param \Psr\Http\Message\ResponseInterface $response
1900 */
1901 public static function sendResponse(\Psr\Http\Message\ResponseInterface $response) {
1902 $config = CRM_Core_Config::singleton()->userSystem->sendResponse($response);
1903 }
1904
1905 }