Merge pull request #10407 from JMAConsulting/CRM-19653
[civicrm-core.git] / CRM / Utils / System / DrupalBase.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
32 * $Id$
33 *
34 */
35
36 /**
37 * Drupal specific stuff goes here
38 */
39 abstract class CRM_Utils_System_DrupalBase extends CRM_Utils_System_Base {
40
41 /**
42 * Does this CMS / UF support a CMS specific logging mechanism?
43 * @todo - we should think about offering up logging mechanisms in a way that is also extensible by extensions
44 * @var bool
45 */
46 var $supports_UF_Logging = TRUE;
47
48 /**
49 */
50 public function __construct() {
51 /**
52 * deprecated property to check if this is a drupal install. The correct method is to have functions on the UF classes for all UF specific
53 * functions and leave the codebase oblivious to the type of CMS
54 * @deprecated
55 * @var bool
56 */
57 $this->is_drupal = TRUE;
58 $this->supports_form_extensions = TRUE;
59 }
60
61 /**
62 * @inheritDoc
63 */
64 public function getCiviSourceStorage() {
65 global $civicrm_root;
66
67 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
68 // More generally, we shouldn't be using $config here.
69 if (!defined('CIVICRM_UF_BASEURL')) {
70 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
71 }
72
73 $cmsUrl = CIVICRM_UF_BASEURL;
74 if (CRM_Utils_System::isSSL()) {
75 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
76 }
77 $civiRelPath = CRM_Utils_File::relativize(realpath($civicrm_root), realpath($this->cmsRootPath()));
78 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
79 return array(
80 'url' => CRM_Utils_File::addTrailingSlash($civiUrl, '/'),
81 'path' => CRM_Utils_File::addTrailingSlash($civicrm_root),
82 );
83 }
84
85 /**
86 * @inheritdoc
87 */
88 public function getDefaultFileStorage() {
89 $config = CRM_Core_Config::singleton();
90 $baseURL = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
91
92 $siteName = $this->parseDrupalSiteName('/files/civicrm');
93 if ($siteName) {
94 $filesURL = $baseURL . "sites/$siteName/files/civicrm/";
95 }
96 else {
97 $filesURL = $baseURL . "sites/default/files/civicrm/";
98 }
99
100 return array(
101 'url' => $filesURL,
102 'path' => CRM_Utils_File::baseFilePath(),
103 );
104 }
105
106 /**
107 * @inheritDoc
108 */
109 public function getDefaultSiteSettings($dir) {
110 $config = CRM_Core_Config::singleton();
111 $siteName = $siteRoot = NULL;
112 $matches = array();
113 if (preg_match(
114 '|/sites/([\w\.\-\_]+)/|',
115 $config->templateCompileDir,
116 $matches
117 )) {
118 $siteName = $matches[1];
119 if ($siteName) {
120 $siteName = "/sites/$siteName/";
121 $siteNamePos = strpos($dir, $siteName);
122 if ($siteNamePos !== FALSE) {
123 $siteRoot = substr($dir, 0, $siteNamePos);
124 }
125 }
126 }
127 $url = $config->userFrameworkBaseURL;
128 return array($url, $siteName, $siteRoot);
129 }
130
131 /**
132 * Check if a resource url is within the drupal directory and format appropriately.
133 *
134 * @param $url (reference)
135 *
136 * @return bool
137 * TRUE for internal paths, FALSE for external. The drupal_add_js fn is able to add js more
138 * efficiently if it is known to be in the drupal site
139 */
140 public function formatResourceUrl(&$url) {
141 $internal = FALSE;
142 $base = CRM_Core_Config::singleton()->resourceBase;
143 global $base_url;
144 // Handle absolute urls
145 // compares $url (which is some unknown/untrusted value from a third-party dev) to the CMS's base url (which is independent of civi's url)
146 // to see if the url is within our drupal dir, if it is we are able to treated it as an internal url
147 if (strpos($url, $base_url) === 0) {
148 $file = trim(str_replace($base_url, '', $url), '/');
149 // CRM-18130: Custom CSS URL not working if aliased or rewritten
150 if (file_exists(DRUPAL_ROOT . $file)) {
151 $url = $file;
152 $internal = TRUE;
153 }
154 }
155 // Handle relative urls that are within the CiviCRM module directory
156 elseif (strpos($url, $base) === 0) {
157 $internal = TRUE;
158 $url = $this->appendCoreDirectoryToResourceBase(dirname(drupal_get_path('module', 'civicrm')) . '/') . trim(substr($url, strlen($base)), '/');
159 }
160 // Strip query string
161 $q = strpos($url, '?');
162 if ($q && $internal) {
163 $url = substr($url, 0, $q);
164 }
165 return $internal;
166 }
167
168 /**
169 * In instance where civicrm folder has a drupal folder & a civicrm core folder @ the same level append the
170 * civicrm folder name to the url
171 * See CRM-13737 for discussion of how this allows implementers to alter the folder structure
172 * @todo - this only provides a limited amount of flexiblity - it still expects a 'civicrm' folder with a 'drupal' folder
173 * and is only flexible as to the name of the civicrm folder.
174 *
175 * @param string $url
176 * Potential resource url based on standard folder assumptions.
177 * @return string
178 * with civicrm-core directory appended if not standard civi dir
179 */
180 public function appendCoreDirectoryToResourceBase($url) {
181 global $civicrm_root;
182 $lastDirectory = basename($civicrm_root);
183 if ($lastDirectory != 'civicrm') {
184 return $url .= $lastDirectory . '/';
185 }
186 return $url;
187 }
188
189 /**
190 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
191 *
192 * @inheritDoc
193 */
194 public function url(
195 $path = NULL,
196 $query = NULL,
197 $absolute = FALSE,
198 $fragment = NULL,
199 $frontend = FALSE,
200 $forceBackend = FALSE
201 ) {
202 $config = CRM_Core_Config::singleton();
203 $script = 'index.php';
204
205 $path = CRM_Utils_String::stripPathChars($path);
206
207 if (isset($fragment)) {
208 $fragment = '#' . $fragment;
209 }
210
211 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
212
213 $separator = '&';
214
215 if (!$config->cleanURL) {
216 if (isset($path)) {
217 if (isset($query)) {
218 return $base . $script . '?q=' . $path . $separator . $query . $fragment;
219 }
220 else {
221 return $base . $script . '?q=' . $path . $fragment;
222 }
223 }
224 else {
225 if (isset($query)) {
226 return $base . $script . '?' . $query . $fragment;
227 }
228 else {
229 return $base . $fragment;
230 }
231 }
232 }
233 else {
234 if (isset($path)) {
235 if (isset($query)) {
236 return $base . $path . '?' . $query . $fragment;
237 }
238 else {
239 return $base . $path . $fragment;
240 }
241 }
242 else {
243 if (isset($query)) {
244 return $base . $script . '?' . $query . $fragment;
245 }
246 else {
247 return $base . $fragment;
248 }
249 }
250 }
251 }
252
253 /**
254 * @inheritDoc
255 */
256 public function getUserIDFromUserObject($user) {
257 return !empty($user->uid) ? $user->uid : NULL;
258 }
259
260 /**
261 * @inheritDoc
262 */
263 public function setMessage($message) {
264 drupal_set_message($message);
265 }
266
267 /**
268 * @inheritDoc
269 */
270 public function getUniqueIdentifierFromUserObject($user) {
271 return empty($user->mail) ? NULL : $user->mail;
272 }
273
274 /**
275 * @inheritDoc
276 */
277 public function getLoggedInUniqueIdentifier() {
278 global $user;
279 return $this->getUniqueIdentifierFromUserObject($user);
280 }
281
282 /**
283 * @inheritDoc
284 */
285 public function permissionDenied() {
286 drupal_access_denied();
287 }
288
289 /**
290 * @inheritDoc
291 */
292 public function getUserRecordUrl($contactID) {
293 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
294 if (CRM_Core_Session::singleton()
295 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array(
296 'cms:administer users',
297 'cms:view user account',
298 ))
299 ) {
300 return $this->url('user/' . $uid);
301 };
302 }
303
304 /**
305 * @inheritDoc
306 */
307 public function checkPermissionAddUser() {
308 return CRM_Core_Permission::check('administer users');
309 }
310
311 /**
312 * @inheritDoc
313 */
314 public function logger($message) {
315 if (CRM_Core_Config::singleton()->userFrameworkLogging && function_exists('watchdog')) {
316 watchdog('civicrm', '%message', array('%message' => $message), NULL, WATCHDOG_DEBUG);
317 }
318 }
319
320 /**
321 * @inheritDoc
322 */
323 public function clearResourceCache() {
324 _drupal_flush_css_js();
325 }
326
327 /**
328 * Append Drupal js to coreResourcesList.
329 *
330 * @param array $list
331 */
332 public function appendCoreResources(&$list) {
333 $list[] = 'js/crm.drupal.js';
334 }
335
336 /**
337 * @inheritDoc
338 */
339 public function flush() {
340 drupal_flush_all_caches();
341 }
342
343 /**
344 * @inheritDoc
345 */
346 public function getModules() {
347 $result = array();
348 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
349 foreach ($q as $row) {
350 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
351 }
352 return $result;
353 }
354
355 /**
356 * Find any users/roles/security-principals with the given permission
357 * and replace it with one or more permissions.
358 *
359 * @param string $oldPerm
360 * @param array $newPerms
361 * Array, strings.
362 *
363 * @return void
364 */
365 public function replacePermission($oldPerm, $newPerms) {
366 $roles = user_roles(FALSE, $oldPerm);
367 if (!empty($roles)) {
368 foreach (array_keys($roles) as $rid) {
369 user_role_revoke_permissions($rid, array($oldPerm));
370 user_role_grant_permissions($rid, $newPerms);
371 }
372 }
373 }
374
375 /**
376 * @inheritDoc
377 */
378 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
379 if (empty($url)) {
380 return $url;
381 }
382
383 //CRM-7803 -from d7 onward.
384 $config = CRM_Core_Config::singleton();
385 if (function_exists('variable_get') &&
386 module_exists('locale') &&
387 function_exists('language_negotiation_get')
388 ) {
389 global $language;
390
391 //does user configuration allow language
392 //support from the URL (Path prefix or domain)
393 if (language_negotiation_get('language') == 'locale-url') {
394 $urlType = variable_get('locale_language_negotiation_url_part');
395
396 //url prefix
397 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
398 if (isset($language->prefix) && $language->prefix) {
399 if ($addLanguagePart) {
400 $url .= $language->prefix . '/';
401 }
402 if ($removeLanguagePart) {
403 $url = str_replace("/{$language->prefix}/", '/', $url);
404 }
405 }
406 }
407 //domain
408 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
409 if (isset($language->domain) && $language->domain) {
410 if ($addLanguagePart) {
411 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $language->domain . base_path();
412 }
413 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
414 $url = str_replace('\\', '/', $url);
415 $parseUrl = parse_url($url);
416
417 //kinda hackish but not sure how to do it right
418 //hope http_build_url() will help at some point.
419 if (is_array($parseUrl) && !empty($parseUrl)) {
420 $urlParts = explode('/', $url);
421 $hostKey = array_search($parseUrl['host'], $urlParts);
422 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
423 $urlParts[$hostKey] = $ufUrlParts['host'];
424 $url = implode('/', $urlParts);
425 }
426 }
427 }
428 }
429 }
430 }
431 return $url;
432 }
433
434 /**
435 * @inheritDoc
436 */
437 public function getVersion() {
438 return defined('VERSION') ? VERSION : 'Unknown';
439 }
440
441 /**
442 * @inheritDoc
443 */
444 public function updateCategories() {
445 // copied this from profile.module. Seems a bit inefficient, but i don't know a better way
446 cache_clear_all();
447 menu_rebuild();
448 }
449
450 /**
451 * @inheritDoc
452 */
453 public function getUFLocale() {
454 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
455 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
456 // sometimes for CLI based on order called, this might not be set and/or empty
457 global $language;
458
459 if (empty($language)) {
460 return NULL;
461 }
462
463 if ($language->language == 'zh-hans') {
464 return 'zh_CN';
465 }
466
467 if ($language->language == 'zh-hant') {
468 return 'zh_TW';
469 }
470
471 if (preg_match('/^.._..$/', $language->language)) {
472 return $language->language;
473 }
474
475 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
476 }
477
478 /**
479 * @inheritDoc
480 */
481 public function setUFLocale($civicrm_language) {
482 global $language;
483
484 $langcode = substr($civicrm_language, 0, 2);
485 $languages = language_list();
486
487 if (isset($languages[$langcode])) {
488 $language = $languages[$langcode];
489
490 // Config must be re-initialized to reset the base URL
491 // otherwise links will have the wrong language prefix/domain.
492 $config = CRM_Core_Config::singleton();
493 $config->free();
494
495 return TRUE;
496 }
497
498 return FALSE;
499 }
500
501 /**
502 * Perform any post login activities required by the UF -
503 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
504 * calls hook_user op 'login' and generates a new session.
505 *
506 * @param array $params
507 *
508 * FIXME: Document values accepted/required by $params
509 */
510 public function userLoginFinalize($params = array()) {
511 user_login_finalize($params);
512 }
513
514 /**
515 * @inheritDoc
516 */
517 public function getLoginDestination(&$form) {
518 $args = NULL;
519
520 $id = $form->get('id');
521 if ($id) {
522 $args .= "&id=$id";
523 }
524 else {
525 $gid = $form->get('gid');
526 if ($gid) {
527 $args .= "&gid=$gid";
528 }
529 else {
530 // Setup Personal Campaign Page link uses pageId
531 $pageId = $form->get('pageId');
532 if ($pageId) {
533 $component = $form->get('component');
534 $args .= "&pageId=$pageId&component=$component&action=add";
535 }
536 }
537 }
538
539 $destination = NULL;
540 if ($args) {
541 // append destination so user is returned to form they came from after login
542 $destination = CRM_Utils_System::currentPath() . '?reset=1' . $args;
543 }
544 return $destination;
545 }
546
547 /**
548 * Fixme: Why are we overriding the parent function? Seems inconsistent.
549 * This version supplies slightly different params to $this->url (not absolute and html encoded) but why?
550 *
551 * @param string $action
552 *
553 * @return string
554 */
555 public function postURL($action) {
556 if (!empty($action)) {
557 return $action;
558 }
559 return $this->url($_GET['q']);
560 }
561
562 /**
563 * Get an array of user details for a contact, containing at minimum the user ID & name.
564 *
565 * @param int $contactID
566 *
567 * @return array
568 * CMS user details including
569 * - id
570 * - name (ie the system user name.
571 */
572 public function getUser($contactID) {
573 $userDetails = parent::getUser($contactID);
574 $user = $this->getUserObject($userDetails['id']);
575 $userDetails['name'] = $user->name;
576 $userDetails['email'] = $user->mail;
577 return $userDetails;
578 }
579
580 /**
581 * Load the user object.
582 *
583 * Note this function still works in drupal 6, 7 & 8 but is deprecated in Drupal 8.
584 *
585 * @param $userID
586 *
587 * @return object
588 */
589 public function getUserObject($userID) {
590 return user_load($userID);
591 }
592
593 /**
594 * Determine if Drupal multi-site applies to the current request -- and,
595 * specifically, determine the name of the multisite folder.
596 *
597 * @param string $flagFile
598 * Check if $flagFile exists inside the site dir.
599 * @return null|string
600 * string, e.g. `bar.example.com` if using multisite.
601 * NULL if using the default site.
602 */
603 private function parseDrupalSiteName($flagFile = '') {
604 $phpSelf = array_key_exists('PHP_SELF', $_SERVER) ? $_SERVER['PHP_SELF'] : '';
605 $httpHost = array_key_exists('HTTP_HOST', $_SERVER) ? $_SERVER['HTTP_HOST'] : '';
606 if (empty($httpHost)) {
607 $httpHost = parse_url(CIVICRM_UF_BASEURL, PHP_URL_HOST);
608 if (parse_url(CIVICRM_UF_BASEURL, PHP_URL_PORT)) {
609 $httpHost .= ':' . parse_url(CIVICRM_UF_BASEURL, PHP_URL_PORT);
610 }
611 }
612
613 $confdir = $this->cmsRootPath() . '/sites';
614
615 if (file_exists($confdir . "/sites.php")) {
616 include $confdir . "/sites.php";
617 }
618 else {
619 $sites = array();
620 }
621
622 $uri = explode('/', $phpSelf);
623 $server = explode('.', implode('.', array_reverse(explode(':', rtrim($httpHost, '.')))));
624 for ($i = count($uri) - 1; $i > 0; $i--) {
625 for ($j = count($server); $j > 0; $j--) {
626 $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
627 if (file_exists("$confdir/$dir" . $flagFile)) {
628 \Civi::$statics[__CLASS__]['drupalSiteName'] = $dir;
629 return \Civi::$statics[__CLASS__]['drupalSiteName'];
630 }
631 // check for alias
632 if (isset($sites[$dir]) && file_exists("$confdir/{$sites[$dir]}" . $flagFile)) {
633 \Civi::$statics[__CLASS__]['drupalSiteName'] = $sites[$dir];
634 return \Civi::$statics[__CLASS__]['drupalSiteName'];
635 }
636 }
637 }
638 }
639
640 }