3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * Drupal specific stuff goes here
39 class CRM_Utils_System_Drupal
extends CRM_Utils_System_DrupalBase
{
44 public function createUser(&$params, $mail) {
45 $form_state = form_state_defaults();
47 $form_state['input'] = array(
48 'name' => $params['cms_name'],
49 'mail' => $params[$mail],
50 'op' => 'Create new account',
53 $admin = user_access('administer users');
54 if (!variable_get('user_email_verification', TRUE) ||
$admin) {
55 $form_state['input']['pass'] = array('pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']);
58 if (!empty($params['notify'])) {
59 $form_state['input']['notify'] = $params['notify'];
62 $form_state['rebuild'] = FALSE;
63 $form_state['programmed'] = TRUE;
64 $form_state['complete form'] = FALSE;
65 $form_state['method'] = 'post';
66 $form_state['build_info']['args'] = array();
68 * if we want to submit this form more than once in a process (e.g. create more than one user)
69 * we must force it to validate each time for this form. Otherwise it will not validate
70 * subsequent submissions and the manner in which the password is passed in will be invalid
72 $form_state['must_validate'] = TRUE;
73 $config = CRM_Core_Config
::singleton();
75 // we also need to redirect b
76 $config->inCiviCRM
= TRUE;
78 $form = drupal_retrieve_form('user_register_form', $form_state);
79 $form_state['process_input'] = 1;
80 $form_state['submitted'] = 1;
81 $form['#array_parents'] = array();
82 $form['#tree'] = FALSE;
83 drupal_process_form('user_register_form', $form, $form_state);
85 $config->inCiviCRM
= FALSE;
87 if (form_get_errors()) {
90 return $form_state['user']->uid
;
96 public function updateCMSName($ufID, $ufName) {
98 if (function_exists('user_load')) {
99 $user = user_load($ufID);
100 if ($user->mail
!= $ufName) {
101 user_save($user, array('mail' => $ufName));
102 $user = user_load($ufID);
108 * Check if username and email exists in the drupal db
110 * @param array $params
111 * Array of name and mail values.
112 * @param array $errors
114 * @param string $emailName
115 * Field label for the 'email'.
119 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
120 $config = CRM_Core_Config
::singleton();
122 $dao = new CRM_Core_DAO();
123 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
124 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
125 $errors = form_get_errors();
127 // unset drupal messages to avoid twice display of errors
128 unset($_SESSION['messages']);
131 if (!empty($params['name'])) {
132 if ($nameError = user_validate_name($params['name'])) {
133 $errors['cms_name'] = $nameError;
137 "SELECT uid FROM {users} WHERE name = :name",
138 array(':name' => $params['name'])
141 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
146 if (!empty($params['mail'])) {
147 if ($emailError = user_validate_mail($params['mail'])) {
148 $errors[$emailName] = $emailError;
152 "SELECT uid FROM {users} WHERE mail = :mail",
153 array(':mail' => $params['mail'])
156 $resetUrl = $config->userFrameworkBaseURL
. 'user/password';
157 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
158 array(1 => $params['mail'], 2 => $resetUrl)
168 public function getLoginURL($destination = '') {
169 $query = $destination ?
array('destination' => $destination) : array();
170 return url('user', array('query' => $query));
176 public function setTitle($title, $pageTitle = NULL) {
177 if (arg(0) == 'civicrm') {
182 drupal_set_title($pageTitle, PASS_THROUGH
);
189 public function appendBreadCrumb($breadCrumbs) {
190 $breadCrumb = drupal_get_breadcrumb();
192 if (is_array($breadCrumbs)) {
193 foreach ($breadCrumbs as $crumbs) {
194 if (stripos($crumbs['url'], 'id%%')) {
195 $args = array('cid', 'mid');
196 foreach ($args as $a) {
197 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
201 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
205 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
208 drupal_set_breadcrumb($breadCrumb);
214 public function resetBreadCrumb() {
216 drupal_set_breadcrumb($bc);
222 public function addHTMLHead($header) {
224 if (!empty($header)) {
225 $key = 'civi_' . ++
$count;
228 '#markup' => $header,
230 drupal_add_html_head($data, $key);
237 public function addScriptUrl($url, $region) {
238 $params = array('group' => JS_LIBRARY
, 'weight' => 10);
242 $params['scope'] = substr($region, 5);
248 // If the path is within the drupal directory we can use the more efficient 'file' setting
249 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
250 drupal_add_js($url, $params);
257 public function addScript($code, $region) {
258 $params = array('type' => 'inline', 'group' => JS_LIBRARY
, 'weight' => 10);
262 $params['scope'] = substr($region, 5);
268 drupal_add_js($code, $params);
275 public function addStyleUrl($url, $region) {
276 if ($region != 'html-header') {
280 // If the path is within the drupal directory we can use the more efficient 'file' setting
281 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
282 drupal_add_css($url, $params);
289 public function addStyle($code, $region) {
290 if ($region != 'html-header') {
293 $params = array('type' => 'inline');
294 drupal_add_css($code, $params);
301 public function mapConfigToSSL() {
303 $base_url = str_replace('http://', 'https://', $base_url);
309 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
310 require_once 'DB.php';
312 $config = CRM_Core_Config
::singleton();
314 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
315 if (DB
::isError($dbDrupal)) {
316 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
319 $account = $userUid = $userMail = NULL;
320 if ($loadCMSBootstrap) {
321 $bootStrapParams = array();
322 if ($name && $password) {
323 $bootStrapParams = array(
328 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
332 $userUid = $user->uid
;
333 $userMail = $user->mail
;
338 // SOAP cannot load drupal bootstrap and hence we do it the old way
339 // Contact CiviSMTP folks if we run into issues with this :)
340 $cmsPath = $config->userSystem
->cmsRootPath($realPath);
342 require_once "$cmsPath/includes/bootstrap.inc";
343 require_once "$cmsPath/includes/password.inc";
345 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
346 $name = $dbDrupal->escapeSimple($strtolower($name));
349 FROM {$config->userFrameworkUsersTableName} u
350 WHERE LOWER(u.name) = '$name'
354 $query = $dbDrupal->query($sql);
355 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
358 $fakeDrupalAccount = drupal_anonymous_user();
359 $fakeDrupalAccount->name
= $name;
360 $fakeDrupalAccount->pass
= $row['pass'];
361 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
362 if ($passwordCheck) {
363 $userUid = $row['uid'];
364 $userMail = $row['mail'];
369 if ($userUid && $userMail) {
370 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
371 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
375 return array($contactID, $userUid, mt_rand());
383 public function loadUser($username) {
386 $user = user_load_by_name($username);
388 if (empty($user->uid
)) {
393 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
395 // lets store contact id and user id in session
396 $session = CRM_Core_Session
::singleton();
397 $session->set('ufID', $uid);
398 $session->set('userID', $contact_id);
403 * Perform any post login activities required by the UF -
404 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
405 * calls hook_user op 'login' and generates a new session.
407 * @param array $params
409 * FIXME: Document values accepted/required by $params
411 public function userLoginFinalize($params = array()) {
412 user_login_finalize($params);
416 * Determine the native ID of the CMS user
418 * @param string $username
421 public function getUfId($username) {
422 $user = user_load_by_name($username);
423 if (empty($user->uid
)) {
432 public function logout() {
433 module_load_include('inc', 'user', 'user.pages');
434 return user_logout();
438 * Get the default location for CiviCRM blocks
442 public function getDefaultBlockLocation() {
443 return 'sidebar_first';
447 * Load drupal bootstrap
449 * @param array $params
450 * Either uid, or name & pass.
451 * @param bool $loadUser
452 * Boolean Require CMS user load.
453 * @param bool $throwError
454 * If true, print error on failure and exit.
455 * @param bool|string $realPath path to script
459 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
460 //take the cms root path.
461 $cmsPath = $this->cmsRootPath($realPath);
463 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
465 echo '<br />Sorry, could not locate bootstrap.inc\n';
470 // load drupal bootstrap
472 define('DRUPAL_ROOT', $cmsPath);
474 // For drupal multi-site CRM-11313
475 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
476 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
477 if (!empty($matches[1])) {
478 $_SERVER['HTTP_HOST'] = $matches[1];
481 require_once 'includes/bootstrap.inc';
482 // @ to suppress notices eg 'DRUPALFOO already defined'.
483 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
485 // explicitly setting error reporting, since we cannot handle drupal related notices
487 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
489 echo '<br />Sorry, could not load drupal bootstrap.';
495 // seems like we've bootstrapped drupal
496 $config = CRM_Core_Config
::singleton();
498 // lets also fix the clean url setting
500 $config->cleanURL
= (int) variable_get('clean_url', '0');
502 // we need to call the config hook again, since we now know
503 // all the modules that are listening on it, does not apply
504 // to J! and WP as yet
506 CRM_Utils_Hook
::config($config);
512 $uid = CRM_Utils_Array
::value('uid', $params);
514 //load user, we need to check drupal permissions.
515 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
516 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
519 $uid = user_authenticate($name, $pass);
522 echo '<br />Sorry, unrecognized username or password.';
531 $account = user_load($uid);
532 if ($account && $account->uid
) {
540 echo '<br />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);
558 public function cmsRootPath($scriptFilename = NULL) {
559 $cmsRoot = $valid = NULL;
561 if (!is_null($scriptFilename)) {
562 $path = $scriptFilename;
565 $path = $_SERVER['SCRIPT_FILENAME'];
568 if (function_exists('drush_get_context')) {
569 // drush anyway takes care of multisite install etc
570 return drush_get_context('DRUSH_DRUPAL_ROOT');
573 $pathVars = explode('/',
574 str_replace('//', '/',
575 str_replace('\\', '/', $path)
579 //lets store first var,
580 //need to get back for windows.
581 $firstVar = array_shift($pathVars);
583 //lets remove sript name to reduce one iteration.
584 array_pop($pathVars);
586 // CRM-7429 -- do check for uppermost 'includes' dir, which would
587 // work for multisite installation.
589 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
590 $cmsIncludePath = "$cmsRoot/includes";
591 // Stop if we find bootstrap.
592 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
596 //remove one directory level.
597 array_pop($pathVars);
598 } while (count($pathVars));
600 return ($valid) ?
$cmsRoot : NULL;
606 public function isUserLoggedIn() {
608 if (function_exists('user_is_logged_in')) {
609 $isloggedIn = user_is_logged_in();
618 public function getLoggedInUfID() {
620 if (function_exists('user_is_logged_in') &&
621 user_is_logged_in() &&
622 function_exists('user_uid_optional_to_arg')
624 $ufID = user_uid_optional_to_arg(array());
633 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
638 //CRM-7803 -from d7 onward.
639 $config = CRM_Core_Config
::singleton();
640 if (function_exists('variable_get') &&
641 module_exists('locale') &&
642 function_exists('language_negotiation_get')
646 //does user configuration allow language
647 //support from the URL (Path prefix or domain)
648 if (language_negotiation_get('language') == 'locale-url') {
649 $urlType = variable_get('locale_language_negotiation_url_part');
652 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
653 if (isset($language->prefix
) && $language->prefix
) {
654 if ($addLanguagePart) {
655 $url .= $language->prefix
. '/';
657 if ($removeLanguagePart) {
658 $url = str_replace("/{$language->prefix}/", '/', $url);
663 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
664 if (isset($language->domain
) && $language->domain
) {
665 if ($addLanguagePart) {
666 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain
);
667 // drupal function base_path() adds a "/" to the beginning and end of the returned path
668 if (substr($cleanedUrl, -1) == '/') {
669 $cleanedUrl = substr($cleanedUrl, 0, -1);
671 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $cleanedUrl . base_path();
673 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
674 $url = str_replace('\\', '/', $url);
675 $parseUrl = parse_url($url);
677 //kinda hackish but not sure how to do it right
678 //hope http_build_url() will help at some point.
679 if (is_array($parseUrl) && !empty($parseUrl)) {
680 $urlParts = explode('/', $url);
681 $hostKey = array_search($parseUrl['host'], $urlParts);
682 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
683 $urlParts[$hostKey] = $ufUrlParts['host'];
684 $url = implode('/', $urlParts);
696 * Find any users/roles/security-principals with the given permission
697 * and replace it with one or more permissions.
699 * @param string $oldPerm
700 * @param array $newPerms
705 public function replacePermission($oldPerm, $newPerms) {
706 $roles = user_roles(FALSE, $oldPerm);
707 if (!empty($roles)) {
708 foreach (array_keys($roles) as $rid) {
709 user_role_revoke_permissions($rid, array($oldPerm));
710 user_role_grant_permissions($rid, $newPerms);
716 * Get a list of all installed modules, including enabled and disabled ones
721 public function getModules() {
723 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
724 foreach ($q as $row) {
725 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
731 * Wrapper for og_membership creation
735 * @param int $drupalID
738 public function og_membership_create($ogID, $drupalID) {
739 if (function_exists('og_entity_query_alter')) {
740 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
742 // @TODO Find more solid way to check - try system_get_info('module', 'og').
744 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
745 og_group('node', $ogID, array('entity' => user_load($drupalID)));
748 // Works for the OG 7.x-1.x branch
749 og_group($ogID, array('entity' => user_load($drupalID)));
754 * Wrapper for og_membership deletion
758 * @param int $drupalID
761 public function og_membership_delete($ogID, $drupalID) {
762 if (function_exists('og_entity_query_alter')) {
763 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
764 // TODO: Find a more solid way to make this test
765 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
766 og_ungroup('node', $ogID, 'user', user_load($drupalID));
769 // Works for the OG 7.x-1.x branch
770 og_ungroup($ogID, 'user', user_load($drupalID));
777 public function getTimeZoneString() {
779 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
780 $timezone = $user->timezone
;
783 $timezone = variable_get('date_default_timezone', NULL);
786 $timezone = parent
::getTimeZoneString();