3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Drupal specific stuff goes here.
21 class CRM_Utils_System_Drupal6
extends CRM_Utils_System_DrupalBase
{
26 * If we are using a theming system, invoke theme, else just print the content.
28 * @param string $content
29 * The content that will be themed.
31 * Are we displaying to the screen or bypassing theming?.
32 * @param bool $maintenance
33 * For maintenance mode.
36 * prints content on stdout
38 public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
39 // TODO: Simplify; this was copied verbatim from CiviCRM 3.4's multi-UF theming function, but that's more complex than necessary
40 if (function_exists('theme') && !$print) {
42 drupal_set_breadcrumb('');
43 drupal_maintenance_theme();
46 // Arg 3 for D6 theme() is "show_blocks". Previously, we passed
47 // through a badly named variable ("$args") which was almost always
48 // TRUE (except on fatal error screen). However, this feature is
49 // non-functional on D6 default themes, was purposefully removed from
50 // D7, has no analog in other our other CMS's, and clutters the code.
51 // Hard-wiring to TRUE should be OK.
52 $out = theme('page', $content, TRUE);
67 public function createUser(&$params, $mail) {
69 $form_state['values'] = [
70 'name' => $params['cms_name'],
71 'mail' => $params[$mail],
72 'op' => 'Create new account',
75 $admin = user_access('administer users');
76 if (!variable_get('user_email_verification', TRUE) ||
$admin) {
77 $form_state['values']['pass']['pass1'] = $params['cms_pass'];
78 $form_state['values']['pass']['pass2'] = $params['cms_pass'];
81 $config = CRM_Core_Config
::singleton();
83 // we also need to redirect b
84 $config->inCiviCRM
= TRUE;
86 $form = drupal_retrieve_form('user_register', $form_state);
87 $form['#post'] = $form_state['values'];
88 drupal_prepare_form('user_register', $form, $form_state);
90 // remove the captcha element from the form prior to processing
91 unset($form['captcha']);
93 drupal_process_form('user_register', $form, $form_state);
95 $config->inCiviCRM
= FALSE;
97 if (form_get_errors() ||
!isset($form_state['user'])) {
100 return $form_state['user']->uid
;
106 public function updateCMSName($ufID, $ufName) {
108 if (function_exists('user_load')) {
109 $user = user_load(['uid' => $ufID]);
110 if ($user->mail
!= $ufName) {
111 user_save($user, ['mail' => $ufName]);
112 $user = user_load(['uid' => $ufID]);
118 * Check if username and email exists in the drupal db.
120 * @param array $params
121 * Array of name and mail values.
122 * @param array $errors
124 * @param string $emailName
125 * Field label for the 'email'.
127 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
128 $config = CRM_Core_Config
::singleton();
130 $dao = new CRM_Core_DAO();
131 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
132 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
133 _user_edit_validate(NULL, $params);
134 $errors = form_get_errors();
136 if (!empty($errors['name'])) {
137 $errors['cms_name'] = $errors['name'];
139 if (!empty($errors['mail'])) {
140 $errors[$emailName] = $errors['mail'];
142 // also unset drupal messages to avoid twice display of errors
143 unset($_SESSION['messages']);
146 // Do the name check manually.
147 $nameError = user_validate_name($params['name']);
149 $errors['cms_name'] = $nameError;
152 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
156 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))
159 $result = db_query($sql);
160 $row = db_fetch_array($result);
168 $dbName = $row['name'] ??
NULL;
169 $dbEmail = $row['mail'] ??
NULL;
170 if (strtolower($dbName) == strtolower($name)) {
171 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
175 if (strtolower($dbEmail) == strtolower($email)) {
177 $errors[$emailName] = ts('You cannot create an email account for a contact with no email',
182 $errors[$emailName] = ts('This email %1 already has an account associated with it. Please select another email.',
193 public function setTitle($title, $pageTitle = NULL) {
197 if (arg(0) == 'civicrm') {
199 drupal_set_title($pageTitle);
206 public function appendBreadCrumb($breadCrumbs) {
207 $breadCrumb = drupal_get_breadcrumb();
209 if (is_array($breadCrumbs)) {
210 foreach ($breadCrumbs as $crumbs) {
211 if (stripos($crumbs['url'], 'id%%')) {
212 $args = ['cid', 'mid'];
213 foreach ($args as $a) {
214 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
218 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
222 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
225 drupal_set_breadcrumb($breadCrumb);
231 public function resetBreadCrumb() {
233 drupal_set_breadcrumb($bc);
237 * Append a string to the head of the html file.
239 * @param string $head
240 * The new string to be appended.
242 public function addHTMLHead($head) {
243 drupal_set_html_head($head);
249 * @param $url : string, absolute path to file
250 * @param string $region
251 * location within the document: 'html-header', 'page-header', 'page-footer'.
253 * Note: This function is not to be called directly
254 * @see CRM_Core_Region::render()
257 * TRUE if we support this operation in this CMS, FALSE otherwise
259 public function addStyleUrl($url, $region) {
260 if ($region != 'html-header' ||
!$this->formatResourceUrl($url)) {
263 drupal_add_css($url);
270 public function mapConfigToSSL() {
272 $base_url = str_replace('http://', 'https://', $base_url);
276 * Get the name of the table that stores the user details.
280 protected function getUsersTableName() {
281 $userFrameworkUsersTableName = Civi
::settings()->get('userFrameworkUsersTableName');
282 if (empty($userFrameworkUsersTableName)) {
283 $userFrameworkUsersTableName = 'users';
285 return $userFrameworkUsersTableName;
291 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
292 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
294 // probably if bootstrap is loaded this call
295 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
296 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
297 // safe in the unknown situation where authenticate might be called & it is important that
299 require_once 'DB.php';
301 $config = CRM_Core_Config
::singleton();
303 $ufDSN = CRM_Utils_SQL
::autoSwitchDSN($config->userFrameworkDSN
);
305 $dbDrupal = DB
::connect($ufDSN);
307 catch (Exception
$e) {
308 throw new CRM_Core_Exception("Cannot connect to drupal db via $ufDSN, " . $e->getMessage());
311 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
312 $dbpassword = md5($password);
313 $name = $dbDrupal->escapeSimple($strtolower($name));
314 $userFrameworkUsersTableName = $this->getUsersTableName();
315 $sql = 'SELECT u.* FROM ' . $userFrameworkUsersTableName . " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
316 $query = $dbDrupal->query($sql);
319 // need to change this to make sure we matched only one row
320 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC
)) {
321 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
322 $contactID = CRM_Core_BAO_UFMatch
::getContactId($row['uid']);
328 if ($loadCMSBootstrap) {
329 $bootStrapParams = [];
330 if ($name && $password) {
336 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
338 return [$contactID, $row['uid'], mt_rand()];
347 public function loadUser($username) {
349 $user = user_load(['name' => $username]);
350 if (empty($user->uid
)) {
355 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
357 // lets store contact id and user id in session
358 $session = CRM_Core_Session
::singleton();
359 $session->set('ufID', $uid);
360 $session->set('userID', $contact_id);
365 * Perform any post login activities required by the UF -
366 * e.g. for drupal : records a watchdog message about the new session,
367 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
369 * @param array $params
371 * FIXME: Document values accepted/required by $params
373 public function userLoginFinalize($params = []) {
374 user_authenticate_finalize($params);
378 * Determine the native ID of the CMS user.
380 * @param string $username
383 public function getUfId($username) {
384 $user = user_load(['name' => $username]);
385 if (empty($user->uid
)) {
394 public function logout() {
395 module_load_include('inc', 'user', 'user.pages');
396 return user_logout();
400 * Load drupal bootstrap.
402 * @param array $params
403 * Either uid, or name & pass.
404 * @param bool $loadUser
405 * Boolean Require CMS user load.
406 * @param bool $throwError
407 * If true, print error on failure and exit.
408 * @param bool|string $realPath path to script
412 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
413 //take the cms root path.
414 $cmsPath = $this->cmsRootPath($realPath);
416 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
418 echo '<br />Sorry, could not locate bootstrap.inc\n';
423 // load drupal bootstrap
425 define('DRUPAL_ROOT', $cmsPath);
427 // For drupal multi-site CRM-11313
428 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
429 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
430 if (!empty($matches[1])) {
431 $_SERVER['HTTP_HOST'] = $matches[1];
434 require_once 'includes/bootstrap.inc';
435 // @ to suppress notices eg 'DRUPALFOO already defined'.
436 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
438 // explicitly setting error reporting, since we cannot handle drupal related notices
440 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
442 echo '<br />Sorry, could not load drupal bootstrap.';
448 // seems like we've bootstrapped drupal
449 $config = CRM_Core_Config
::singleton();
451 // lets also fix the clean url setting
453 $config->cleanURL
= (int) variable_get('clean_url', '0');
455 // we need to call the config hook again, since we now know
456 // all the modules that are listening on it, does not apply
457 // to J! and WP as yet
459 CRM_Utils_Hook
::config($config);
465 // If $uid is passed in, authentication has been done already.
466 $uid = $params['uid'] ??
NULL;
468 //load user, we need to check drupal permissions.
469 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
470 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
473 $user = user_authenticate(['name' => $name, 'pass' => $pass]);
476 echo '<br />Sorry, unrecognized username or password.';
488 $account = user_load($uid);
489 if ($account && $account->uid
) {
496 echo '<br />Sorry, can not load CMS user account.';
500 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
501 // which means that define(CIVICRM_CLEANURL) was correctly set.
503 $config = CRM_Core_Config
::singleton();
504 $config->cleanURL
= (int) variable_get('clean_url', '0');
506 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
507 CRM_Utils_Hook
::config($config);
515 * @param string $scriptFilename
517 * @return null|string
519 public function cmsRootPath($scriptFilename = NULL) {
520 $cmsRoot = $valid = NULL;
522 if (!is_null($scriptFilename)) {
523 $path = $scriptFilename;
526 $path = $_SERVER['SCRIPT_FILENAME'];
529 if (function_exists('drush_get_context')) {
530 // drush anyway takes care of multisite install etc
531 return drush_get_context('DRUSH_DRUPAL_ROOT');
534 global $civicrm_paths;
535 if (!empty($civicrm_paths['cms.root']['path'])) {
536 return $civicrm_paths['cms.root']['path'];
540 $pathVars = explode('/',
541 str_replace('//', '/',
542 str_replace('\\', '/', $path)
546 //lets store first var,
547 //need to get back for windows.
548 $firstVar = array_shift($pathVars);
550 //lets remove sript name to reduce one iteration.
551 array_pop($pathVars);
553 //CRM-7429 --do check for upper most 'includes' dir,
554 //which would effectually work for multisite installation.
556 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
557 $cmsIncludePath = "$cmsRoot/includes";
558 // Stop if we found bootstrap.
559 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
563 //remove one directory level.
564 array_pop($pathVars);
565 } while (count($pathVars));
567 return ($valid) ?
$cmsRoot : NULL;
573 public function isUserLoggedIn() {
575 if (function_exists('user_is_logged_in')) {
576 $isloggedIn = user_is_logged_in();
585 public function getLoggedInUfID() {
587 if (function_exists('user_is_logged_in') &&
588 user_is_logged_in() &&
589 function_exists('user_uid_optional_to_arg')
591 $ufID = user_uid_optional_to_arg([]);
600 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
605 //up to d6 only, already we have code in place for d7
606 $config = CRM_Core_Config
::singleton();
607 if (function_exists('variable_get') &&
608 module_exists('locale')
613 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE
);
616 if (isset($language->prefix
) &&
619 LANGUAGE_NEGOTIATION_PATH
,
620 LANGUAGE_NEGOTIATION_PATH_DEFAULT
,
624 if ($addLanguagePart) {
625 $url .= $language->prefix
. '/';
627 if ($removeLanguagePart) {
628 $url = str_replace("/{$language->prefix}/", '/', $url);
631 if (isset($language->domain
) &&
633 $mode == LANGUAGE_NEGOTIATION_DOMAIN
636 if ($addLanguagePart) {
637 $url = CRM_Utils_File
::addTrailingSlash($language->domain
, '/');
639 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
640 $url = str_replace('\\', '/', $url);
641 $parseUrl = parse_url($url);
643 //kinda hackish but not sure how to do it right
644 //hope http_build_url() will help at some point.
645 if (is_array($parseUrl) && !empty($parseUrl)) {
646 $urlParts = explode('/', $url);
647 $hostKey = array_search($parseUrl['host'], $urlParts);
648 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
649 $urlParts[$hostKey] = $ufUrlParts['host'];
650 $url = implode('/', $urlParts);
660 * Find any users/roles/security-principals with the given permission
661 * and replace it with one or more permissions.
663 * @param string $oldPerm
664 * @param array $newPerms
667 public function replacePermission($oldPerm, $newPerms) {
668 $roles = user_roles(FALSE, $oldPerm);
669 foreach ($roles as $rid => $roleName) {
670 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
671 $perms = drupal_map_assoc(explode(', ', $permList));
672 unset($perms[$oldPerm]);
673 $perms = $perms +
drupal_map_assoc($newPerms);
674 $permList = implode(', ', $perms);
675 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
676 /* @codingStandardsIgnoreStart
677 if ( ! empty( $roles ) ) {
678 $rids = implode(',', array_keys($roles));
679 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
680 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
681 $oldPerm, implode(', ', $newPerms) );
682 @codingStandardsIgnoreEnd */
689 public function getModules() {
691 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
692 while ($row = db_fetch_object($q)) {
693 $result[] = new CRM_Core_Module('drupal.' . $row->name
, $row->status
== 1);
701 public function getLoginURL($destination = '') {
702 $config = CRM_Core_Config
::singleton();
703 $loginURL = $config->userFrameworkBaseURL
;
705 if (!empty($destination)) {
706 // append destination so user is returned to form they came from after login
707 $loginURL .= '?destination=' . urlencode($destination);
713 * Wrapper for og_membership creation.
717 * @param int $drupalID
720 public function og_membership_create($ogID, $drupalID) {
721 og_save_subscription($ogID, $drupalID, ['is_active' => 1]);
725 * Wrapper for og_membership deletion.
729 * @param int $drupalID
732 public function og_membership_delete($ogID, $drupalID) {
733 og_delete_subscription($ogID, $drupalID);
739 public function getTimeZoneString() {
741 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
742 if (variable_get('configurable_timezones', 1) && $user->uid
&& isset($user->timezone
) && strlen($user->timezone
)) {
743 $timezone = $user->timezone
;
746 $timezone = variable_get('date_default_timezone', NULL);
749 // Retrieved timezone will be represented as GMT offset in seconds but, according
750 // to the doc for the overridden method, ought to be returned as a region string
751 // (e.g., America/Havana).
752 if (strlen($timezone)) {
753 $timezone = timezone_name_from_abbr("", (int) $timezone);
757 $timezone = parent
::getTimeZoneString();
766 public function setHttpHeader($name, $value) {
767 drupal_set_header("$name: $value");
773 public function synchronizeUsers() {
774 $config = CRM_Core_Config
::singleton();
775 if (PHP_SAPI
!= 'cli') {
783 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
785 while ($row = db_fetch_array($result)) {
789 $user = new StdClass();
790 $uf = $config->userFramework
;
793 $contactMatching = 0;
794 foreach ($rows as $row) {
795 $user->$id = $row[$id];
796 $user->$mail = $row[$mail];
797 $user->$name = $row[$name];
799 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row[$id], $row[$mail], $uf, 1, 'Individual', TRUE)) {
808 'contactCount' => $contactCount,
809 'contactMatching' => $contactMatching,
810 'contactCreated' => $contactCreated,
815 * Return the CMS-specific url for its permissions page
818 public function getCMSPermissionsUrlParams() {
819 return ['ufAccessURL' => url('admin/user/permissions')];