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
;
78 public function updateCMSName($ufID, $ufName) {
80 if (function_exists('user_load')) {
81 $user = user_load($ufID);
82 if ($user->mail
!= $ufName) {
83 user_save($user, ['mail' => $ufName]);
84 $user = user_load($ufID);
90 * Check if username and email exists in the drupal db.
92 * @param array $params
93 * Array of name and mail values.
94 * @param array $errors
96 * @param string $emailName
97 * Field label for the 'email'.
99 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
100 $config = CRM_Core_Config
::singleton();
102 $dao = new CRM_Core_DAO();
103 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
104 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
105 $errors = form_get_errors();
107 // unset drupal messages to avoid twice display of errors
108 unset($_SESSION['messages']);
111 if (!empty($params['name'])) {
112 if ($nameError = user_validate_name($params['name'])) {
113 $errors['cms_name'] = $nameError;
117 "SELECT uid FROM {users} WHERE name = :name",
118 [':name' => $params['name']]
121 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
126 if (!empty($params['mail'])) {
127 if ($emailError = user_validate_mail($params['mail'])) {
128 $errors[$emailName] = $emailError;
132 "SELECT uid FROM {users} WHERE mail = :mail",
133 [':mail' => $params['mail']]
136 $resetUrl = url('user/password');
137 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
138 [1 => $params['mail'], 2 => $resetUrl]
148 public function getLoginURL($destination = '') {
149 $query = $destination ?
['destination' => $destination] : NULL;
150 return CRM_Utils_System
::url('user', $query, TRUE);
156 public function setTitle($title, $pageTitle = NULL) {
157 if (arg(0) == 'civicrm') {
162 drupal_set_title($pageTitle, PASS_THROUGH
);
169 public function appendBreadCrumb($breadCrumbs) {
170 $breadCrumb = drupal_get_breadcrumb();
172 if (is_array($breadCrumbs)) {
173 foreach ($breadCrumbs as $crumbs) {
174 if (stripos($crumbs['url'], 'id%%')) {
175 $args = ['cid', 'mid'];
176 foreach ($args as $a) {
177 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
181 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
185 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
188 drupal_set_breadcrumb($breadCrumb);
194 public function resetBreadCrumb() {
196 drupal_set_breadcrumb($bc);
202 public function addHTMLHead($header) {
204 if (!empty($header)) {
205 $key = 'civi_' . ++
$count;
208 '#markup' => $header,
210 drupal_add_html_head($data, $key);
217 public function addScriptUrl($url, $region) {
218 $params = ['group' => JS_LIBRARY
, 'weight' => 10];
222 $params['scope'] = substr($region, 5);
228 // If the path is within the drupal directory we can use the more efficient 'file' setting
229 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
230 drupal_add_js($url, $params);
237 public function addScript($code, $region) {
238 $params = ['type' => 'inline', 'group' => JS_LIBRARY
, 'weight' => 10];
242 $params['scope'] = substr($region, 5);
248 drupal_add_js($code, $params);
255 public function addStyleUrl($url, $region) {
256 if ($region != 'html-header') {
260 // If the path is within the drupal directory we can use the more efficient 'file' setting
261 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
262 drupal_add_css($url, $params);
269 public function addStyle($code, $region) {
270 if ($region != 'html-header') {
273 $params = ['type' => 'inline'];
274 drupal_add_css($code, $params);
281 public function mapConfigToSSL() {
283 $base_url = str_replace('http://', 'https://', $base_url);
287 * Get the name of the users table.
291 protected function getUsersTableName() {
292 $userFrameworkUsersTableName = Civi
::settings()->get('userFrameworkUsersTableName');
293 if (empty($userFrameworkUsersTableName)) {
294 $userFrameworkUsersTableName = 'users';
296 return $userFrameworkUsersTableName;
302 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
303 require_once 'DB.php';
305 $config = CRM_Core_Config
::singleton();
307 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
308 if (DB
::isError($dbDrupal)) {
309 throw new CRM_Core_Exception("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
312 $account = $userUid = $userMail = NULL;
313 if ($loadCMSBootstrap) {
314 $bootStrapParams = [];
315 if ($name && $password) {
321 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
325 $userUid = $user->uid
;
326 $userMail = $user->mail
;
331 // SOAP cannot load drupal bootstrap and hence we do it the old way
332 // Contact CiviSMTP folks if we run into issues with this :)
333 $cmsPath = $config->userSystem
->cmsRootPath($realPath);
335 require_once "$cmsPath/includes/bootstrap.inc";
336 require_once "$cmsPath/includes/password.inc";
338 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
339 $name = $dbDrupal->escapeSimple($strtolower($name));
340 $userFrameworkUsersTableName = $this->getUsersTableName();
342 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
345 FROM {$userFrameworkUsersTableName} u
346 WHERE LOWER(u.name) = '$name'
350 $query = $dbDrupal->query($sql);
351 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
354 $fakeDrupalAccount = drupal_anonymous_user();
355 $fakeDrupalAccount->name
= $name;
356 $fakeDrupalAccount->pass
= $row['pass'];
357 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
358 if ($passwordCheck) {
359 $userUid = $row['uid'];
360 $userMail = $row['mail'];
365 if ($userUid && $userMail) {
366 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
367 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
371 return [$contactID, $userUid, mt_rand()];
379 public function loadUser($username) {
382 $user = user_load_by_name($username);
384 if (empty($user->uid
)) {
389 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
391 // lets store contact id and user id in session
392 $session = CRM_Core_Session
::singleton();
393 $session->set('ufID', $uid);
394 $session->set('userID', $contact_id);
399 * Perform any post login activities required by the UF -
400 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
401 * calls hook_user op 'login' and generates a new session.
403 * @param array $params
405 * FIXME: Document values accepted/required by $params
407 public function userLoginFinalize($params = []) {
408 user_login_finalize($params);
412 * Determine the native ID of the CMS user.
414 * @param string $username
417 public function getUfId($username) {
418 $user = user_load_by_name($username);
419 if (empty($user->uid
)) {
428 public function logout() {
429 module_load_include('inc', 'user', 'user.pages');
430 return user_logout();
434 * Get the default location for CiviCRM blocks.
438 public function getDefaultBlockLocation() {
439 return 'sidebar_first';
443 * Load drupal bootstrap.
445 * @param array $params
446 * Either uid, or name & pass.
447 * @param bool $loadUser
448 * Boolean Require CMS user load.
449 * @param bool $throwError
450 * If true, print error on failure and exit.
451 * @param bool|string $realPath path to script
455 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
456 //take the cms root path.
457 $cmsPath = $this->cmsRootPath($realPath);
459 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
461 throw new Exception('Sorry, could not locate bootstrap.inc');
465 // load drupal bootstrap
467 define('DRUPAL_ROOT', $cmsPath);
469 // For drupal multi-site CRM-11313
470 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
471 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
472 if (!empty($matches[1])) {
473 $_SERVER['HTTP_HOST'] = $matches[1];
476 require_once 'includes/bootstrap.inc';
477 // @ to suppress notices eg 'DRUPALFOO already defined'.
478 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
480 // explicitly setting error reporting, since we cannot handle drupal related notices
481 // @todo 1 = E_ERROR, but more to the point setting error reporting deep in code
482 // causes grief with debugging scripts
484 if (!function_exists('module_exists')) {
486 throw new Exception('Sorry, could not load drupal bootstrap.');
490 if (!module_exists('civicrm')) {
492 throw new Exception('Sorry, drupal cannot find CiviCRM');
497 // seems like we've bootstrapped drupal
498 $config = CRM_Core_Config
::singleton();
500 // lets also fix the clean url setting
502 $config->cleanURL
= (int) variable_get('clean_url', '0');
504 // we need to call the config hook again, since we now know
505 // all the modules that are listening on it, does not apply
506 // to J! and WP as yet
508 CRM_Utils_Hook
::config($config);
514 $uid = CRM_Utils_Array
::value('uid', $params);
516 //load user, we need to check drupal permissions.
517 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
518 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
521 $uid = user_authenticate($name, $pass);
524 throw new Exception('Sorry, unrecognized username or password.');
532 $account = user_load($uid);
533 if ($account && $account->uid
) {
541 throw new Exception('Sorry, can not load CMS user account.');
544 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
545 // which means that define(CIVICRM_CLEANURL) was correctly set.
547 $config = CRM_Core_Config
::singleton();
548 $config->cleanURL
= (int) variable_get('clean_url', '0');
550 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
551 CRM_Utils_Hook
::config($config);
559 * @param string $scriptFilename
561 * @return null|string
563 public function cmsRootPath($scriptFilename = NULL) {
564 $cmsRoot = $valid = NULL;
566 if (!is_null($scriptFilename)) {
567 $path = $scriptFilename;
570 $path = $_SERVER['SCRIPT_FILENAME'];
573 if (function_exists('drush_get_context')) {
574 // drush anyway takes care of multisite install etc
575 return drush_get_context('DRUSH_DRUPAL_ROOT');
578 global $civicrm_paths;
579 if (!empty($civicrm_paths['cms.root']['path'])) {
580 return $civicrm_paths['cms.root']['path'];
584 $pathVars = explode('/',
585 str_replace('//', '/',
586 str_replace('\\', '/', $path)
590 //lets store first var,
591 //need to get back for windows.
592 $firstVar = array_shift($pathVars);
594 // Remove the script name to remove an necessary iteration of the loop.
595 array_pop($pathVars);
597 // CRM-7429 -- do check for uppermost 'includes' dir, which would
598 // work for multisite installation.
600 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
601 $cmsIncludePath = "$cmsRoot/includes";
602 // Stop if we find bootstrap.
603 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
607 //remove one directory level.
608 array_pop($pathVars);
609 } while (count($pathVars));
611 return ($valid) ?
$cmsRoot : NULL;
617 public function isUserLoggedIn() {
619 if (function_exists('user_is_logged_in')) {
620 $isloggedIn = user_is_logged_in();
629 public function getLoggedInUfID() {
631 if (function_exists('user_is_logged_in') &&
632 user_is_logged_in() &&
633 function_exists('user_uid_optional_to_arg')
635 $ufID = user_uid_optional_to_arg([]);
644 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
649 //CRM-7803 -from d7 onward.
650 $config = CRM_Core_Config
::singleton();
651 if (function_exists('variable_get') &&
652 module_exists('locale') &&
653 function_exists('language_negotiation_get')
657 //does user configuration allow language
658 //support from the URL (Path prefix or domain)
659 if (language_negotiation_get('language') == 'locale-url') {
660 $urlType = variable_get('locale_language_negotiation_url_part');
663 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
664 if (isset($language->prefix
) && $language->prefix
) {
665 if ($addLanguagePart) {
666 $url .= $language->prefix
. '/';
668 if ($removeLanguagePart) {
669 $url = str_replace("/{$language->prefix}/", '/', $url);
674 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
675 if (isset($language->domain
) && $language->domain
) {
676 if ($addLanguagePart) {
677 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain
);
678 // drupal function base_path() adds a "/" to the beginning and end of the returned path
679 if (substr($cleanedUrl, -1) == '/') {
680 $cleanedUrl = substr($cleanedUrl, 0, -1);
682 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $cleanedUrl . base_path();
684 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
685 $url = str_replace('\\', '/', $url);
686 $parseUrl = parse_url($url);
688 //kinda hackish but not sure how to do it right
689 //hope http_build_url() will help at some point.
690 if (is_array($parseUrl) && !empty($parseUrl)) {
691 $urlParts = explode('/', $url);
692 $hostKey = array_search($parseUrl['host'], $urlParts);
693 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
694 $urlParts[$hostKey] = $ufUrlParts['host'];
695 $url = implode('/', $urlParts);
707 * Find any users/roles/security-principals with the given permission
708 * and replace it with one or more permissions.
710 * @param string $oldPerm
711 * @param array $newPerms
714 public function replacePermission($oldPerm, $newPerms) {
715 $roles = user_roles(FALSE, $oldPerm);
716 if (!empty($roles)) {
717 foreach (array_keys($roles) as $rid) {
718 user_role_revoke_permissions($rid, [$oldPerm]);
719 user_role_grant_permissions($rid, $newPerms);
725 * Wrapper for og_membership creation.
729 * @param int $drupalID
732 public function og_membership_create($ogID, $drupalID) {
733 if (function_exists('og_entity_query_alter')) {
734 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
736 // @TODO Find more solid way to check - try system_get_info('module', 'og').
738 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
739 og_group('node', $ogID, ['entity' => user_load($drupalID)]);
742 // Works for the OG 7.x-1.x branch
743 og_group($ogID, ['entity' => user_load($drupalID)]);
748 * Wrapper for og_membership deletion.
752 * @param int $drupalID
755 public function og_membership_delete($ogID, $drupalID) {
756 if (function_exists('og_entity_query_alter')) {
757 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
758 // TODO: Find a more solid way to make this test
759 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
760 og_ungroup('node', $ogID, 'user', user_load($drupalID));
763 // Works for the OG 7.x-1.x branch
764 og_ungroup($ogID, 'user', user_load($drupalID));
771 public function getTimeZoneString() {
773 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
774 if (variable_get('configurable_timezones', 1) && $user->uid
&& isset($user->timezone
) && strlen($user->timezone
)) {
775 $timezone = $user->timezone
;
778 $timezone = variable_get('date_default_timezone', NULL);
781 $timezone = parent
::getTimeZoneString();
789 public function setHttpHeader($name, $value) {
790 drupal_add_http_header($name, $value);
796 public function synchronizeUsers() {
797 $config = CRM_Core_Config
::singleton();
798 if (PHP_SAPI
!= 'cli') {
805 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
807 $user = new StdClass();
808 $uf = $config->userFramework
;
811 $contactMatching = 0;
812 foreach ($result as $row) {
813 $user->$id = $row->$id;
814 $user->$mail = $row->$mail;
815 $user->$name = $row->$name;
817 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
826 'contactCount' => $contactCount,
827 'contactMatching' => $contactMatching,
828 'contactCreated' => $contactCreated,
833 * Commit the session before exiting.
834 * Similar to drupal_exit().
836 public function onCiviExit() {
837 if (function_exists('module_invoke_all')) {
838 if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE
!= 'update') {
839 module_invoke_all('exit');
841 drupal_session_commit();