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