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