3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 // 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)) {
131 // Handle relative urls that are within the CiviCRM module directory
132 elseif (strpos($url, $base) === 0) {
134 $url = $this->appendCoreDirectoryToResourceBase(dirname(drupal_get_path('module', 'civicrm')) . '/') . trim(substr($url, strlen($base)), '/');
136 // Strip query string
137 $q = strpos($url, '?');
138 if ($q && $internal) {
139 $url = substr($url, 0, $q);
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.
152 * Potential resource url based on standard folder assumptions.
154 * with civicrm-core directory appended if not standard civi dir
156 public function appendCoreDirectoryToResourceBase($url) {
157 global $civicrm_root;
158 $lastDirectory = basename($civicrm_root);
159 if ($lastDirectory != 'civicrm') {
160 return $url .= $lastDirectory . '/';
166 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
176 $forceBackend = FALSE
178 $config = CRM_Core_Config
::singleton();
179 $script = 'index.php';
181 $path = CRM_Utils_String
::stripPathChars($path);
183 if (isset($fragment)) {
184 $fragment = '#' . $fragment;
187 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
191 if (!$config->cleanURL
) {
194 return $base . $script . '?q=' . $path . $separator . $query . $fragment;
197 return $base . $script . '?q=' . $path . $fragment;
202 return $base . $script . '?' . $query . $fragment;
205 return $base . $fragment;
212 return $base . $path . '?' . $query . $fragment;
215 return $base . $path . $fragment;
220 return $base . $script . '?' . $query . $fragment;
223 return $base . $fragment;
232 public function getUserIDFromUserObject($user) {
233 return !empty($user->uid
) ?
$user->uid
: NULL;
239 public function setMessage($message) {
240 drupal_set_message($message);
246 public function getUniqueIdentifierFromUserObject($user) {
247 return empty($user->mail
) ?
NULL : $user->mail
;
253 public function getLoggedInUniqueIdentifier() {
255 return $this->getUniqueIdentifierFromUserObject($user);
261 public function permissionDenied() {
262 drupal_access_denied();
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',
276 return $this->url('user/' . $uid);
283 public function checkPermissionAddUser() {
284 return CRM_Core_Permission
::check('administer users');
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
);
299 public function clearResourceCache() {
300 _drupal_flush_css_js();
306 public function flush() {
307 drupal_flush_all_caches();
313 public function getModules() {
315 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
316 foreach ($q as $row) {
317 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
323 * Find any users/roles/security-principals with the given permission
324 * and replace it with one or more permissions.
326 * @param string $oldPerm
327 * @param array $newPerms
332 public function replacePermission($oldPerm, $newPerms) {
333 $roles = user_roles(FALSE, $oldPerm);
334 if (!empty($roles)) {
335 foreach (array_keys($roles) as $rid) {
336 user_role_revoke_permissions($rid, array($oldPerm));
337 user_role_grant_permissions($rid, $newPerms);
345 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
350 //CRM-7803 -from d7 onward.
351 $config = CRM_Core_Config
::singleton();
352 if (function_exists('variable_get') &&
353 module_exists('locale') &&
354 function_exists('language_negotiation_get')
358 //does user configuration allow language
359 //support from the URL (Path prefix or domain)
360 if (language_negotiation_get('language') == 'locale-url') {
361 $urlType = variable_get('locale_language_negotiation_url_part');
364 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
365 if (isset($language->prefix
) && $language->prefix
) {
366 if ($addLanguagePart) {
367 $url .= $language->prefix
. '/';
369 if ($removeLanguagePart) {
370 $url = str_replace("/{$language->prefix}/", '/', $url);
375 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
376 if (isset($language->domain
) && $language->domain
) {
377 if ($addLanguagePart) {
378 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $language->domain
. base_path();
380 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
381 $url = str_replace('\\', '/', $url);
382 $parseUrl = parse_url($url);
384 //kinda hackish but not sure how to do it right
385 //hope http_build_url() will help at some point.
386 if (is_array($parseUrl) && !empty($parseUrl)) {
387 $urlParts = explode('/', $url);
388 $hostKey = array_search($parseUrl['host'], $urlParts);
389 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
390 $urlParts[$hostKey] = $ufUrlParts['host'];
391 $url = implode('/', $urlParts);
404 public function getVersion() {
405 return defined('VERSION') ? VERSION
: 'Unknown';
411 public function isUserRegistrationPermitted() {
412 if (!variable_get('user_register', TRUE)) {
421 public function isPasswordUserGenerated() {
422 if (variable_get('user_email_verification', TRUE)) {
431 public function updateCategories() {
432 // copied this from profile.module. Seems a bit inefficient, but i don't know a better way
440 public function getUFLocale() {
441 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
442 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
443 // sometimes for CLI based on order called, this might not be set and/or empty
444 $language = $this->getCurrentLanguage();
446 if (empty($language)) {
450 if ($language == 'zh-hans') {
454 if ($language == 'zh-hant') {
458 if (preg_match('/^.._..$/', $language)) {
462 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
468 public function setUFLocale($civicrm_language) {
471 $langcode = substr($civicrm_language, 0, 2);
472 $languages = language_list();
474 if (isset($languages[$langcode])) {
475 $language = $languages[$langcode];
477 // Config must be re-initialized to reset the base URL
478 // otherwise links will have the wrong language prefix/domain.
479 $config = CRM_Core_Config
::singleton();
489 * Perform any post login activities required by the UF -
490 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
491 * calls hook_user op 'login' and generates a new session.
493 * @param array $params
495 * FIXME: Document values accepted/required by $params
497 public function userLoginFinalize($params = array()) {
498 user_login_finalize($params);
504 public function getLoginDestination(&$form) {
507 $id = $form->get('id');
512 $gid = $form->get('gid');
514 $args .= "&gid=$gid";
517 // Setup Personal Campaign Page link uses pageId
518 $pageId = $form->get('pageId');
520 $component = $form->get('component');
521 $args .= "&pageId=$pageId&component=$component&action=add";
528 // append destination so user is returned to form they came from after login
529 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
535 * Fixme: Why are we overriding the parent function? Seems inconsistent.
536 * This version supplies slightly different params to $this->url (not absolute and html encoded) but why?
538 * @param string $action
542 public function postURL($action) {
543 if (!empty($action)) {
546 return $this->url($_GET['q']);
550 * Get an array of user details for a contact, containing at minimum the user ID & name.
552 * @param int $contactID
555 * CMS user details including
557 * - name (ie the system user name.
559 public function getUser($contactID) {
560 $userDetails = parent
::getUser($contactID);
561 $user = $this->getUserObject($userDetails['id']);
562 $userDetails['name'] = $user->name
;
563 $userDetails['email'] = $user->mail
;
568 * Load the user object.
570 * Note this function still works in drupal 6, 7 & 8 but is deprecated in Drupal 8.
576 public function getUserObject($userID) {
577 return user_load($userID);
581 * Parse the name of the drupal site.
583 * @param string $civicrm_root
585 * @return null|string
588 public function parseDrupalSiteNameFromRoot($civicrm_root) {
590 if (strpos($civicrm_root,
591 DIRECTORY_SEPARATOR
. 'sites' . DIRECTORY_SEPARATOR
. 'all' . DIRECTORY_SEPARATOR
. 'modules'
594 $startPos = strpos($civicrm_root,
595 DIRECTORY_SEPARATOR
. 'sites' . DIRECTORY_SEPARATOR
597 $endPos = strpos($civicrm_root,
598 DIRECTORY_SEPARATOR
. 'modules' . DIRECTORY_SEPARATOR
600 if ($startPos && $endPos) {
601 // if component is in sites/SITENAME/modules
602 $siteName = substr($civicrm_root,
604 $endPos - $startPos - 7
612 * Determine if Drupal multi-site applies to the current request -- and,
613 * specifically, determine the name of the multisite folder.
615 * @param string $flagFile
616 * Check if $flagFile exists inside the site dir.
617 * @return null|string
618 * string, e.g. `bar.example.com` if using multisite.
619 * NULL if using the default site.
621 private function parseDrupalSiteNameFromRequest($flagFile = '') {
622 $phpSelf = array_key_exists('PHP_SELF', $_SERVER) ?
$_SERVER['PHP_SELF'] : '';
623 $httpHost = array_key_exists('HTTP_HOST', $_SERVER) ?
$_SERVER['HTTP_HOST'] : '';
624 if (empty($httpHost)) {
625 $httpHost = parse_url(CIVICRM_UF_BASEURL
, PHP_URL_HOST
);
626 if (parse_url(CIVICRM_UF_BASEURL
, PHP_URL_PORT
)) {
627 $httpHost .= ':' . parse_url(CIVICRM_UF_BASEURL
, PHP_URL_PORT
);
631 $confdir = $this->cmsRootPath() . '/sites';
633 if (file_exists($confdir . "/sites.php")) {
634 include $confdir . "/sites.php";
640 $uri = explode('/', $phpSelf);
641 $server = explode('.', implode('.', array_reverse(explode(':', rtrim($httpHost, '.')))));
642 for ($i = count($uri) - 1; $i > 0; $i--) {
643 for ($j = count($server); $j > 0; $j--) {
644 $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
645 if (file_exists("$confdir/$dir" . $flagFile)) {
646 \Civi
::$statics[__CLASS__
]['drupalSiteName'] = $dir;
647 return \Civi
::$statics[__CLASS__
]['drupalSiteName'];
650 if (isset($sites[$dir]) && file_exists("$confdir/{$sites[$dir]}" . $flagFile)) {
651 \Civi
::$statics[__CLASS__
]['drupalSiteName'] = $sites[$dir];
652 return \Civi
::$statics[__CLASS__
]['drupalSiteName'];
659 * Function to return current language of Drupal
663 public function getCurrentLanguage() {
665 return (!empty($language->language
)) ?
$language->language
: $language;