3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
35 * Drupal specific stuff goes here
37 class CRM_Utils_System_Drupal
extends CRM_Utils_System_DrupalBase
{
42 public function createUser(&$params, $mail) {
43 $form_state = form_state_defaults();
45 $form_state['input'] = [
46 'name' => $params['cms_name'],
47 'mail' => $params[$mail],
48 'op' => 'Create new account',
51 $admin = user_access('administer users');
52 if (!variable_get('user_email_verification', TRUE) ||
$admin) {
53 $form_state['input']['pass'] = ['pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']];
56 if (!empty($params['notify'])) {
57 $form_state['input']['notify'] = $params['notify'];
60 $form_state['rebuild'] = FALSE;
61 $form_state['programmed'] = TRUE;
62 $form_state['complete form'] = FALSE;
63 $form_state['method'] = 'post';
64 $form_state['build_info']['args'] = [];
66 * if we want to submit this form more than once in a process (e.g. create more than one user)
67 * we must force it to validate each time for this form. Otherwise it will not validate
68 * subsequent submissions and the manner in which the password is passed in will be invalid
70 $form_state['must_validate'] = TRUE;
71 $config = CRM_Core_Config
::singleton();
73 // we also need to redirect b
74 $config->inCiviCRM
= TRUE;
76 $form = drupal_retrieve_form('user_register_form', $form_state);
77 $form_state['process_input'] = 1;
78 $form_state['submitted'] = 1;
79 $form['#array_parents'] = [];
80 $form['#tree'] = FALSE;
81 drupal_process_form('user_register_form', $form, $form_state);
83 $config->inCiviCRM
= FALSE;
85 if (form_get_errors()) {
88 return $form_state['user']->uid
;
94 public function updateCMSName($ufID, $ufName) {
96 if (function_exists('user_load')) {
97 $user = user_load($ufID);
98 if ($user->mail
!= $ufName) {
99 user_save($user, ['mail' => $ufName]);
100 $user = user_load($ufID);
106 * Check if username and email exists in the drupal db.
108 * @param array $params
109 * Array of name and mail values.
110 * @param array $errors
112 * @param string $emailName
113 * Field label for the 'email'.
115 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
116 $config = CRM_Core_Config
::singleton();
118 $dao = new CRM_Core_DAO();
119 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
120 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
121 $errors = form_get_errors();
123 // unset drupal messages to avoid twice display of errors
124 unset($_SESSION['messages']);
127 if (!empty($params['name'])) {
128 if ($nameError = user_validate_name($params['name'])) {
129 $errors['cms_name'] = $nameError;
133 "SELECT uid FROM {users} WHERE name = :name",
134 [':name' => $params['name']]
137 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
142 if (!empty($params['mail'])) {
143 if ($emailError = user_validate_mail($params['mail'])) {
144 $errors[$emailName] = $emailError;
148 "SELECT uid FROM {users} WHERE mail = :mail",
149 [':mail' => $params['mail']]
152 $resetUrl = url('user/password');
153 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
154 [1 => $params['mail'], 2 => $resetUrl]
164 public function getLoginURL($destination = '') {
165 $query = $destination ?
['destination' => $destination] : NULL;
166 return CRM_Utils_System
::url('user', $query, TRUE);
172 public function setTitle($title, $pageTitle = NULL) {
173 if (arg(0) == 'civicrm') {
178 drupal_set_title($pageTitle, PASS_THROUGH
);
185 public function appendBreadCrumb($breadCrumbs) {
186 $breadCrumb = drupal_get_breadcrumb();
188 if (is_array($breadCrumbs)) {
189 foreach ($breadCrumbs as $crumbs) {
190 if (stripos($crumbs['url'], 'id%%')) {
191 $args = ['cid', 'mid'];
192 foreach ($args as $a) {
193 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
197 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
201 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
204 drupal_set_breadcrumb($breadCrumb);
210 public function resetBreadCrumb() {
212 drupal_set_breadcrumb($bc);
218 public function addHTMLHead($header) {
220 if (!empty($header)) {
221 $key = 'civi_' . ++
$count;
224 '#markup' => $header,
226 drupal_add_html_head($data, $key);
233 public function addScriptUrl($url, $region) {
234 $params = ['group' => JS_LIBRARY
, 'weight' => 10];
238 $params['scope'] = substr($region, 5);
244 // If the path is within the drupal directory we can use the more efficient 'file' setting
245 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
246 drupal_add_js($url, $params);
253 public function addScript($code, $region) {
254 $params = ['type' => 'inline', 'group' => JS_LIBRARY
, 'weight' => 10];
258 $params['scope'] = substr($region, 5);
264 drupal_add_js($code, $params);
271 public function addStyleUrl($url, $region) {
272 if ($region != 'html-header') {
276 // If the path is within the drupal directory we can use the more efficient 'file' setting
277 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
278 drupal_add_css($url, $params);
285 public function addStyle($code, $region) {
286 if ($region != 'html-header') {
289 $params = ['type' => 'inline'];
290 drupal_add_css($code, $params);
297 public function mapConfigToSSL() {
299 $base_url = str_replace('http://', 'https://', $base_url);
303 * Get the name of the users table.
307 protected function getUsersTableName() {
308 $userFrameworkUsersTableName = Civi
::settings()->get('userFrameworkUsersTableName');
309 if (empty($userFrameworkUsersTableName)) {
310 $userFrameworkUsersTableName = 'users';
312 return $userFrameworkUsersTableName;
318 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
319 require_once 'DB.php';
321 $config = CRM_Core_Config
::singleton();
323 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
324 if (DB
::isError($dbDrupal)) {
325 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
328 $account = $userUid = $userMail = NULL;
329 if ($loadCMSBootstrap) {
330 $bootStrapParams = [];
331 if ($name && $password) {
337 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
341 $userUid = $user->uid
;
342 $userMail = $user->mail
;
347 // SOAP cannot load drupal bootstrap and hence we do it the old way
348 // Contact CiviSMTP folks if we run into issues with this :)
349 $cmsPath = $config->userSystem
->cmsRootPath($realPath);
351 require_once "$cmsPath/includes/bootstrap.inc";
352 require_once "$cmsPath/includes/password.inc";
354 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
355 $name = $dbDrupal->escapeSimple($strtolower($name));
356 $userFrameworkUsersTableName = $this->getUsersTableName();
358 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
361 FROM {$userFrameworkUsersTableName} u
362 WHERE LOWER(u.name) = '$name'
366 $query = $dbDrupal->query($sql);
367 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
370 $fakeDrupalAccount = drupal_anonymous_user();
371 $fakeDrupalAccount->name
= $name;
372 $fakeDrupalAccount->pass
= $row['pass'];
373 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
374 if ($passwordCheck) {
375 $userUid = $row['uid'];
376 $userMail = $row['mail'];
381 if ($userUid && $userMail) {
382 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
383 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
387 return [$contactID, $userUid, mt_rand()];
395 public function loadUser($username) {
398 $user = user_load_by_name($username);
400 if (empty($user->uid
)) {
405 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
407 // lets store contact id and user id in session
408 $session = CRM_Core_Session
::singleton();
409 $session->set('ufID', $uid);
410 $session->set('userID', $contact_id);
415 * Perform any post login activities required by the UF -
416 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
417 * calls hook_user op 'login' and generates a new session.
419 * @param array $params
421 * FIXME: Document values accepted/required by $params
423 public function userLoginFinalize($params = []) {
424 user_login_finalize($params);
428 * Determine the native ID of the CMS user.
430 * @param string $username
433 public function getUfId($username) {
434 $user = user_load_by_name($username);
435 if (empty($user->uid
)) {
444 public function logout() {
445 module_load_include('inc', 'user', 'user.pages');
446 return user_logout();
450 * Get the default location for CiviCRM blocks.
454 public function getDefaultBlockLocation() {
455 return 'sidebar_first';
459 * Load drupal bootstrap.
461 * @param array $params
462 * Either uid, or name & pass.
463 * @param bool $loadUser
464 * Boolean Require CMS user load.
465 * @param bool $throwError
466 * If true, print error on failure and exit.
467 * @param bool|string $realPath path to script
471 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
472 //take the cms root path.
473 $cmsPath = $this->cmsRootPath($realPath);
475 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
477 throw new Exception('Sorry, could not locate bootstrap.inc');
481 // load drupal bootstrap
483 define('DRUPAL_ROOT', $cmsPath);
485 // For drupal multi-site CRM-11313
486 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
487 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
488 if (!empty($matches[1])) {
489 $_SERVER['HTTP_HOST'] = $matches[1];
492 require_once 'includes/bootstrap.inc';
493 // @ to suppress notices eg 'DRUPALFOO already defined'.
494 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
496 // explicitly setting error reporting, since we cannot handle drupal related notices
497 // @todo 1 = E_ERROR, but more to the point setting error reporting deep in code
498 // causes grief with debugging scripts
500 if (!function_exists('module_exists')) {
502 throw new Exception('Sorry, could not load drupal bootstrap.');
506 if (!module_exists('civicrm')) {
508 throw new Exception('Sorry, drupal cannot find CiviCRM');
513 // seems like we've bootstrapped drupal
514 $config = CRM_Core_Config
::singleton();
516 // lets also fix the clean url setting
518 $config->cleanURL
= (int) variable_get('clean_url', '0');
520 // we need to call the config hook again, since we now know
521 // all the modules that are listening on it, does not apply
522 // to J! and WP as yet
524 CRM_Utils_Hook
::config($config);
530 $uid = CRM_Utils_Array
::value('uid', $params);
532 //load user, we need to check drupal permissions.
533 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
534 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
537 $uid = user_authenticate($name, $pass);
540 throw new Exception('Sorry, unrecognized username or password.');
548 $account = user_load($uid);
549 if ($account && $account->uid
) {
557 throw new Exception('Sorry, can not load CMS user account.');
560 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
561 // which means that define(CIVICRM_CLEANURL) was correctly set.
563 $config = CRM_Core_Config
::singleton();
564 $config->cleanURL
= (int) variable_get('clean_url', '0');
566 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
567 CRM_Utils_Hook
::config($config);
575 * @param string $scriptFilename
577 * @return null|string
579 public function cmsRootPath($scriptFilename = NULL) {
580 $cmsRoot = $valid = NULL;
582 if (!is_null($scriptFilename)) {
583 $path = $scriptFilename;
586 $path = $_SERVER['SCRIPT_FILENAME'];
589 if (function_exists('drush_get_context')) {
590 // drush anyway takes care of multisite install etc
591 return drush_get_context('DRUSH_DRUPAL_ROOT');
594 global $civicrm_paths;
595 if (!empty($civicrm_paths['cms.root']['path'])) {
596 return $civicrm_paths['cms.root']['path'];
600 $pathVars = explode('/',
601 str_replace('//', '/',
602 str_replace('\\', '/', $path)
606 //lets store first var,
607 //need to get back for windows.
608 $firstVar = array_shift($pathVars);
610 // Remove the script name to remove an necessary iteration of the loop.
611 array_pop($pathVars);
613 // CRM-7429 -- do check for uppermost 'includes' dir, which would
614 // work for multisite installation.
616 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
617 $cmsIncludePath = "$cmsRoot/includes";
618 // Stop if we find bootstrap.
619 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
623 //remove one directory level.
624 array_pop($pathVars);
625 } while (count($pathVars));
627 return ($valid) ?
$cmsRoot : NULL;
633 public function isUserLoggedIn() {
635 if (function_exists('user_is_logged_in')) {
636 $isloggedIn = user_is_logged_in();
645 public function getLoggedInUfID() {
647 if (function_exists('user_is_logged_in') &&
648 user_is_logged_in() &&
649 function_exists('user_uid_optional_to_arg')
651 $ufID = user_uid_optional_to_arg([]);
660 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
665 //CRM-7803 -from d7 onward.
666 $config = CRM_Core_Config
::singleton();
667 if (function_exists('variable_get') &&
668 module_exists('locale') &&
669 function_exists('language_negotiation_get')
673 //does user configuration allow language
674 //support from the URL (Path prefix or domain)
675 if (language_negotiation_get('language') == 'locale-url') {
676 $urlType = variable_get('locale_language_negotiation_url_part');
679 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
680 if (isset($language->prefix
) && $language->prefix
) {
681 if ($addLanguagePart) {
682 $url .= $language->prefix
. '/';
684 if ($removeLanguagePart) {
685 $url = str_replace("/{$language->prefix}/", '/', $url);
690 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
691 if (isset($language->domain
) && $language->domain
) {
692 if ($addLanguagePart) {
693 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain
);
694 // drupal function base_path() adds a "/" to the beginning and end of the returned path
695 if (substr($cleanedUrl, -1) == '/') {
696 $cleanedUrl = substr($cleanedUrl, 0, -1);
698 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $cleanedUrl . base_path();
700 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
701 $url = str_replace('\\', '/', $url);
702 $parseUrl = parse_url($url);
704 //kinda hackish but not sure how to do it right
705 //hope http_build_url() will help at some point.
706 if (is_array($parseUrl) && !empty($parseUrl)) {
707 $urlParts = explode('/', $url);
708 $hostKey = array_search($parseUrl['host'], $urlParts);
709 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
710 $urlParts[$hostKey] = $ufUrlParts['host'];
711 $url = implode('/', $urlParts);
723 * Find any users/roles/security-principals with the given permission
724 * and replace it with one or more permissions.
726 * @param string $oldPerm
727 * @param array $newPerms
730 public function replacePermission($oldPerm, $newPerms) {
731 $roles = user_roles(FALSE, $oldPerm);
732 if (!empty($roles)) {
733 foreach (array_keys($roles) as $rid) {
734 user_role_revoke_permissions($rid, [$oldPerm]);
735 user_role_grant_permissions($rid, $newPerms);
741 * Wrapper for og_membership creation.
745 * @param int $drupalID
748 public function og_membership_create($ogID, $drupalID) {
749 if (function_exists('og_entity_query_alter')) {
750 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
752 // @TODO Find more solid way to check - try system_get_info('module', 'og').
754 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
755 og_group('node', $ogID, ['entity' => user_load($drupalID)]);
758 // Works for the OG 7.x-1.x branch
759 og_group($ogID, ['entity' => user_load($drupalID)]);
764 * Wrapper for og_membership deletion.
768 * @param int $drupalID
771 public function og_membership_delete($ogID, $drupalID) {
772 if (function_exists('og_entity_query_alter')) {
773 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
774 // TODO: Find a more solid way to make this test
775 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
776 og_ungroup('node', $ogID, 'user', user_load($drupalID));
779 // Works for the OG 7.x-1.x branch
780 og_ungroup($ogID, 'user', user_load($drupalID));
787 public function getTimeZoneString() {
789 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
790 if (variable_get('configurable_timezones', 1) && $user->uid
&& isset($user->timezone
) && strlen($user->timezone
)) {
791 $timezone = $user->timezone
;
794 $timezone = variable_get('date_default_timezone', NULL);
797 $timezone = parent
::getTimeZoneString();
805 public function setHttpHeader($name, $value) {
806 drupal_add_http_header($name, $value);
812 public function synchronizeUsers() {
813 $config = CRM_Core_Config
::singleton();
814 if (PHP_SAPI
!= 'cli') {
821 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
823 $user = new StdClass();
824 $uf = $config->userFramework
;
827 $contactMatching = 0;
828 foreach ($result as $row) {
829 $user->$id = $row->$id;
830 $user->$mail = $row->$mail;
831 $user->$name = $row->$name;
833 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
839 if (is_object($match)) {
845 'contactCount' => $contactCount,
846 'contactMatching' => $contactMatching,
847 'contactCreated' => $contactCreated,
852 * Commit the session before exiting.
853 * Similar to drupal_exit().
855 public function onCiviExit() {
856 if (function_exists('module_invoke_all')) {
857 if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE
!= 'update') {
858 module_invoke_all('exit');
860 drupal_session_commit();