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