Merge pull request #7038 from eileenmcnaughton/master
[civicrm-core.git] / CRM / Utils / System.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 */
33
34 /**
35 * System wide utilities.
36 */
37 class CRM_Utils_System {
38
39 static $_callbacks = NULL;
40
41 /**
42 * @var string
43 * Page title
44 */
45 static $title = '';
46
47 /**
48 * Compose a new URL string from the current URL string.
49 *
50 * Used by all the framework components, specifically,
51 * pager, sort and qfc
52 *
53 * @param string $urlVar
54 * The url variable being considered (i.e. crmPageID, crmSortID etc).
55 * @param bool $includeReset
56 * (optional) Whether to include the reset GET string (if present).
57 * @param bool $includeForce
58 * (optional) Whether to include the force GET string (if present).
59 * @param string $path
60 * (optional) The path to use for the new url.
61 * @param bool|string $absolute
62 * (optional) Whether to return an absolute URL.
63 *
64 * @return string
65 * The URL fragment.
66 */
67 public static function makeURL($urlVar, $includeReset = FALSE, $includeForce = TRUE, $path = NULL, $absolute = FALSE) {
68 if (empty($path)) {
69 $config = CRM_Core_Config::singleton();
70 $path = CRM_Utils_Array::value($config->userFrameworkURLVar, $_GET);
71 if (empty($path)) {
72 return '';
73 }
74 }
75
76 return
77 self::url(
78 $path,
79 CRM_Utils_System::getLinksUrl($urlVar, $includeReset, $includeForce),
80 $absolute
81 );
82 }
83
84 /**
85 * Get the query string and clean it up.
86 *
87 * Strips some variables that should not be propagated, specifically variables
88 * like 'reset'. Also strips any side-affect actions (e.g. export).
89 *
90 * This function is copied mostly verbatim from Pager.php (_getLinksUrl)
91 *
92 * @param string $urlVar
93 * The URL variable being considered (e.g. crmPageID, crmSortID etc).
94 * @param bool $includeReset
95 * (optional) By default this is FALSE, meaning that the reset parameter
96 * is skipped. Set to TRUE to leave the reset parameter as-is.
97 * @param bool $includeForce
98 * (optional)
99 * @param bool $skipUFVar
100 * (optional)
101 *
102 * @return string
103 */
104 public static function getLinksUrl($urlVar, $includeReset = FALSE, $includeForce = TRUE, $skipUFVar = TRUE) {
105 // Sort out query string to prevent messy urls
106 $querystring = array();
107 $qs = array();
108 $arrays = array();
109
110 if (!empty($_SERVER['QUERY_STRING'])) {
111 $qs = explode('&', str_replace('&amp;', '&', $_SERVER['QUERY_STRING']));
112 for ($i = 0, $cnt = count($qs); $i < $cnt; $i++) {
113 // check first if exist a pair
114 if (strstr($qs[$i], '=') !== FALSE) {
115 list($name, $value) = explode('=', $qs[$i]);
116 if ($name != $urlVar) {
117 $name = rawurldecode($name);
118 // check for arrays in parameters: site.php?foo[]=1&foo[]=2&foo[]=3
119 if ((strpos($name, '[') !== FALSE) &&
120 (strpos($name, ']') !== FALSE)
121 ) {
122 $arrays[] = $qs[$i];
123 }
124 else {
125 $qs[$name] = $value;
126 }
127 }
128 }
129 else {
130 $qs[$qs[$i]] = '';
131 }
132 unset($qs[$i]);
133 }
134 }
135
136 if ($includeForce) {
137 $qs['force'] = 1;
138 }
139
140 // Ok this is a big assumption but usually works
141 // If we are in snippet mode, retain the 'section' param, if not, get rid
142 // of it.
143 if (!empty($qs['snippet'])) {
144 unset($qs['snippet']);
145 }
146 else {
147 unset($qs['section']);
148 }
149
150 if ($skipUFVar) {
151 $config = CRM_Core_Config::singleton();
152 unset($qs[$config->userFrameworkURLVar]);
153 }
154
155 foreach ($qs as $name => $value) {
156 if ($name != 'reset' || $includeReset) {
157 $querystring[] = $name . '=' . $value;
158 }
159 }
160
161 $querystring = array_merge($querystring, array_unique($arrays));
162
163 $url = implode('&', $querystring);
164 if ($urlVar) {
165 $url .= (!empty($querystring) ? '&' : '') . $urlVar . '=';
166 }
167
168 return $url;
169 }
170
171 /**
172 * If we are using a theming system, invoke theme, else just print the content.
173 *
174 * @param string $content
175 * The content that will be themed.
176 * @param bool $print
177 * (optional) Are we displaying to the screen or bypassing theming?
178 * @param bool $maintenance
179 * (optional) For maintenance mode.
180 *
181 * @return string
182 */
183 public static function theme(
184 &$content,
185 $print = FALSE,
186 $maintenance = FALSE
187 ) {
188 $config = &CRM_Core_Config::singleton();
189 return $config->userSystem->theme($content, $print, $maintenance);
190 }
191
192 /**
193 * Generate a query string if input is an array.
194 *
195 * @param array|string $query
196 *
197 * @return string
198 */
199 public static function makeQueryString($query) {
200 if (is_array($query)) {
201 $buf = '';
202 foreach ($query as $key => $value) {
203 $buf .= ($buf ? '&' : '') . urlencode($key) . '=' . urlencode($value);
204 }
205 $query = $buf;
206 }
207 return $query;
208 }
209
210 /**
211 * Generate an internal CiviCRM URL.
212 *
213 * @param string $path
214 * The path being linked to, such as "civicrm/add".
215 * @param array|string $query
216 * A query string to append to the link, or an array of key-value pairs.
217 * @param bool $absolute
218 * Whether to force the output to be an absolute link (beginning with a
219 * URI-scheme such as 'http:'). Useful for links that will be displayed
220 * outside the site, such as in an RSS feed.
221 * @param string $fragment
222 * A fragment identifier (named anchor) to append to the link.
223 *
224 * @param bool $htmlize
225 * @param bool $frontend
226 * @param bool $forceBackend
227 *
228 * @return string
229 * An HTML string containing a link to the given path.
230 */
231 public static function url(
232 $path = NULL,
233 $query = NULL,
234 $absolute = FALSE,
235 $fragment = NULL,
236 $htmlize = TRUE,
237 $frontend = FALSE,
238 $forceBackend = FALSE
239 ) {
240 $query = self::makeQueryString($query);
241
242 // we have a valid query and it has not yet been transformed
243 if ($htmlize && !empty($query) && strpos($query, '&amp;') === FALSE) {
244 $query = htmlentities($query);
245 }
246
247 $config = CRM_Core_Config::singleton();
248 return $config->userSystem->url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
249 }
250
251 /**
252 * Get href.
253 *
254 * @param string $text
255 * @param string $path
256 * @param string|array $query
257 * @param bool $absolute
258 * @param string $fragment
259 * @param bool $htmlize
260 * @param bool $frontend
261 * @param bool $forceBackend
262 *
263 * @return string
264 */
265 public static function href(
266 $text, $path = NULL, $query = NULL, $absolute = TRUE,
267 $fragment = NULL, $htmlize = TRUE, $frontend = FALSE, $forceBackend = FALSE
268 ) {
269 $url = self::url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
270 return "<a href=\"$url\">$text</a>";
271 }
272
273 /**
274 * Permission denied.
275 *
276 * @return mixed
277 */
278 public static function permissionDenied() {
279 $config = CRM_Core_Config::singleton();
280 return $config->userSystem->permissionDenied();
281 }
282
283 /**
284 * Log out.
285 *
286 * @return mixed
287 */
288 public static function logout() {
289 $config = CRM_Core_Config::singleton();
290 return $config->userSystem->logout();
291 }
292
293 /**
294 * This is a very drupal specific function for now.
295 */
296 public static function updateCategories() {
297 $config = CRM_Core_Config::singleton();
298 if ($config->userSystem->is_drupal) {
299 $config->userSystem->updateCategories();
300 }
301 }
302
303 /**
304 * What menu path are we currently on. Called for the primary tpl.
305 *
306 * @return string
307 * the current menu path
308 */
309 public static function currentPath() {
310 $config = CRM_Core_Config::singleton();
311 return trim(CRM_Utils_Array::value($config->userFrameworkURLVar, $_GET), '/');
312 }
313
314 /**
315 * Called from a template to compose a url.
316 *
317 * @param array $params
318 * List of parameters.
319 *
320 * @return string
321 * url
322 */
323 public static function crmURL($params) {
324 $p = CRM_Utils_Array::value('p', $params);
325 if (!isset($p)) {
326 $p = self::currentPath();
327 }
328
329 return self::url(
330 $p,
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 /**
341 * Sets the title of the page.
342 *
343 * @param string $title
344 * @param string $pageTitle
345 */
346 public static function setTitle($title, $pageTitle = NULL) {
347 self::$title = $title;
348 $config = CRM_Core_Config::singleton();
349 return $config->userSystem->setTitle($title, $pageTitle);
350 }
351
352 /**
353 * Figures and sets the userContext.
354 *
355 * Uses the referrer if valid else uses the default.
356 *
357 * @param array $names
358 * Referrer should match any str in this array.
359 * @param string $default
360 * (optional) The default userContext if no match found.
361 */
362 public static function setUserContext($names, $default = NULL) {
363 $url = $default;
364
365 $session = CRM_Core_Session::singleton();
366 $referer = CRM_Utils_Array::value('HTTP_REFERER', $_SERVER);
367
368 if ($referer && !empty($names)) {
369 foreach ($names as $name) {
370 if (strstr($referer, $name)) {
371 $url = $referer;
372 break;
373 }
374 }
375 }
376
377 if ($url) {
378 $session->pushUserContext($url);
379 }
380 }
381
382 /**
383 * Gets a class name for an object.
384 *
385 * @param object $object
386 * Object whose class name is needed.
387 *
388 * @return string
389 * The class name of the object.
390 */
391 public static function getClassName($object) {
392 return get_class($object);
393 }
394
395 /**
396 * Redirect to another URL.
397 *
398 * @param string $url
399 * The URL to provide to the browser via the Location header.
400 */
401 public static function redirect($url = NULL) {
402 if (!$url) {
403 $url = self::url('civicrm/dashboard', 'reset=1');
404 }
405 // replace the &amp; characters with &
406 // this is kinda hackish but not sure how to do it right
407 $url = str_replace('&amp;', '&', $url);
408
409 // If we are in a json context, respond appropriately
410 if (CRM_Utils_Array::value('snippet', $_GET) === 'json') {
411 CRM_Core_Page_AJAX::returnJsonResponse(array(
412 'status' => 'redirect',
413 'userContext' => $url,
414 ));
415 }
416
417 self::setHttpHeader('Location', $url);
418 self::civiExit();
419 }
420
421 /**
422 * Redirect to another URL using JavaScript.
423 *
424 * Use an html based file with javascript embedded to redirect to another url
425 * This prevent the too many redirect errors emitted by various browsers
426 *
427 * @param string $url
428 * (optional) The destination URL.
429 * @param string $title
430 * (optional) The page title to use for the redirect page.
431 * @param string $message
432 * (optional) The message to provide in the body of the redirect page.
433 */
434 public static function jsRedirect(
435 $url = NULL,
436 $title = NULL,
437 $message = NULL
438 ) {
439 if (!$url) {
440 $url = self::url('civicrm/dashboard', 'reset=1');
441 }
442
443 if (!$title) {
444 $title = ts('CiviCRM task in progress');
445 }
446
447 if (!$message) {
448 $message = ts('A long running CiviCRM task is currently in progress. This message will be refreshed till the task is completed');
449 }
450
451 // replace the &amp; characters with &
452 // this is kinda hackish but not sure how to do it right
453 $url = str_replace('&amp;', '&', $url);
454
455 $template = CRM_Core_Smarty::singleton();
456 $template->assign('redirectURL', $url);
457 $template->assign('title', $title);
458 $template->assign('message', $message);
459
460 $html = $template->fetch('CRM/common/redirectJS.tpl');
461
462 echo $html;
463
464 self::civiExit();
465 }
466
467 /**
468 * Append an additional breadcrumb tag to the existing breadcrumbs.
469 *
470 * @param string $breadCrumbs
471 */
472 public static function appendBreadCrumb($breadCrumbs) {
473 $config = CRM_Core_Config::singleton();
474 return $config->userSystem->appendBreadCrumb($breadCrumbs);
475 }
476
477 /**
478 * Reset an additional breadcrumb tag to the existing breadcrumb.
479 */
480 public static function resetBreadCrumb() {
481 $config = CRM_Core_Config::singleton();
482 return $config->userSystem->resetBreadCrumb();
483 }
484
485 /**
486 * Append a string to the head of the HTML file.
487 *
488 * @param string $bc
489 */
490 public static function addHTMLHead($bc) {
491 $config = CRM_Core_Config::singleton();
492 return $config->userSystem->addHTMLHead($bc);
493 }
494
495 /**
496 * Determine the post URL for a form.
497 *
498 * @param int $action
499 * The default action if one is pre-specified.
500 *
501 * @return string
502 * The URL to post the form.
503 */
504 public static function postURL($action) {
505 $config = CRM_Core_Config::singleton();
506 return $config->userSystem->postURL($action);
507 }
508
509 /**
510 * Get the base URL of the system.
511 *
512 * @return string
513 */
514 public static function baseURL() {
515 $config = CRM_Core_Config::singleton();
516 return $config->userFrameworkBaseURL;
517 }
518
519 /**
520 * Authenticate or abort.
521 *
522 * @param string $message
523 * @param bool $abort
524 *
525 * @return bool
526 */
527 public static function authenticateAbort($message, $abort) {
528 if ($abort) {
529 echo $message;
530 self::civiExit(0);
531 }
532 else {
533 return FALSE;
534 }
535 }
536
537 /**
538 * Authenticate key.
539 *
540 * @param bool $abort
541 * (optional) Whether to exit; defaults to true.
542 *
543 * @return bool
544 */
545 public static function authenticateKey($abort = TRUE) {
546 // also make sure the key is sent and is valid
547 $key = trim(CRM_Utils_Array::value('key', $_REQUEST));
548
549 $docAdd = "More info at:" . CRM_Utils_System::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
550
551 if (!$key) {
552 return self::authenticateAbort(
553 "ERROR: You need to send a valid key to execute this file. " . $docAdd . "\n",
554 $abort
555 );
556 }
557
558 $siteKey = defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : NULL;
559
560 if (!$siteKey || empty($siteKey)) {
561 return self::authenticateAbort(
562 "ERROR: You need to set a valid site key in civicrm.settings.php. " . $docAdd . "\n",
563 $abort
564 );
565 }
566
567 if (strlen($siteKey) < 8) {
568 return self::authenticateAbort(
569 "ERROR: Site key needs to be greater than 7 characters in civicrm.settings.php. " . $docAdd . "\n",
570 $abort
571 );
572 }
573
574 if ($key !== $siteKey) {
575 return self::authenticateAbort(
576 "ERROR: Invalid key value sent. " . $docAdd . "\n",
577 $abort
578 );
579 }
580
581 return TRUE;
582 }
583
584 /**
585 * Authenticate script.
586 *
587 * @param bool $abort
588 * @param string $name
589 * @param string $pass
590 * @param bool $storeInSession
591 * @param bool $loadCMSBootstrap
592 * @param bool $requireKey
593 *
594 * @return bool
595 */
596 public static function authenticateScript($abort = TRUE, $name = NULL, $pass = NULL, $storeInSession = TRUE, $loadCMSBootstrap = TRUE, $requireKey = TRUE) {
597 // auth to make sure the user has a login/password to do a shell operation
598 // later on we'll link this to acl's
599 if (!$name) {
600 $name = trim(CRM_Utils_Array::value('name', $_REQUEST));
601 $pass = trim(CRM_Utils_Array::value('pass', $_REQUEST));
602 }
603
604 // its ok to have an empty password
605 if (!$name) {
606 return self::authenticateAbort(
607 "ERROR: You need to send a valid user name and password to execute this file\n",
608 $abort
609 );
610 }
611
612 if ($requireKey && !self::authenticateKey($abort)) {
613 return FALSE;
614 }
615
616 $result = CRM_Utils_System::authenticate($name, $pass, $loadCMSBootstrap);
617 if (!$result) {
618 return self::authenticateAbort(
619 "ERROR: Invalid username and/or password\n",
620 $abort
621 );
622 }
623 elseif ($storeInSession) {
624 // lets store contact id and user id in session
625 list($userID, $ufID, $randomNumber) = $result;
626 if ($userID && $ufID) {
627 $config = CRM_Core_Config::singleton();
628 $config->userSystem->setUserSession(array($userID, $ufID));
629 }
630 else {
631 return self::authenticateAbort(
632 "ERROR: Unexpected error, could not match userID and contactID",
633 $abort
634 );
635 }
636 }
637
638 return $result;
639 }
640
641 /**
642 * Authenticate the user against the uf db.
643 *
644 * In case of successful authentication, returns an array consisting of
645 * (contactID, ufID, unique string). Returns FALSE if authentication is
646 * unsuccessful.
647 *
648 * @param string $name
649 * The username.
650 * @param string $password
651 * The password.
652 * @param bool $loadCMSBootstrap
653 * @param string $realPath
654 *
655 * @return false|array
656 */
657 public static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
658 $config = CRM_Core_Config::singleton();
659
660 /* Before we do any loading, let's start the session and write to it.
661 * We typically call authenticate only when we need to bootstrap the CMS
662 * directly via Civi and hence bypass the normal CMS auth and bootstrap
663 * process typically done in CLI and cron scripts. See: CRM-12648
664 *
665 * Q: Can we move this to the userSystem class so that it can be tuned
666 * per-CMS? For example, when dealing with UnitTests UF, there's no
667 * userFrameworkDSN.
668 */
669 $session = CRM_Core_Session::singleton();
670 $session->set('civicrmInitSession', TRUE);
671
672 if ($config->userFrameworkDSN) {
673 $dbDrupal = DB::connect($config->userFrameworkDSN);
674 }
675 return $config->userSystem->authenticate($name, $password, $loadCMSBootstrap, $realPath);
676 }
677
678 /**
679 * Set a message in the UF to display to a user.
680 *
681 * @param string $message
682 * The message to set.
683 */
684 public static function setUFMessage($message) {
685 $config = CRM_Core_Config::singleton();
686 return $config->userSystem->setMessage($message);
687 }
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 (!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 = array();
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])] = array(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 = array();
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 array(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 array(dirname(__FILE__), '..', '..', 'civicrm-version.php')
1084 );
1085 if (file_exists($verFile)) {
1086 require_once $verFile;
1087 if (function_exists('civicrmVersion')) {
1088 $info = civicrmVersion();
1089 $version = $info['version'];
1090 }
1091 }
1092 else {
1093 // svn installs don't have version.txt by default. In that case version.xml should help -
1094 $verFile = implode(DIRECTORY_SEPARATOR,
1095 array(dirname(__FILE__), '..', '..', 'xml', 'version.xml')
1096 );
1097 if (file_exists($verFile)) {
1098 $str = file_get_contents($verFile);
1099 $xmlObj = simplexml_load_string($str);
1100 $version = (string) $xmlObj->version_no;
1101 }
1102 }
1103
1104 // pattern check
1105 if (!CRM_Utils_System::isVersionFormatValid($version)) {
1106 CRM_Core_Error::fatal('Unknown codebase version.');
1107 }
1108 }
1109
1110 return $version;
1111 }
1112
1113 /**
1114 * Gives the first two parts of the version string E.g. 6.1.
1115 *
1116 * @return string
1117 */
1118 public static function majorVersion() {
1119 list($a, $b) = explode('.', self::version());
1120 return "$a.$b";
1121 }
1122
1123 /**
1124 * Determines whether a string is a valid CiviCRM version string.
1125 *
1126 * @param string $version
1127 * Version string to be checked.
1128 *
1129 * @return bool
1130 */
1131 public static function isVersionFormatValid($version) {
1132 return preg_match("/^(\d{1,2}\.){2,3}(\d{1,2}|(alpha|beta)\d{1,2})(\.upgrade)?$/", $version);
1133 }
1134
1135 /**
1136 * Wraps or emulates PHP's getallheaders() function.
1137 */
1138 public static function getAllHeaders() {
1139 if (function_exists('getallheaders')) {
1140 return getallheaders();
1141 }
1142
1143 // emulate get all headers
1144 // http://www.php.net/manual/en/function.getallheaders.php#66335
1145 $headers = array();
1146 foreach ($_SERVER as $name => $value) {
1147 if (substr($name, 0, 5) == 'HTTP_') {
1148 $headers[str_replace(' ',
1149 '-',
1150 ucwords(strtolower(str_replace('_',
1151 ' ',
1152 substr($name, 5)
1153 )
1154 ))
1155 )] = $value;
1156 }
1157 }
1158 return $headers;
1159 }
1160
1161 /**
1162 * Get request headers.
1163 *
1164 * @return array|false
1165 */
1166 public static function getRequestHeaders() {
1167 if (function_exists('apache_request_headers')) {
1168 return apache_request_headers();
1169 }
1170 else {
1171 return $_SERVER;
1172 }
1173 }
1174
1175 /**
1176 * Determine whether this is an SSL request.
1177 *
1178 * Note that we inline this function in install/civicrm.php, so if you change
1179 * this function, please go and change the code in the install script as well.
1180 */
1181 public static function isSSL() {
1182 return
1183 (isset($_SERVER['HTTPS']) &&
1184 !empty($_SERVER['HTTPS']) &&
1185 strtolower($_SERVER['HTTPS']) != 'off') ? TRUE : FALSE;
1186 }
1187
1188 /**
1189 * Redirect to SSL.
1190 *
1191 * @param bool|FALSE $abort
1192 *
1193 * @throws \Exception
1194 */
1195 public static function redirectToSSL($abort = FALSE) {
1196 $config = CRM_Core_Config::singleton();
1197 $req_headers = self::getRequestHeaders();
1198 // FIXME: Shouldn't the X-Forwarded-Proto check be part of CRM_Utils_System::isSSL()?
1199 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'enableSSL') &&
1200 !self::isSSL() &&
1201 strtolower(CRM_Utils_Array::value('X_FORWARDED_PROTO', $req_headers)) != 'https'
1202 ) {
1203 // ensure that SSL is enabled on a civicrm url (for cookie reasons etc)
1204 $url = "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
1205 if (!self::checkURL($url, TRUE)) {
1206 if ($abort) {
1207 CRM_Core_Error::fatal('HTTPS is not set up on this machine');
1208 }
1209 else {
1210 CRM_Core_Session::setStatus(ts('HTTPS is not set up on this machine'), ts('Warning'), 'alert');
1211 // admin should be the only one following this
1212 // since we dont want the user stuck in a bad place
1213 return;
1214 }
1215 }
1216 CRM_Utils_System::redirect($url);
1217 }
1218 }
1219
1220 /**
1221 * Get logged in user's IP address.
1222 *
1223 * Get IP address from HTTP REMOTE_ADDR header. If the CMS is Drupal then use
1224 * the Drupal function as this also handles reverse proxies (based on proper
1225 * configuration in settings.php)
1226 *
1227 * @param bool $strictIPV4
1228 * (optional) Whether to return only IPv4 addresses.
1229 *
1230 * @return string
1231 * IP address of logged in user.
1232 */
1233 public static function ipAddress($strictIPV4 = TRUE) {
1234 $address = CRM_Utils_Array::value('REMOTE_ADDR', $_SERVER);
1235
1236 $config = CRM_Core_Config::singleton();
1237 if ($config->userSystem->is_drupal && function_exists('ip_address')) {
1238 // drupal function handles the server being behind a proxy securely. We still have legacy ipn methods
1239 // that reach this point without bootstrapping hence the check that the fn exists
1240 $address = ip_address();
1241 }
1242
1243 // hack for safari
1244 if ($address == '::1') {
1245 $address = '127.0.0.1';
1246 }
1247
1248 // when we need to have strictly IPV4 ip address
1249 // convert ipV6 to ipV4
1250 if ($strictIPV4) {
1251 // this converts 'IPV4 mapped IPV6 address' to IPV4
1252 if (filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && strstr($address, '::ffff:')) {
1253 $address = ltrim($address, '::ffff:');
1254 }
1255 }
1256
1257 return $address;
1258 }
1259
1260 /**
1261 * Get the referring / previous page URL.
1262 *
1263 * @return string
1264 * The previous page URL
1265 */
1266 public static function refererPath() {
1267 return CRM_Utils_Array::value('HTTP_REFERER', $_SERVER);
1268 }
1269
1270 /**
1271 * Get the documentation base URL.
1272 *
1273 * @return string
1274 * Base URL of the CRM documentation.
1275 */
1276 public static function getDocBaseURL() {
1277 // FIXME: move this to configuration at some stage
1278 return 'http://book.civicrm.org/';
1279 }
1280
1281 /**
1282 * Returns wiki (alternate) documentation URL base.
1283 *
1284 * @return string
1285 * documentation url
1286 */
1287 public static function getWikiBaseURL() {
1288 // FIXME: move this to configuration at some stage
1289 return 'http://wiki.civicrm.org/confluence/display/CRMDOC/';
1290 }
1291
1292 /**
1293 * Returns URL or link to documentation page, based on provided parameters.
1294 *
1295 * For use in PHP code.
1296 * WARNING: Always returns URL, if ts function is not defined ($URLonly has
1297 * no effect).
1298 *
1299 * @param string $page
1300 * Title of documentation wiki page.
1301 * @param bool $URLonly
1302 * (optional) Whether to return URL only or full HTML link (default).
1303 * @param string $text
1304 * (optional) Text of HTML link (no effect if $URLonly = false).
1305 * @param string $title
1306 * (optional) Tooltip text for HTML link (no effect if $URLonly = false)
1307 * @param string $style
1308 * (optional) Style attribute value for HTML link (no effect if $URLonly = false)
1309 *
1310 * @param null $resource
1311 *
1312 * @return string
1313 * URL or link to documentation page, based on provided parameters.
1314 */
1315 public static function docURL2($page, $URLonly = FALSE, $text = NULL, $title = NULL, $style = NULL, $resource = NULL) {
1316 // if ts function doesn't exist, it means that CiviCRM hasn't been fully initialised yet -
1317 // return just the URL, no matter what other parameters are defined
1318 if (!function_exists('ts')) {
1319 if ($resource == 'wiki') {
1320 $docBaseURL = self::getWikiBaseURL();
1321 }
1322 else {
1323 $docBaseURL = self::getDocBaseURL();
1324 }
1325 return $docBaseURL . str_replace(' ', '+', $page);
1326 }
1327 else {
1328 $params = array(
1329 'page' => $page,
1330 'URLonly' => $URLonly,
1331 'text' => $text,
1332 'title' => $title,
1333 'style' => $style,
1334 'resource' => $resource,
1335 );
1336 return self::docURL($params);
1337 }
1338 }
1339
1340 /**
1341 * Returns URL or link to documentation page, based on provided parameters.
1342 *
1343 * For use in templates code.
1344 *
1345 * @param array $params
1346 * An array of parameters (see CRM_Utils_System::docURL2 method for names)
1347 *
1348 * @return null|string
1349 * URL or link to documentation page, based on provided parameters.
1350 */
1351 public static function docURL($params) {
1352
1353 if (!isset($params['page'])) {
1354 return NULL;
1355 }
1356
1357 if (CRM_Utils_Array::value('resource', $params) == 'wiki') {
1358 $docBaseURL = self::getWikiBaseURL();
1359 }
1360 else {
1361 $docBaseURL = self::getDocBaseURL();
1362 }
1363
1364 if (!isset($params['title']) or $params['title'] === NULL) {
1365 $params['title'] = ts('Opens documentation in a new window.');
1366 }
1367
1368 if (!isset($params['text']) or $params['text'] === NULL) {
1369 $params['text'] = ts('(learn more...)');
1370 }
1371
1372 if (!isset($params['style']) || $params['style'] === NULL) {
1373 $style = '';
1374 }
1375 else {
1376 $style = "style=\"{$params['style']}\"";
1377 }
1378
1379 $link = $docBaseURL . str_replace(' ', '+', $params['page']);
1380
1381 if (isset($params['URLonly']) && $params['URLonly'] == TRUE) {
1382 return $link;
1383 }
1384 else {
1385 return "<a href=\"{$link}\" $style target=\"_blank\" class=\"crm-doc-link no-popup\" title=\"{$params['title']}\">{$params['text']}</a>";
1386 }
1387 }
1388
1389 /**
1390 * Get the locale of the hosting CMS.
1391 *
1392 * @return string
1393 * The used locale or null for none.
1394 */
1395 public static function getUFLocale() {
1396 $config = CRM_Core_Config::singleton();
1397 return $config->userSystem->getUFLocale();
1398 }
1399
1400 /**
1401 * Set the locale of the hosting CMS.
1402 *
1403 * For example, a mailing will want to change the CMS language so that
1404 * URLs are in the correct language (such as the Drupal language prefix).
1405 *
1406 * @param string $civicrm_language
1407 * An array of parameters (see CRM_Utils_System::docURL2 method for names)
1408 *
1409 * @return bool
1410 * Returns whether the locale was successfully changed.
1411 */
1412 public static function setUFLocale($civicrm_language) {
1413 $config = CRM_Core_Config::singleton();
1414 return $config->userSystem->setUFLocale($civicrm_language);
1415 }
1416
1417 /**
1418 * Execute external or internal URLs and return server response.
1419 *
1420 * @param string $url
1421 * Request URL.
1422 * @param bool $addCookie
1423 * Whether to provide a cookie. Should be true to access internal URLs.
1424 *
1425 * @return string
1426 * Response from URL.
1427 */
1428 public static function getServerResponse($url, $addCookie = TRUE) {
1429 CRM_Core_TemporaryErrorScope::ignoreException();
1430 require_once 'HTTP/Request.php';
1431 $request = new HTTP_Request($url);
1432
1433 if ($addCookie) {
1434 foreach ($_COOKIE as $name => $value) {
1435 $request->addCookie($name, $value);
1436 }
1437 }
1438
1439 if (isset($_SERVER['AUTH_TYPE'])) {
1440 $request->setBasicAuth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
1441 }
1442
1443 $config = CRM_Core_Config::singleton();
1444 if ($config->userFramework == 'WordPress') {
1445 session_write_close();
1446 }
1447
1448 $request->sendRequest();
1449 $response = $request->getResponseBody();
1450
1451 return $response;
1452 }
1453
1454 /**
1455 * Exit with provided exit code.
1456 *
1457 * @param int $status
1458 * (optional) Code with which to exit.
1459 */
1460 public static function civiExit($status = 0) {
1461 // move things to CiviCRM cache as needed
1462 CRM_Core_Session::storeSessionObjects();
1463
1464 exit($status);
1465 }
1466
1467 /**
1468 * Reset the various system caches and some important static variables.
1469 */
1470 public static function flushCache() {
1471 // flush out all cache entries so we can reload new data
1472 // a bit aggressive, but livable for now
1473 $cache = CRM_Utils_Cache::singleton();
1474 $cache->flush();
1475
1476 // also reset the various static memory caches
1477
1478 // reset the memory or array cache
1479 CRM_Core_BAO_Cache::deleteGroup('contact fields', NULL, FALSE);
1480
1481 // reset ACL cache
1482 CRM_ACL_BAO_Cache::resetCache();
1483
1484 // reset various static arrays used here
1485 CRM_Contact_BAO_Contact::$_importableFields = CRM_Contact_BAO_Contact::$_exportableFields
1486 = CRM_Contribute_BAO_Contribution::$_importableFields
1487 = CRM_Contribute_BAO_Contribution::$_exportableFields
1488 = CRM_Pledge_BAO_Pledge::$_exportableFields = CRM_Contribute_BAO_Query::$_contributionFields
1489 = CRM_Core_BAO_CustomField::$_importFields
1490 = CRM_Core_BAO_Cache::$_cache = CRM_Core_DAO::$_dbColumnValueCache = NULL;
1491
1492 CRM_Core_OptionGroup::flushAll();
1493 CRM_Utils_PseudoConstant::flushAll();
1494 }
1495
1496 /**
1497 * Load CMS bootstrap.
1498 *
1499 * @param array $params
1500 * Array with uid name and pass
1501 * @param bool $loadUser
1502 * Boolean load user or not.
1503 * @param bool $throwError
1504 * @param string $realPath
1505 */
1506 public static function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
1507 if (!is_array($params)) {
1508 $params = array();
1509 }
1510 $config = CRM_Core_Config::singleton();
1511 return $config->userSystem->loadBootStrap($params, $loadUser, $throwError, $realPath);
1512 }
1513
1514 /**
1515 * Check if user is logged in.
1516 *
1517 * @return bool
1518 */
1519 public static function isUserLoggedIn() {
1520 $config = CRM_Core_Config::singleton();
1521 return $config->userSystem->isUserLoggedIn();
1522 }
1523
1524 /**
1525 * Get current logged in user id.
1526 *
1527 * @return int
1528 * ufId, currently logged in user uf id.
1529 */
1530 public static function getLoggedInUfID() {
1531 $config = CRM_Core_Config::singleton();
1532 return $config->userSystem->getLoggedInUfID();
1533 }
1534
1535 /**
1536 * Get Base CMS url.
1537 *
1538 * @return mixed|string
1539 */
1540 public static function baseCMSURL() {
1541 static $_baseURL = NULL;
1542 if (!$_baseURL) {
1543 $config = CRM_Core_Config::singleton();
1544 $_baseURL = $userFrameworkBaseURL = $config->userFrameworkBaseURL;
1545
1546 if ($config->userFramework == 'Joomla') {
1547 // gross hack
1548 // we need to remove the administrator/ from the end
1549 $_baseURL = str_replace("/administrator/", "/", $userFrameworkBaseURL);
1550 }
1551 else {
1552 // Drupal setting
1553 global $civicrm_root;
1554 if (strpos($civicrm_root,
1555 DIRECTORY_SEPARATOR . 'sites' .
1556 DIRECTORY_SEPARATOR . 'all' .
1557 DIRECTORY_SEPARATOR . 'modules'
1558 ) === FALSE
1559 ) {
1560 $startPos = strpos($civicrm_root,
1561 DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR
1562 );
1563 $endPos = strpos($civicrm_root,
1564 DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR
1565 );
1566 if ($startPos && $endPos) {
1567 // if component is in sites/SITENAME/modules
1568 $siteName = substr($civicrm_root,
1569 $startPos + 7,
1570 $endPos - $startPos - 7
1571 );
1572
1573 $_baseURL = $userFrameworkBaseURL . "sites/$siteName/";
1574 }
1575 }
1576 }
1577 }
1578 return $_baseURL;
1579 }
1580
1581 /**
1582 * Given a URL, return a relative URL if possible.
1583 *
1584 * @param string $url
1585 *
1586 * @return string
1587 */
1588 public static function relativeURL($url) {
1589 // check if url is relative, if so return immediately
1590 if (substr($url, 0, 4) != 'http') {
1591 return $url;
1592 }
1593
1594 // make everything relative from the baseFilePath
1595 $baseURL = self::baseCMSURL();
1596
1597 // check if baseURL is a substr of $url, if so
1598 // return rest of string
1599 if (substr($url, 0, strlen($baseURL)) == $baseURL) {
1600 return substr($url, strlen($baseURL));
1601 }
1602
1603 // return the original value
1604 return $url;
1605 }
1606
1607 /**
1608 * Produce an absolute URL from a possibly-relative URL.
1609 *
1610 * @param string $url
1611 * @param bool $removeLanguagePart
1612 *
1613 * @return string
1614 */
1615 public static function absoluteURL($url, $removeLanguagePart = FALSE) {
1616 // check if url is already absolute, if so return immediately
1617 if (substr($url, 0, 4) == 'http') {
1618 return $url;
1619 }
1620
1621 // make everything absolute from the baseFileURL
1622 $baseURL = self::baseCMSURL();
1623
1624 //CRM-7622: drop the language from the URL if requested (and it’s there)
1625 $config = CRM_Core_Config::singleton();
1626 if ($removeLanguagePart) {
1627 $baseURL = self::languageNegotiationURL($baseURL, FALSE, TRUE);
1628 }
1629
1630 return $baseURL . $url;
1631 }
1632
1633 /**
1634 * Clean url, replaces first '&' with '?'.
1635 *
1636 * @param string $url
1637 *
1638 * @return string
1639 * , clean url
1640 */
1641 public static function cleanUrl($url) {
1642 if (!$url) {
1643 return NULL;
1644 }
1645
1646 if ($pos = strpos($url, '&')) {
1647 $url = substr_replace($url, '?', $pos, 1);
1648 }
1649
1650 return $url;
1651 }
1652
1653 /**
1654 * Format the url as per language Negotiation.
1655 *
1656 * @param string $url
1657 *
1658 * @param bool $addLanguagePart
1659 * @param bool $removeLanguagePart
1660 *
1661 * @return string
1662 * , formatted url.
1663 */
1664 public static function languageNegotiationURL(
1665 $url,
1666 $addLanguagePart = TRUE,
1667 $removeLanguagePart = FALSE
1668 ) {
1669 $config = &CRM_Core_Config::singleton();
1670 return $config->userSystem->languageNegotiationURL($url, $addLanguagePart, $removeLanguagePart);
1671 }
1672
1673 /**
1674 * Append the contents of an 'extra' smarty template file.
1675 *
1676 * It must be present in the custom template directory. This does not work if there are
1677 * multiple custom template directories
1678 *
1679 * @param string $fileName
1680 * The name of the tpl file that we are processing.
1681 * @param string $content
1682 * The current content string. May be modified by this function.
1683 * @param string $overideFileName
1684 * (optional) Sent by contribution/event reg/profile pages which uses a id
1685 * specific extra file name if present.
1686 */
1687 public static function appendTPLFile(
1688 $fileName,
1689 &$content,
1690 $overideFileName = NULL
1691 ) {
1692 $template = CRM_Core_Smarty::singleton();
1693 if ($overideFileName) {
1694 $additionalTPLFile = $overideFileName;
1695 }
1696 else {
1697 $additionalTPLFile = str_replace('.tpl', '.extra.tpl', $fileName);
1698 }
1699
1700 if ($template->template_exists($additionalTPLFile)) {
1701 $content .= $template->fetch($additionalTPLFile);
1702 }
1703 }
1704
1705 /**
1706 * Get a list of all files that are found within the directories.
1707 *
1708 * Files must be the result of appending the provided relative path to
1709 * each component of the PHP include path.
1710 *
1711 * @author Ken Zalewski
1712 *
1713 * @param string $relpath
1714 * A relative path, typically pointing to a directory with multiple class
1715 * files.
1716 *
1717 * @return array
1718 * An array of files that exist in one or more of the directories that are
1719 * referenced by the relative path when appended to each element of the PHP
1720 * include path.
1721 */
1722 public static function listIncludeFiles($relpath) {
1723 $file_list = array();
1724 $inc_dirs = explode(PATH_SEPARATOR, get_include_path());
1725 foreach ($inc_dirs as $inc_dir) {
1726 $target_dir = $inc_dir . DIRECTORY_SEPARATOR . $relpath;
1727 if (is_dir($target_dir)) {
1728 $cur_list = scandir($target_dir);
1729 foreach ($cur_list as $fname) {
1730 if ($fname != '.' && $fname != '..') {
1731 $file_list[$fname] = $fname;
1732 }
1733 }
1734 }
1735 }
1736 return $file_list;
1737 }
1738
1739 /**
1740 * Get a list of all "plugins".
1741 *
1742 * (PHP classes that implement a piece of
1743 * functionality using a well-defined interface) that are found in a
1744 * particular CiviCRM directory (both custom and core are searched).
1745 *
1746 * @author Ken Zalewski
1747 *
1748 * @param string $relpath
1749 * A relative path referencing a directory that contains one or more
1750 * plugins.
1751 * @param string $fext
1752 * (optional) Only files with this extension will be considered to be
1753 * plugins.
1754 * @param array $skipList
1755 * (optional) List of files to skip.
1756 *
1757 * @return array
1758 * List of plugins, where the plugin name is both the key and the value of
1759 * each element.
1760 */
1761 public static function getPluginList($relpath, $fext = '.php', $skipList = array()) {
1762 $fext_len = strlen($fext);
1763 $plugins = array();
1764 $inc_files = CRM_Utils_System::listIncludeFiles($relpath);
1765 foreach ($inc_files as $inc_file) {
1766 if (substr($inc_file, 0 - $fext_len) == $fext) {
1767 $plugin_name = substr($inc_file, 0, 0 - $fext_len);
1768 if (!in_array($plugin_name, $skipList)) {
1769 $plugins[$plugin_name] = $plugin_name;
1770 }
1771 }
1772 }
1773 return $plugins;
1774 }
1775
1776 /**
1777 * Execute scheduled jobs.
1778 */
1779 public static function executeScheduledJobs() {
1780 $facility = new CRM_Core_JobManager();
1781 $facility->execute(FALSE);
1782
1783 $redirectUrl = self::url('civicrm/admin/job', 'reset=1');
1784
1785 CRM_Core_Session::setStatus(
1786 ts('Scheduled jobs have been executed according to individual timing settings. Please check log for messages.'),
1787 ts('Complete'), 'success');
1788
1789 CRM_Utils_System::redirect($redirectUrl);
1790 }
1791
1792 /**
1793 * Evaluate any tokens in a URL.
1794 *
1795 * @param string|FALSE $url
1796 *
1797 * @return string|FALSE
1798 */
1799 public static function evalUrl($url) {
1800 if (!$url || strpos($url, '{') === FALSE) {
1801 return $url;
1802 }
1803 else {
1804 $config = CRM_Core_Config::singleton();
1805 $vars = array(
1806 '{ver}' => CRM_Utils_System::version(),
1807 '{uf}' => $config->userFramework,
1808 '{php}' => phpversion(),
1809 '{sid}' => self::getSiteID(),
1810 '{baseUrl}' => $config->userFrameworkBaseURL,
1811 '{lang}' => $config->lcMessages,
1812 '{co}' => $config->defaultContactCountry,
1813 );
1814 return strtr($url, array_map('urlencode', $vars));
1815 }
1816 }
1817
1818 /**
1819 * Returns the unique identifier for this site, as used by community messages.
1820 *
1821 * SiteID will be generated if it is not already stored in the settings table.
1822 *
1823 * @return string
1824 */
1825 public static function getSiteID() {
1826 $sid = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'site_id');
1827 if (!$sid) {
1828 $config = CRM_Core_Config::singleton();
1829 $sid = md5('sid_' . (defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : '') . '_' . $config->userFrameworkBaseURL);
1830 civicrm_api3('Setting', 'create', array('domain_id' => 'all', 'site_id' => $sid));
1831 }
1832 return $sid;
1833 }
1834
1835 /**
1836 * Determine whether this is a developmental system.
1837 *
1838 * @return bool
1839 */
1840 public static function isDevelopment() {
1841 static $cache = NULL;
1842 if ($cache === NULL) {
1843 global $civicrm_root;
1844 $cache = file_exists("{$civicrm_root}/.svn") || file_exists("{$civicrm_root}/.git");
1845 }
1846 return $cache;
1847 }
1848
1849 /**
1850 * Is in upgrade mode.
1851 *
1852 * @return bool
1853 */
1854 public static function isInUpgradeMode() {
1855 $args = explode('/', CRM_Utils_Array::value('q', $_GET));
1856 $upgradeInProcess = CRM_Core_Session::singleton()->get('isUpgradePending');
1857 if ((isset($args[1]) && $args[1] == 'upgrade') || $upgradeInProcess) {
1858 return TRUE;
1859 }
1860 else {
1861 return FALSE;
1862 }
1863 }
1864
1865 /**
1866 * Determine the standard URL for viewing or editing the specified link.
1867 *
1868 * This function delegates the decision-making to (a) the hook system and
1869 * (b) the BAO system.
1870 *
1871 * @param array $crudLinkSpec
1872 * With keys:.
1873 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
1874 * - entity_table: string, eg "civicrm_contact"
1875 * - entity_id: int
1876 *
1877 * @return array|NULL
1878 * NULL if unavailable, or an array. array has keys:
1879 * - path: string
1880 * - query: array
1881 * - title: string
1882 * - url: string
1883 */
1884 public static function createDefaultCrudLink($crudLinkSpec) {
1885 $crudLinkSpec['action'] = CRM_Utils_Array::value('action', $crudLinkSpec, CRM_Core_Action::VIEW);
1886 $daoClass = CRM_Core_DAO_AllCoreTables::getClassForTable($crudLinkSpec['entity_table']);
1887 if (!$daoClass) {
1888 return NULL;
1889 }
1890
1891 $baoClass = str_replace('_DAO_', '_BAO_', $daoClass);
1892 if (!class_exists($baoClass)) {
1893 return NULL;
1894 }
1895
1896 $bao = new $baoClass();
1897 $bao->id = $crudLinkSpec['entity_id'];
1898 if (!$bao->find(TRUE)) {
1899 return NULL;
1900 }
1901
1902 $link = array();
1903 CRM_Utils_Hook::crudLink($crudLinkSpec, $bao, $link);
1904 if (empty($link) && is_callable(array($bao, 'createDefaultCrudLink'))) {
1905 $link = $bao->createDefaultCrudLink($crudLinkSpec);
1906 }
1907
1908 if (!empty($link)) {
1909 if (!isset($link['url'])) {
1910 $link['url'] = self::url($link['path'], $link['query'], TRUE, NULL, FALSE);
1911 }
1912 return $link;
1913 }
1914
1915 return NULL;
1916 }
1917
1918 /**
1919 * Set http header.
1920 *
1921 * @param string $name
1922 * @param string $value
1923 */
1924 public static function setHttpHeader($name, $value) {
1925 CRM_Core_Config::singleton()->userSystem->setHttpHeader($name, $value);
1926 }
1927
1928 }