3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 getCiviSourceStorage() {
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');
73 $cmsUrl = CIVICRM_UF_BASEURL
;
74 if (CRM_Utils_System
::isSSL()) {
75 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
77 $civiRelPath = CRM_Utils_File
::relativize(realpath($civicrm_root), realpath($this->cmsRootPath()));
78 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
80 'url' => CRM_Utils_File
::addTrailingSlash($civiUrl, '/'),
81 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
88 public function getDefaultFileStorage() {
89 $config = CRM_Core_Config
::singleton();
90 $baseURL = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
92 $siteName = $this->parseDrupalSiteName('/files/civicrm');
94 $filesURL = $baseURL . "sites/$siteName/files/civicrm/";
97 $filesURL = $baseURL . "sites/default/files/civicrm/";
102 'path' => CRM_Utils_File
::baseFilePath(),
109 public function getDefaultSiteSettings($dir) {
110 $config = CRM_Core_Config
::singleton();
111 $siteName = $siteRoot = NULL;
114 '|/sites/([\w\.\-\_]+)/|',
115 $config->templateCompileDir
,
118 $siteName = $matches[1];
120 $siteName = "/sites/$siteName/";
121 $siteNamePos = strpos($dir, $siteName);
122 if ($siteNamePos !== FALSE) {
123 $siteRoot = substr($dir, 0, $siteNamePos);
127 $url = $config->userFrameworkBaseURL
;
128 return array($url, $siteName, $siteRoot);
132 * Check if a resource url is within the drupal directory and format appropriately.
134 * @param $url (reference)
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
140 public function formatResourceUrl(&$url) {
142 $base = CRM_Core_Config
::singleton()->resourceBase
;
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)) {
155 // Handle relative urls that are within the CiviCRM module directory
156 elseif (strpos($url, $base) === 0) {
158 $url = $this->appendCoreDirectoryToResourceBase(dirname(drupal_get_path('module', 'civicrm')) . '/') . trim(substr($url, strlen($base)), '/');
160 // Strip query string
161 $q = strpos($url, '?');
162 if ($q && $internal) {
163 $url = substr($url, 0, $q);
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.
176 * Potential resource url based on standard folder assumptions.
178 * with civicrm-core directory appended if not standard civi dir
180 public function appendCoreDirectoryToResourceBase($url) {
181 global $civicrm_root;
182 $lastDirectory = basename($civicrm_root);
183 if ($lastDirectory != 'civicrm') {
184 return $url .= $lastDirectory . '/';
190 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
200 $forceBackend = FALSE
202 $config = CRM_Core_Config
::singleton();
203 $script = 'index.php';
205 $path = CRM_Utils_String
::stripPathChars($path);
207 if (isset($fragment)) {
208 $fragment = '#' . $fragment;
211 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
215 if (!$config->cleanURL
) {
218 return $base . $script . '?q=' . $path . $separator . $query . $fragment;
221 return $base . $script . '?q=' . $path . $fragment;
226 return $base . $script . '?' . $query . $fragment;
229 return $base . $fragment;
236 return $base . $path . '?' . $query . $fragment;
239 return $base . $path . $fragment;
244 return $base . $script . '?' . $query . $fragment;
247 return $base . $fragment;
256 public function getUserIDFromUserObject($user) {
257 return !empty($user->uid
) ?
$user->uid
: NULL;
263 public function setMessage($message) {
264 drupal_set_message($message);
270 public function getUniqueIdentifierFromUserObject($user) {
271 return empty($user->mail
) ?
NULL : $user->mail
;
277 public function getLoggedInUniqueIdentifier() {
279 return $this->getUniqueIdentifierFromUserObject($user);
285 public function permissionDenied() {
286 drupal_access_denied();
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',
300 return $this->url('user/' . $uid);
307 public function checkPermissionAddUser() {
308 return CRM_Core_Permission
::check('administer users');
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
);
323 public function clearResourceCache() {
324 _drupal_flush_css_js();
328 * Append Drupal js to coreResourcesList.
332 public function appendCoreResources(&$list) {
333 $list[] = 'js/crm.drupal.js';
339 public function flush() {
340 drupal_flush_all_caches();
346 public function getModules() {
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);
356 * Find any users/roles/security-principals with the given permission
357 * and replace it with one or more permissions.
359 * @param string $oldPerm
360 * @param array $newPerms
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);
378 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
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')
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');
397 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
398 if (isset($language->prefix
) && $language->prefix
) {
399 if ($addLanguagePart) {
400 $url .= $language->prefix
. '/';
402 if ($removeLanguagePart) {
403 $url = str_replace("/{$language->prefix}/", '/', $url);
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();
413 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
414 $url = str_replace('\\', '/', $url);
415 $parseUrl = parse_url($url);
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);
437 public function getVersion() {
438 return defined('VERSION') ? VERSION
: 'Unknown';
444 public function updateCategories() {
445 // copied this from profile.module. Seems a bit inefficient, but i don't know a better way
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
459 if (empty($language)) {
463 if ($language->language
== 'zh-hans') {
467 if ($language->language
== 'zh-hant') {
471 if (preg_match('/^.._..$/', $language->language
)) {
472 return $language->language
;
475 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
481 public function setUFLocale($civicrm_language) {
484 $langcode = substr($civicrm_language, 0, 2);
485 $languages = language_list();
487 if (isset($languages[$langcode])) {
488 $language = $languages[$langcode];
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();
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.
506 * @param array $params
508 * FIXME: Document values accepted/required by $params
510 public function userLoginFinalize($params = array()) {
511 user_login_finalize($params);
517 public function getLoginDestination(&$form) {
520 $id = $form->get('id');
525 $gid = $form->get('gid');
527 $args .= "&gid=$gid";
530 // Setup Personal Campaign Page link uses pageId
531 $pageId = $form->get('pageId');
533 $component = $form->get('component');
534 $args .= "&pageId=$pageId&component=$component&action=add";
541 // append destination so user is returned to form they came from after login
542 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
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?
551 * @param string $action
555 public function postURL($action) {
556 if (!empty($action)) {
559 return $this->url($_GET['q']);
563 * Get an array of user details for a contact, containing at minimum the user ID & name.
565 * @param int $contactID
568 * CMS user details including
570 * - name (ie the system user name.
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
;
581 * Load the user object.
583 * Note this function still works in drupal 6, 7 & 8 but is deprecated in Drupal 8.
589 public function getUserObject($userID) {
590 return user_load($userID);
594 * Determine if Drupal multi-site applies to the current request -- and,
595 * specifically, determine the name of the multisite folder.
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.
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
);
613 $confdir = $this->cmsRootPath() . '/sites';
615 if (file_exists($confdir . "/sites.php")) {
616 include $confdir . "/sites.php";
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'];
632 if (isset($sites[$dir]) && file_exists("$confdir/{$sites[$dir]}" . $flagFile)) {
633 \Civi
::$statics[__CLASS__
]['drupalSiteName'] = $sites[$dir];
634 return \Civi
::$statics[__CLASS__
]['drupalSiteName'];