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