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