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_Drupal
extends CRM_Utils_System_DrupalBase
{
26 public function createUser(&$params, $mail) {
27 $form_state = form_state_defaults();
29 $form_state['input'] = [
30 'name' => $params['cms_name'],
31 'mail' => $params[$mail],
32 'op' => 'Create new account',
35 $admin = user_access('administer users');
36 if (!variable_get('user_email_verification', TRUE) ||
$admin) {
37 $form_state['input']['pass'] = ['pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']];
40 if (!empty($params['notify'])) {
41 $form_state['input']['notify'] = $params['notify'];
44 $form_state['rebuild'] = FALSE;
45 $form_state['programmed'] = TRUE;
46 $form_state['complete form'] = FALSE;
47 $form_state['method'] = 'post';
48 $form_state['build_info']['args'] = [];
50 * if we want to submit this form more than once in a process (e.g. create more than one user)
51 * we must force it to validate each time for this form. Otherwise it will not validate
52 * subsequent submissions and the manner in which the password is passed in will be invalid
54 $form_state['must_validate'] = TRUE;
55 $config = CRM_Core_Config
::singleton();
57 // we also need to redirect b
58 $config->inCiviCRM
= TRUE;
60 $form = drupal_retrieve_form('user_register_form', $form_state);
61 $form_state['process_input'] = 1;
62 $form_state['submitted'] = 1;
63 $form['#array_parents'] = [];
64 $form['#tree'] = FALSE;
65 drupal_process_form('user_register_form', $form, $form_state);
67 $config->inCiviCRM
= FALSE;
69 if (form_get_errors()) {
72 return $form_state['user']->uid
;
76 * Appends a Drupal 7 Javascript file when the CRM Menubar Javascript file has
77 * been included. The file is added before the menu bar so we can properly listen
78 * for the menu bar ready event.
80 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$event) {
81 $menuBarFileIndex = array_search('js/crm.menubar.js', $event->list);
83 if ($menuBarFileIndex !== FALSE) {
84 array_splice($event->list, $menuBarFileIndex, 0, ['js/crm.drupal7.js']);
91 public function updateCMSName($ufID, $ufName) {
93 if (function_exists('user_load')) {
94 $user = user_load($ufID);
95 if ($user->mail
!= $ufName) {
96 user_save($user, ['mail' => $ufName]);
97 $user = user_load($ufID);
103 * Check if username and email exists in the drupal db.
105 * @param array $params
106 * Array of name and mail values.
107 * @param array $errors
109 * @param string $emailName
110 * Field label for the 'email'.
112 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
113 $config = CRM_Core_Config
::singleton();
115 $dao = new CRM_Core_DAO();
116 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
117 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
118 $errors = form_get_errors();
120 // unset drupal messages to avoid twice display of errors
121 unset($_SESSION['messages']);
124 if (!empty($params['name'])) {
125 if ($nameError = user_validate_name($params['name'])) {
126 $errors['cms_name'] = $nameError;
130 "SELECT uid FROM {users} WHERE name = :name",
131 [':name' => $params['name']]
134 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
139 if (!empty($params['mail'])) {
140 if ($emailError = user_validate_mail($params['mail'])) {
141 $errors[$emailName] = $emailError;
145 "SELECT uid FROM {users} WHERE mail = :mail",
146 [':mail' => $params['mail']]
149 $resetUrl = url('user/password');
150 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
151 [1 => $params['mail'], 2 => $resetUrl]
161 public function getLoginURL($destination = '') {
162 $query = $destination ?
['destination' => $destination] : NULL;
163 return CRM_Utils_System
::url('user', $query, TRUE);
169 public function setTitle($title, $pageTitle = NULL) {
170 if (arg(0) == 'civicrm') {
175 drupal_set_title($pageTitle, PASS_THROUGH
);
182 public function appendBreadCrumb($breadCrumbs) {
183 $breadCrumb = drupal_get_breadcrumb();
185 if (is_array($breadCrumbs)) {
186 foreach ($breadCrumbs as $crumbs) {
187 if (stripos($crumbs['url'], 'id%%')) {
188 $args = ['cid', 'mid'];
189 foreach ($args as $a) {
190 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
194 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
198 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
201 drupal_set_breadcrumb($breadCrumb);
207 public function resetBreadCrumb() {
209 drupal_set_breadcrumb($bc);
215 public function addHTMLHead($header) {
217 if (!empty($header)) {
218 $key = 'civi_' . ++
$count;
221 '#markup' => $header,
223 drupal_add_html_head($data, $key);
230 public function addScriptUrl($url, $region) {
231 $params = ['group' => JS_LIBRARY
, 'weight' => 10];
235 $params['scope'] = substr($region, 5);
241 // If the path is within the drupal directory we can use the more efficient 'file' setting
242 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
243 drupal_add_js($url, $params);
250 public function addScript($code, $region) {
251 $params = ['type' => 'inline', 'group' => JS_LIBRARY
, 'weight' => 10];
255 $params['scope'] = substr($region, 5);
261 drupal_add_js($code, $params);
268 public function addStyleUrl($url, $region) {
269 if ($region != 'html-header') {
273 // If the path is within the drupal directory we can use the more efficient 'file' setting
274 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
275 drupal_add_css($url, $params);
282 public function addStyle($code, $region) {
283 if ($region != 'html-header') {
286 $params = ['type' => 'inline'];
287 drupal_add_css($code, $params);
294 public function mapConfigToSSL() {
296 $base_url = str_replace('http://', 'https://', $base_url);
300 * Get the name of the users table.
304 protected function getUsersTableName() {
305 $userFrameworkUsersTableName = Civi
::settings()->get('userFrameworkUsersTableName');
306 if (empty($userFrameworkUsersTableName)) {
307 $userFrameworkUsersTableName = 'users';
309 return $userFrameworkUsersTableName;
315 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
316 require_once 'DB.php';
318 $config = CRM_Core_Config
::singleton();
320 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
321 if (DB
::isError($dbDrupal)) {
322 throw new CRM_Core_Exception("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
325 $account = $userUid = $userMail = NULL;
326 if ($loadCMSBootstrap) {
327 $bootStrapParams = [];
328 if ($name && $password) {
334 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
338 $userUid = $user->uid
;
339 $userMail = $user->mail
;
344 // SOAP cannot load drupal bootstrap and hence we do it the old way
345 // Contact CiviSMTP folks if we run into issues with this :)
346 $cmsPath = $config->userSystem
->cmsRootPath($realPath);
348 require_once "$cmsPath/includes/bootstrap.inc";
349 require_once "$cmsPath/includes/password.inc";
351 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
352 $name = $dbDrupal->escapeSimple($strtolower($name));
353 $userFrameworkUsersTableName = $this->getUsersTableName();
355 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
358 FROM {$userFrameworkUsersTableName} u
359 WHERE LOWER(u.name) = '$name'
363 $query = $dbDrupal->query($sql);
364 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
367 $fakeDrupalAccount = drupal_anonymous_user();
368 $fakeDrupalAccount->name
= $name;
369 $fakeDrupalAccount->pass
= $row['pass'];
370 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
371 if ($passwordCheck) {
372 $userUid = $row['uid'];
373 $userMail = $row['mail'];
378 if ($userUid && $userMail) {
379 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
380 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
384 return [$contactID, $userUid, mt_rand()];
392 public function loadUser($username) {
395 $user = user_load_by_name($username);
397 if (empty($user->uid
)) {
402 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
404 // lets store contact id and user id in session
405 $session = CRM_Core_Session
::singleton();
406 $session->set('ufID', $uid);
407 $session->set('userID', $contact_id);
412 * Perform any post login activities required by the UF -
413 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
414 * calls hook_user op 'login' and generates a new session.
416 * @param array $params
418 * FIXME: Document values accepted/required by $params
420 public function userLoginFinalize($params = []) {
421 user_login_finalize($params);
425 * Determine the native ID of the CMS user.
427 * @param string $username
430 public function getUfId($username) {
431 $user = user_load_by_name($username);
432 if (empty($user->uid
)) {
441 public function logout() {
442 module_load_include('inc', 'user', 'user.pages');
443 return user_logout();
447 * Get the default location for CiviCRM blocks.
451 public function getDefaultBlockLocation() {
452 return 'sidebar_first';
456 * Load drupal bootstrap.
458 * @param array $params
459 * Either uid, or name & pass.
460 * @param bool $loadUser
461 * Boolean Require CMS user load.
462 * @param bool $throwError
463 * If true, print error on failure and exit.
464 * @param bool|string $realPath path to script
468 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
469 //take the cms root path.
470 $cmsPath = $this->cmsRootPath($realPath);
472 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
474 throw new Exception('Sorry, could not locate bootstrap.inc');
478 // load drupal bootstrap
480 define('DRUPAL_ROOT', $cmsPath);
482 // For drupal multi-site CRM-11313
483 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
484 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
485 if (!empty($matches[1])) {
486 $_SERVER['HTTP_HOST'] = $matches[1];
489 require_once 'includes/bootstrap.inc';
490 // @ to suppress notices eg 'DRUPALFOO already defined'.
491 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
493 // explicitly setting error reporting, since we cannot handle drupal related notices
494 // @todo 1 = E_ERROR, but more to the point setting error reporting deep in code
495 // causes grief with debugging scripts
497 if (!function_exists('module_exists')) {
499 throw new Exception('Sorry, could not load drupal bootstrap.');
503 if (!module_exists('civicrm')) {
505 throw new Exception('Sorry, drupal cannot find CiviCRM');
510 // seems like we've bootstrapped drupal
511 $config = CRM_Core_Config
::singleton();
513 // lets also fix the clean url setting
515 $config->cleanURL
= (int) variable_get('clean_url', '0');
517 // we need to call the config hook again, since we now know
518 // all the modules that are listening on it, does not apply
519 // to J! and WP as yet
521 CRM_Utils_Hook
::config($config);
527 $uid = $params['uid'] ??
NULL;
529 //load user, we need to check drupal permissions.
530 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
531 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
534 $uid = user_authenticate($name, $pass);
537 throw new Exception('Sorry, unrecognized username or password.');
545 $account = user_load($uid);
546 if ($account && $account->uid
) {
554 throw new Exception('Sorry, can not load CMS user account.');
557 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
558 // which means that define(CIVICRM_CLEANURL) was correctly set.
560 $config = CRM_Core_Config
::singleton();
561 $config->cleanURL
= (int) variable_get('clean_url', '0');
563 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
564 CRM_Utils_Hook
::config($config);
572 * @param string $scriptFilename
574 * @return null|string
576 public function cmsRootPath($scriptFilename = NULL) {
577 $cmsRoot = $valid = NULL;
579 if (!is_null($scriptFilename)) {
580 $path = $scriptFilename;
583 $path = $_SERVER['SCRIPT_FILENAME'];
586 if (function_exists('drush_get_context')) {
587 // drush anyway takes care of multisite install etc
588 return drush_get_context('DRUSH_DRUPAL_ROOT');
591 global $civicrm_paths;
592 if (!empty($civicrm_paths['cms.root']['path'])) {
593 return $civicrm_paths['cms.root']['path'];
597 $pathVars = explode('/',
598 str_replace('//', '/',
599 str_replace('\\', '/', $path)
603 //lets store first var,
604 //need to get back for windows.
605 $firstVar = array_shift($pathVars);
607 // Remove the script name to remove an necessary iteration of the loop.
608 array_pop($pathVars);
610 // CRM-7429 -- do check for uppermost 'includes' dir, which would
611 // work for multisite installation.
613 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
614 $cmsIncludePath = "$cmsRoot/includes";
615 // Stop if we find bootstrap.
616 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
620 //remove one directory level.
621 array_pop($pathVars);
622 } while (count($pathVars));
624 return ($valid) ?
$cmsRoot : NULL;
630 public function isUserLoggedIn() {
632 if (function_exists('user_is_logged_in')) {
633 $isloggedIn = user_is_logged_in();
642 public function getLoggedInUfID() {
644 if (function_exists('user_is_logged_in') &&
645 user_is_logged_in() &&
646 function_exists('user_uid_optional_to_arg')
648 $ufID = user_uid_optional_to_arg([]);
657 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
662 //CRM-7803 -from d7 onward.
663 $config = CRM_Core_Config
::singleton();
664 if (function_exists('variable_get') &&
665 module_exists('locale') &&
666 function_exists('language_negotiation_get')
670 //does user configuration allow language
671 //support from the URL (Path prefix or domain)
672 if (language_negotiation_get('language') == 'locale-url') {
673 $urlType = variable_get('locale_language_negotiation_url_part');
676 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
677 if (isset($language->prefix
) && $language->prefix
) {
678 if ($addLanguagePart) {
679 $url .= $language->prefix
. '/';
681 if ($removeLanguagePart) {
682 $url = str_replace("/{$language->prefix}/", '/', $url);
687 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
688 if (isset($language->domain
) && $language->domain
) {
689 if ($addLanguagePart) {
690 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain
);
691 // drupal function base_path() adds a "/" to the beginning and end of the returned path
692 if (substr($cleanedUrl, -1) == '/') {
693 $cleanedUrl = substr($cleanedUrl, 0, -1);
695 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $cleanedUrl . base_path();
697 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
698 $url = str_replace('\\', '/', $url);
699 $parseUrl = parse_url($url);
701 //kinda hackish but not sure how to do it right
702 //hope http_build_url() will help at some point.
703 if (is_array($parseUrl) && !empty($parseUrl)) {
704 $urlParts = explode('/', $url);
705 $hostKey = array_search($parseUrl['host'], $urlParts);
706 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
707 $urlParts[$hostKey] = $ufUrlParts['host'];
708 $url = implode('/', $urlParts);
720 * Find any users/roles/security-principals with the given permission
721 * and replace it with one or more permissions.
723 * @param string $oldPerm
724 * @param array $newPerms
727 public function replacePermission($oldPerm, $newPerms) {
728 $roles = user_roles(FALSE, $oldPerm);
729 if (!empty($roles)) {
730 foreach (array_keys($roles) as $rid) {
731 user_role_revoke_permissions($rid, [$oldPerm]);
732 user_role_grant_permissions($rid, $newPerms);
738 * Wrapper for og_membership creation.
742 * @param int $drupalID
745 public function og_membership_create($ogID, $drupalID) {
746 if (function_exists('og_entity_query_alter')) {
747 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
749 // @TODO Find more solid way to check - try system_get_info('module', 'og').
751 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
752 og_group('node', $ogID, ['entity' => user_load($drupalID)]);
755 // Works for the OG 7.x-1.x branch
756 og_group($ogID, ['entity' => user_load($drupalID)]);
761 * Wrapper for og_membership deletion.
765 * @param int $drupalID
768 public function og_membership_delete($ogID, $drupalID) {
769 if (function_exists('og_entity_query_alter')) {
770 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
771 // TODO: Find a more solid way to make this test
772 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
773 og_ungroup('node', $ogID, 'user', user_load($drupalID));
776 // Works for the OG 7.x-1.x branch
777 og_ungroup($ogID, 'user', user_load($drupalID));
784 public function getTimeZoneString() {
786 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
787 if (variable_get('configurable_timezones', 1) && $user->uid
&& isset($user->timezone
) && strlen($user->timezone
)) {
788 $timezone = $user->timezone
;
791 $timezone = variable_get('date_default_timezone', NULL);
794 $timezone = parent
::getTimeZoneString();
802 public function setHttpHeader($name, $value) {
803 drupal_add_http_header($name, $value);
809 public function synchronizeUsers() {
810 $config = CRM_Core_Config
::singleton();
811 if (PHP_SAPI
!= 'cli') {
818 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
820 $user = new StdClass();
821 $uf = $config->userFramework
;
824 $contactMatching = 0;
825 foreach ($result as $row) {
826 $user->$id = $row->$id;
827 $user->$mail = $row->$mail;
828 $user->$name = $row->$name;
830 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
839 'contactCount' => $contactCount,
840 'contactMatching' => $contactMatching,
841 'contactCreated' => $contactCreated,
846 * Commit the session before exiting.
847 * Similar to drupal_exit().
849 public function onCiviExit() {
850 if (function_exists('module_invoke_all')) {
851 if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE
!= 'update') {
852 module_invoke_all('exit');
854 drupal_session_commit();