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