3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
37 * Drupal specific stuff goes here
39 abstract class CRM_Utils_System_DrupalBase
extends CRM_Utils_System_Base
{
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
46 var $supports_UF_Logging = TRUE;
50 public function __construct() {
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
57 $this->is_drupal
= TRUE;
58 $this->supports_form_extensions
= TRUE;
64 public function getDefaultFileStorage() {
65 $config = CRM_Core_Config
::singleton();
66 $baseURL = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
68 $siteName = $this->parseDrupalSiteNameFromRequest('/files/civicrm');
70 $filesURL = $baseURL . "sites/$siteName/files/civicrm/";
73 $filesURL = $baseURL . "sites/default/files/civicrm/";
78 'path' => CRM_Utils_File
::baseFilePath(),
85 public function getDefaultSiteSettings($dir) {
86 $config = CRM_Core_Config
::singleton();
87 $siteName = $siteRoot = NULL;
90 '|/sites/([\w\.\-\_]+)/|',
91 $config->templateCompileDir
,
94 $siteName = $matches[1];
96 $siteName = "/sites/$siteName/";
97 $siteNamePos = strpos($dir, $siteName);
98 if ($siteNamePos !== FALSE) {
99 $siteRoot = substr($dir, 0, $siteNamePos);
103 $url = $config->userFrameworkBaseURL
;
104 return array($url, $siteName, $siteRoot);
108 * Check if a resource url is within the drupal directory and format appropriately.
110 * @param $url (reference)
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
116 public function formatResourceUrl(&$url) {
118 $base = CRM_Core_Config
::singleton()->resourceBase
;
120 // Strip query string
121 $q = strpos($url, '?');
122 $url_path = $q ?
substr($url, 0, $q) : $url;
123 // Handle absolute urls
124 // 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)
125 // to see if the url is within our drupal dir, if it is we are able to treated it as an internal url
126 if (strpos($url_path, $base_url) === 0) {
127 $file = trim(str_replace($base_url, '', $url_path), '/');
128 // CRM-18130: Custom CSS URL not working if aliased or rewritten
129 if (file_exists(DRUPAL_ROOT
. '/' . $file)) {
134 // Handle relative urls that are within the CiviCRM module directory
135 elseif (strpos($url_path, $base) === 0) {
137 $url = $this->appendCoreDirectoryToResourceBase(dirname(drupal_get_path('module', 'civicrm')) . '/') . trim(substr($url_path, strlen($base)), '/');
143 * In instance where civicrm folder has a drupal folder & a civicrm core folder @ the same level append the
144 * civicrm folder name to the url
145 * See CRM-13737 for discussion of how this allows implementers to alter the folder structure
146 * @todo - this only provides a limited amount of flexiblity - it still expects a 'civicrm' folder with a 'drupal' folder
147 * and is only flexible as to the name of the civicrm folder.
150 * Potential resource url based on standard folder assumptions.
152 * with civicrm-core directory appended if not standard civi dir
154 public function appendCoreDirectoryToResourceBase($url) {
155 global $civicrm_root;
156 $lastDirectory = basename($civicrm_root);
157 if ($lastDirectory != 'civicrm') {
158 return $url .= $lastDirectory . '/';
164 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
174 $forceBackend = FALSE
176 $config = CRM_Core_Config
::singleton();
177 $script = 'index.php';
179 $path = CRM_Utils_String
::stripPathChars($path);
181 if (isset($fragment)) {
182 $fragment = '#' . $fragment;
185 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
189 if (!$config->cleanURL
) {
192 return $base . $script . '?q=' . $path . $separator . $query . $fragment;
195 return $base . $script . '?q=' . $path . $fragment;
200 return $base . $script . '?' . $query . $fragment;
203 return $base . $fragment;
210 return $base . $path . '?' . $query . $fragment;
213 return $base . $path . $fragment;
218 return $base . $script . '?' . $query . $fragment;
221 return $base . $fragment;
230 public function getUserIDFromUserObject($user) {
231 return !empty($user->uid
) ?
$user->uid
: NULL;
237 public function setMessage($message) {
238 drupal_set_message($message);
244 public function getUniqueIdentifierFromUserObject($user) {
245 return empty($user->mail
) ?
NULL : $user->mail
;
251 public function getLoggedInUniqueIdentifier() {
253 return $this->getUniqueIdentifierFromUserObject($user);
259 public function permissionDenied() {
260 drupal_access_denied();
266 public function getUserRecordUrl($contactID) {
267 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
268 if (CRM_Core_Session
::singleton()
269 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array(
270 'cms:administer users',
271 'cms:view user account',
274 return $this->url('user/' . $uid);
281 public function checkPermissionAddUser() {
282 return CRM_Core_Permission
::check('administer users');
288 public function logger($message) {
289 if (CRM_Core_Config
::singleton()->userFrameworkLogging
&& function_exists('watchdog')) {
290 watchdog('civicrm', '%message', array('%message' => $message), NULL, WATCHDOG_DEBUG
);
297 public function clearResourceCache() {
298 _drupal_flush_css_js();
304 public function flush() {
305 drupal_flush_all_caches();
311 public function getModules() {
313 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
314 foreach ($q as $row) {
315 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
321 * Find any users/roles/security-principals with the given permission
322 * and replace it with one or more permissions.
324 * @param string $oldPerm
325 * @param array $newPerms
330 public function replacePermission($oldPerm, $newPerms) {
331 $roles = user_roles(FALSE, $oldPerm);
332 if (!empty($roles)) {
333 foreach (array_keys($roles) as $rid) {
334 user_role_revoke_permissions($rid, array($oldPerm));
335 user_role_grant_permissions($rid, $newPerms);
343 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
348 //CRM-7803 -from d7 onward.
349 $config = CRM_Core_Config
::singleton();
350 if (function_exists('variable_get') &&
351 module_exists('locale') &&
352 function_exists('language_negotiation_get')
356 //does user configuration allow language
357 //support from the URL (Path prefix or domain)
358 if (language_negotiation_get('language') == 'locale-url') {
359 $urlType = variable_get('locale_language_negotiation_url_part');
362 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
363 if (isset($language->prefix
) && $language->prefix
) {
364 if ($addLanguagePart) {
365 $url .= $language->prefix
. '/';
367 if ($removeLanguagePart) {
368 $url = str_replace("/{$language->prefix}/", '/', $url);
373 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
374 if (isset($language->domain
) && $language->domain
) {
375 if ($addLanguagePart) {
376 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $language->domain
. base_path();
378 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
379 $url = str_replace('\\', '/', $url);
380 $parseUrl = parse_url($url);
382 //kinda hackish but not sure how to do it right
383 //hope http_build_url() will help at some point.
384 if (is_array($parseUrl) && !empty($parseUrl)) {
385 $urlParts = explode('/', $url);
386 $hostKey = array_search($parseUrl['host'], $urlParts);
387 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
388 $urlParts[$hostKey] = $ufUrlParts['host'];
389 $url = implode('/', $urlParts);
402 public function getVersion() {
403 return defined('VERSION') ? VERSION
: 'Unknown';
409 public function isUserRegistrationPermitted() {
410 if (!variable_get('user_register', TRUE)) {
419 public function isPasswordUserGenerated() {
420 if (variable_get('user_email_verification', TRUE)) {
429 public function updateCategories() {
430 // copied this from profile.module. Seems a bit inefficient, but i don't know a better way
438 public function getUFLocale() {
439 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
440 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
441 // sometimes for CLI based on order called, this might not be set and/or empty
442 $language = $this->getCurrentLanguage();
444 if (empty($language)) {
448 if ($language == 'zh-hans') {
452 if ($language == 'zh-hant') {
456 if (preg_match('/^.._..$/', $language)) {
460 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
466 public function setUFLocale($civicrm_language) {
469 $langcode = substr($civicrm_language, 0, 2);
470 $languages = language_list();
472 if (isset($languages[$langcode])) {
473 $language = $languages[$langcode];
475 // Config must be re-initialized to reset the base URL
476 // otherwise links will have the wrong language prefix/domain.
477 $config = CRM_Core_Config
::singleton();
487 * Perform any post login activities required by the UF -
488 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
489 * calls hook_user op 'login' and generates a new session.
491 * @param array $params
493 * FIXME: Document values accepted/required by $params
495 public function userLoginFinalize($params = array()) {
496 user_login_finalize($params);
502 public function getLoginDestination(&$form) {
505 $id = $form->get('id');
510 $gid = $form->get('gid');
512 $args .= "&gid=$gid";
515 // Setup Personal Campaign Page link uses pageId
516 $pageId = $form->get('pageId');
518 $component = $form->get('component');
519 $args .= "&pageId=$pageId&component=$component&action=add";
526 // append destination so user is returned to form they came from after login
527 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
533 * Fixme: Why are we overriding the parent function? Seems inconsistent.
534 * This version supplies slightly different params to $this->url (not absolute and html encoded) but why?
536 * @param string $action
540 public function postURL($action) {
541 if (!empty($action)) {
544 return $this->url($_GET['q']);
548 * Get an array of user details for a contact, containing at minimum the user ID & name.
550 * @param int $contactID
553 * CMS user details including
555 * - name (ie the system user name.
557 public function getUser($contactID) {
558 $userDetails = parent
::getUser($contactID);
559 $user = $this->getUserObject($userDetails['id']);
560 $userDetails['name'] = $user->name
;
561 $userDetails['email'] = $user->mail
;
566 * Load the user object.
568 * Note this function still works in drupal 6, 7 & 8 but is deprecated in Drupal 8.
574 public function getUserObject($userID) {
575 return user_load($userID);
579 * Parse the name of the drupal site.
581 * @param string $civicrm_root
583 * @return null|string
586 public function parseDrupalSiteNameFromRoot($civicrm_root) {
588 if (strpos($civicrm_root,
589 DIRECTORY_SEPARATOR
. 'sites' . DIRECTORY_SEPARATOR
. 'all' . DIRECTORY_SEPARATOR
. 'modules'
592 $startPos = strpos($civicrm_root,
593 DIRECTORY_SEPARATOR
. 'sites' . DIRECTORY_SEPARATOR
595 $endPos = strpos($civicrm_root,
596 DIRECTORY_SEPARATOR
. 'modules' . DIRECTORY_SEPARATOR
598 if ($startPos && $endPos) {
599 // if component is in sites/SITENAME/modules
600 $siteName = substr($civicrm_root,
602 $endPos - $startPos - 7
610 * Determine if Drupal multi-site applies to the current request -- and,
611 * specifically, determine the name of the multisite folder.
613 * @param string $flagFile
614 * Check if $flagFile exists inside the site dir.
615 * @return null|string
616 * string, e.g. `bar.example.com` if using multisite.
617 * NULL if using the default site.
619 private function parseDrupalSiteNameFromRequest($flagFile = '') {
620 $phpSelf = array_key_exists('PHP_SELF', $_SERVER) ?
$_SERVER['PHP_SELF'] : '';
621 $httpHost = array_key_exists('HTTP_HOST', $_SERVER) ?
$_SERVER['HTTP_HOST'] : '';
622 if (empty($httpHost)) {
623 $httpHost = parse_url(CIVICRM_UF_BASEURL
, PHP_URL_HOST
);
624 if (parse_url(CIVICRM_UF_BASEURL
, PHP_URL_PORT
)) {
625 $httpHost .= ':' . parse_url(CIVICRM_UF_BASEURL
, PHP_URL_PORT
);
629 $confdir = $this->cmsRootPath() . '/sites';
631 if (file_exists($confdir . "/sites.php")) {
632 include $confdir . "/sites.php";
638 $uri = explode('/', $phpSelf);
639 $server = explode('.', implode('.', array_reverse(explode(':', rtrim($httpHost, '.')))));
640 for ($i = count($uri) - 1; $i > 0; $i--) {
641 for ($j = count($server); $j > 0; $j--) {
642 $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
643 if (file_exists("$confdir/$dir" . $flagFile)) {
644 \Civi
::$statics[__CLASS__
]['drupalSiteName'] = $dir;
645 return \Civi
::$statics[__CLASS__
]['drupalSiteName'];
648 if (isset($sites[$dir]) && file_exists("$confdir/{$sites[$dir]}" . $flagFile)) {
649 \Civi
::$statics[__CLASS__
]['drupalSiteName'] = $sites[$dir];
650 return \Civi
::$statics[__CLASS__
]['drupalSiteName'];
657 * Function to return current language of Drupal
661 public function getCurrentLanguage() {
663 return (!empty($language->language
)) ?
$language->language
: $language;