3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
37 * Drupal specific stuff goes here
39 class CRM_Utils_System_Drupal
extends CRM_Utils_System_DrupalBase
{
42 * Function to create a user in Drupal.
44 * @param array $params associated array
45 * @param string $mail email id for cms user
47 * @return uid if user exists, false otherwise
52 function createUser(&$params, $mail) {
53 $form_state = form_state_defaults();
55 $form_state['input'] = array(
56 'name' => $params['cms_name'],
57 'mail' => $params[$mail],
58 'op' => 'Create new account',
61 $admin = user_access('administer users');
62 if (!variable_get('user_email_verification', TRUE) ||
$admin) {
63 $form_state['input']['pass'] = array('pass1'=>$params['cms_pass'],'pass2'=>$params['cms_pass']);
66 if(!empty($params['notify'])){
67 $form_state['input']['notify'] = $params['notify'];
70 $form_state['rebuild'] = FALSE;
71 $form_state['programmed'] = TRUE;
72 $form_state['complete form'] = FALSE;
73 $form_state['method'] = 'post';
74 $form_state['build_info']['args'] = array();
76 * if we want to submit this form more than once in a process (e.g. create more than one user)
77 * we must force it to validate each time for this form. Otherwise it will not validate
78 * subsequent submissions and the manner in which the password is passed in will be invalid
80 $form_state['must_validate'] = TRUE;
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', $form_state);
87 $form_state['process_input'] = 1;
88 $form_state['submitted'] = 1;
89 $form['#array_parents'] = array();
90 $form['#tree'] = FALSE;
91 drupal_process_form('user_register_form', $form, $form_state);
93 $config->inCiviCRM
= FALSE;
95 if (form_get_errors()) {
98 return $form_state['user']->uid
;
102 * Change user name in host CMS
104 * @param integer $ufID User ID in CMS
105 * @param string $ufName User name
107 function updateCMSName($ufID, $ufName) {
109 if (function_exists('user_load')) {
110 $user = user_load($ufID);
111 if ($user->mail
!= $ufName) {
112 user_save($user, array('mail' => $ufName));
113 $user = user_load($ufID);
119 * Check if username and email exists in the drupal db
121 * @params $params array array of name and mail values
122 * @params $errors array array of errors
123 * @params $emailName string field label for the 'email'
127 static 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 $errors = form_get_errors();
135 // unset drupal messages to avoid twice display of errors
136 unset($_SESSION['messages']);
139 if (CRM_Utils_Array
::value('name', $params)) {
140 if ($nameError = user_validate_name($params['name'])) {
141 $errors['cms_name'] = $nameError;
145 "SELECT uid FROM {users} WHERE name = :name",
146 array(':name' => $params['name'])
149 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
154 if (CRM_Utils_Array
::value('mail', $params)) {
155 if ($emailError = user_validate_mail($params['mail'])) {
156 $errors[$emailName] = $emailError;
160 "SELECT uid FROM {users} WHERE mail = :mail",
161 array(':mail' => $params['mail'])
164 $resetUrl = $config->userFrameworkBaseURL
. 'user/password';
165 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
166 array(1 => $params['mail'], 2 => $resetUrl)
174 * Function to get the drupal destination string. When this is passed in the
175 * URL the user will be directed to it after filling in the drupal form
177 * @param object $form Form object representing the 'current' form - to which the user will be returned
178 * @return string $destination destination value for URL
181 function getLoginDestination(&$form) {
184 $id = $form->get('id');
189 $gid = $form->get('gid');
191 $args .= "&gid=$gid";
194 // Setup Personal Campaign Page link uses pageId
195 $pageId = $form->get('pageId');
197 $component = $form->get('component');
198 $args .= "&pageId=$pageId&component=$component&action=add";
205 // append destination so user is returned to form they came from after login
206 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
212 * Get user login URL for hosting CMS (method declared in each CMS system class)
214 * @param string $destination - if present, add destination to querystring (works for Drupal only)
216 * @return string - loginURL for the current CMS
219 public function getLoginURL($destination = '') {
220 $config = CRM_Core_Config
::singleton();
221 $loginURL = $config->userFrameworkBaseURL
;
223 if (!empty($destination)) {
224 // append destination so user is returned to form they came from after login
225 $loginURL .= '?destination=' . urlencode($destination);
232 * sets the title of the page
234 * @param string $title
235 * @paqram string $pageTitle
240 function setTitle($title, $pageTitle = NULL) {
241 if (arg(0) == 'civicrm') {
246 drupal_set_title($pageTitle, PASS_THROUGH
);
251 * Append an additional breadcrumb tag to the existing breadcrumb
253 * @param string $title
259 function appendBreadCrumb($breadCrumbs) {
260 $breadCrumb = drupal_get_breadcrumb();
262 if (is_array($breadCrumbs)) {
263 foreach ($breadCrumbs as $crumbs) {
264 if (stripos($crumbs['url'], 'id%%')) {
265 $args = array('cid', 'mid');
266 foreach ($args as $a) {
267 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
271 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
275 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
278 drupal_set_breadcrumb($breadCrumb);
282 * Reset an additional breadcrumb tag to the existing breadcrumb
287 function resetBreadCrumb() {
289 drupal_set_breadcrumb($bc);
293 * Append a string to the head of the html file
295 * @param string $header the new string to be appended
300 function addHTMLHead($header) {
302 if (!empty($header)) {
303 $key = 'civi_' . ++
$count;
306 '#markup' => $header,
308 drupal_add_html_head($data, $key);
315 * @param $url: string, absolute path to file
316 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
318 * Note: This function is not to be called directly
319 * @see CRM_Core_Region::render()
321 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
324 public function addScriptUrl($url, $region) {
325 $params = array('group' => JS_LIBRARY
, 'weight' => 10);
329 $params['scope'] = substr($region, 5);
334 // If the path is within the drupal directory we can use the more efficient 'file' setting
335 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
336 drupal_add_js($url, $params);
341 * Add an inline script
343 * @param $code: string, javascript code
344 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
346 * Note: This function is not to be called directly
347 * @see CRM_Core_Region::render()
349 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
352 public function addScript($code, $region) {
353 $params = array('type' => 'inline', 'group' => JS_LIBRARY
, 'weight' => 10);
357 $params['scope'] = substr($region, 5);
362 drupal_add_js($code, $params);
369 * @param $url: string, absolute path to file
370 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
372 * Note: This function is not to be called directly
373 * @see CRM_Core_Region::render()
375 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
378 public function addStyleUrl($url, $region) {
379 if ($region != 'html-header') {
383 // If the path is within the drupal directory we can use the more efficient 'file' setting
384 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
385 drupal_add_css($url, $params);
390 * Add an inline style
392 * @param $code: string, css code
393 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
395 * Note: This function is not to be called directly
396 * @see CRM_Core_Region::render()
398 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
401 public function addStyle($code, $region) {
402 if ($region != 'html-header') {
405 $params = array('type' => 'inline');
406 drupal_add_css($code, $params);
411 * rewrite various system urls to https
418 function mapConfigToSSL() {
420 $base_url = str_replace('http://', 'https://', $base_url);
424 * figure out the post url for the form
426 * @param mix $action the default action if one is pre-specified
428 * @return string the url to post the form
431 function postURL($action) {
432 if (!empty($action)) {
436 return $this->url($_GET['q']);
441 * Authenticate the user against the drupal db
443 * @param string $name the user name
444 * @param string $password the password for the above user name
445 * @param boolean $loadCMSBootstrap load cms bootstrap?
446 * @param NULL|string $realPath filename of script
448 * @return mixed false if no auth
450 * contactID, ufID, unique string ) if success
453 static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
454 require_once 'DB.php';
456 $config = CRM_Core_Config
::singleton();
458 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
459 if (DB
::isError($dbDrupal)) {
460 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
463 $account = $userUid = $userMail = NULL;
464 if ($loadCMSBootstrap) {
465 $bootStrapParams = array();
466 if ($name && $password) {
467 $bootStrapParams = array(
472 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
476 $userUid = $user->uid
;
477 $userMail = $user->mail
;
482 // SOAP cannot load drupal bootstrap and hence we do it the old way
483 // Contact CiviSMTP folks if we run into issues with this :)
484 $cmsPath = $config->userSystem
->cmsRootPath($realPath);
486 require_once ("$cmsPath/includes/bootstrap.inc");
487 require_once ("$cmsPath/includes/password.inc");
489 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
490 $name = $dbDrupal->escapeSimple($strtolower($name));
493 FROM {$config->userFrameworkUsersTableName} u
494 WHERE LOWER(u.name) = '$name'
498 $query = $dbDrupal->query($sql);
499 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
502 $fakeDrupalAccount = drupal_anonymous_user();
503 $fakeDrupalAccount->name
= $name;
504 $fakeDrupalAccount->pass
= $row['pass'];
505 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
506 if ($passwordCheck) {
507 $userUid = $row['uid'];
508 $userMail = $row['mail'];
513 if ($userUid && $userMail) {
514 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
515 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
519 return array($contactID, $userUid, mt_rand());
525 * Load user into session
527 function loadUser($username) {
530 $user = user_load_by_name($username);
532 if (empty($user->uid
)) {
537 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
539 // lets store contact id and user id in session
540 $session = CRM_Core_Session
::singleton();
541 $session->set('ufID', $uid);
542 $session->set('userID', $contact_id);
547 * Perform any post login activities required by the UF -
548 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
549 * calls hook_user op 'login' and generates a new session.
551 * @param array params
553 * FIXME: Document values accepted/required by $params
555 function userLoginFinalize($params = array()){
556 user_login_finalize($params);
560 * Determine the native ID of the CMS user
565 function getUfId($username) {
566 $user = user_load_by_name($username);
567 if (empty($user->uid
)) {
574 * Set a message in the UF to display to a user
576 * @param string $message the message to set
580 function setMessage($message) {
581 drupal_set_message($message);
584 function permissionDenied() {
585 drupal_access_denied();
589 module_load_include('inc', 'user', 'user.pages');
590 return user_logout();
593 function updateCategories() {
594 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
601 * Get the default location for CiviCRM blocks
605 function getDefaultBlockLocation() {
606 return 'sidebar_first';
610 * Get the locale set in the hosting CMS
612 * @return string with the locale or null for none
614 function getUFLocale() {
615 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
616 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
617 // sometimes for CLI based on order called, this might not be set and/or empty
620 if (empty($language)) {
624 if ($language->language
== 'zh-hans') {
628 if ($language->language
== 'zh-hant') {
632 if (preg_match('/^.._..$/', $language->language
)) {
633 return $language->language
;
636 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
639 function getVersion() {
640 return defined('VERSION') ? VERSION
: 'Unknown';
644 * load drupal bootstrap
646 * @param array $params Either uid, or name & pass.
647 * @param boolean $loadUser boolean Require CMS user load.
648 * @param boolean $throwError If true, print error on failure and exit.
649 * @param boolean|string $realPath path to script
651 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
652 //take the cms root path.
653 $cmsPath = $this->cmsRootPath($realPath);
655 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
657 echo '<br />Sorry, could not locate bootstrap.inc\n';
662 // load drupal bootstrap
664 define('DRUPAL_ROOT', $cmsPath);
666 // For drupal multi-site CRM-11313
667 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
668 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
669 if (!empty($matches[1])) {
670 $_SERVER['HTTP_HOST'] = $matches[1];
673 require_once 'includes/bootstrap.inc';
674 // @ to suppress notices eg 'DRUPALFOO already defined'.
675 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
677 // explicitly setting error reporting, since we cannot handle drupal related notices
679 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
681 echo '<br />Sorry, could not load drupal bootstrap.';
687 // seems like we've bootstrapped drupal
688 $config = CRM_Core_Config
::singleton();
690 // lets also fix the clean url setting
692 $config->cleanURL
= (int) variable_get('clean_url', '0');
694 // we need to call the config hook again, since we now know
695 // all the modules that are listening on it, does not apply
696 // to J! and WP as yet
698 CRM_Utils_Hook
::config($config);
704 $uid = CRM_Utils_Array
::value('uid', $params);
706 //load user, we need to check drupal permissions.
707 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
708 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
711 $uid = user_authenticate($name, $pass);
714 echo '<br />Sorry, unrecognized username or password.';
723 $account = user_load($uid);
724 if ($account && $account->uid
) {
732 echo '<br />Sorry, can not load CMS user account.';
736 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
737 // which means that define(CIVICRM_CLEANURL) was correctly set.
739 $config = CRM_Core_Config
::singleton();
740 $config->cleanURL
= (int)variable_get('clean_url', '0');
742 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
743 CRM_Utils_Hook
::config($config);
751 function cmsRootPath($scriptFilename = NULL) {
752 $cmsRoot = $valid = NULL;
754 if (!is_null($scriptFilename)) {
755 $path = $scriptFilename;
758 $path = $_SERVER['SCRIPT_FILENAME'];
761 if (function_exists('drush_get_context')) {
762 // drush anyway takes care of multisite install etc
763 return drush_get_context('DRUSH_DRUPAL_ROOT');
766 $pathVars = explode('/',
767 str_replace('//', '/',
768 str_replace('\\', '/', $path)
772 //lets store first var,
773 //need to get back for windows.
774 $firstVar = array_shift($pathVars);
776 //lets remove sript name to reduce one iteration.
777 array_pop($pathVars);
779 //CRM-7429 --do check for upper most 'includes' dir,
780 //which would effectually work for multisite installation.
782 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
783 $cmsIncludePath = "$cmsRoot/includes";
784 //stop as we found bootstrap.
785 if (@opendir
($cmsIncludePath) &&
786 file_exists("$cmsIncludePath/bootstrap.inc")
791 //remove one directory level.
792 array_pop($pathVars);
793 } while (count($pathVars));
795 return ($valid) ?
$cmsRoot : NULL;
799 * check is user logged in.
801 * @return boolean true/false.
803 public function isUserLoggedIn() {
805 if (function_exists('user_is_logged_in')) {
806 $isloggedIn = user_is_logged_in();
813 * Get currently logged in user uf id.
815 * @return int $userID logged in user uf id.
817 public function getLoggedInUfID() {
819 if (function_exists('user_is_logged_in') &&
820 user_is_logged_in() &&
821 function_exists('user_uid_optional_to_arg')
823 $ufID = user_uid_optional_to_arg(array());
830 * Format the url as per language Negotiation.
834 * @return string $url, formatted url.
837 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
842 //CRM-7803 -from d7 onward.
843 $config = CRM_Core_Config
::singleton();
844 if (function_exists('variable_get') &&
845 module_exists('locale') &&
846 function_exists('language_negotiation_get')
850 //does user configuration allow language
851 //support from the URL (Path prefix or domain)
852 if (language_negotiation_get('language') == 'locale-url') {
853 $urlType = variable_get('locale_language_negotiation_url_part');
856 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
857 if (isset($language->prefix
) && $language->prefix
) {
858 if ($addLanguagePart) {
859 $url .= $language->prefix
. '/';
861 if ($removeLanguagePart) {
862 $url = str_replace("/{$language->prefix}/", '/', $url);
867 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
868 if (isset($language->domain
) && $language->domain
) {
869 if ($addLanguagePart) {
870 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $language->domain
. base_path();
872 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
873 $url = str_replace('\\', '/', $url);
874 $parseUrl = parse_url($url);
876 //kinda hackish but not sure how to do it right
877 //hope http_build_url() will help at some point.
878 if (is_array($parseUrl) && !empty($parseUrl)) {
879 $urlParts = explode('/', $url);
880 $hostKey = array_search($parseUrl['host'], $urlParts);
881 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
882 $urlParts[$hostKey] = $ufUrlParts['host'];
883 $url = implode('/', $urlParts);
895 * Find any users/roles/security-principals with the given permission
896 * and replace it with one or more permissions.
898 * @param $oldPerm string
899 * @param $newPerms array, strings
903 function replacePermission($oldPerm, $newPerms) {
904 $roles = user_roles(FALSE, $oldPerm);
905 if (!empty($roles)) {
906 foreach (array_keys($roles) as $rid) {
907 user_role_revoke_permissions($rid, array($oldPerm));
908 user_role_grant_permissions($rid, $newPerms);
914 * Get a list of all installed modules, including enabled and disabled ones
916 * @return array CRM_Core_Module
918 function getModules() {
920 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
921 foreach ($q as $row) {
922 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
928 * Wrapper for og_membership creation
930 * @param integer $ogID Organic Group ID
931 * @param integer $drupalID drupal User ID
933 function og_membership_create($ogID, $drupalID){
934 if (function_exists('og_entity_query_alter')) {
935 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
937 // @TODO Find more solid way to check - try system_get_info('module', 'og').
939 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
940 og_group('node', $ogID, array('entity' => user_load($drupalID)));
943 // Works for the OG 7.x-1.x branch
944 og_group($ogID, array('entity' => user_load($drupalID)));
949 * Wrapper for og_membership deletion
951 * @param integer $ogID Organic Group ID
952 * @param integer $drupalID drupal User ID
954 function og_membership_delete($ogID, $drupalID) {
955 if (function_exists('og_entity_query_alter')) {
956 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
957 // TODO: Find a more solid way to make this test
958 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
959 og_ungroup('node', $ogID, 'user', user_load($drupalID));
961 // Works for the OG 7.x-1.x branch
962 og_ungroup($ogID, 'user', user_load($drupalID));
967 * Get timezone from Drupal
968 * @return boolean|string
970 function getTimeZoneOffset(){
972 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
973 $timezone = $user->timezone
;
975 $timezone = variable_get('date_default_timezone', null);
977 $tzObj = new DateTimeZone($timezone);
978 $dateTime = new DateTime("now", $tzObj);
979 $tz = $tzObj->getOffset($dateTime);
985 $timeZoneOffset = sprintf("%02d:%02d", $tz / 3600, abs(($tz/60)%60
));
987 if($timeZoneOffset > 0){
988 $timeZoneOffset = '+' . $timeZoneOffset;
990 return $timeZoneOffset;
993 * Reset any system caches that may be required for proper CiviCRM
997 drupal_flush_all_caches();