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