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 = array();
54 $form_state['input'] = array(
55 'name' => $params['cms_name'],
56 'mail' => $params[$mail],
57 'op' => 'Create new account',
60 $admin = user_access('administer users');
61 if (!variable_get('user_email_verification', TRUE) ||
$admin) {
62 $form_state['input']['pass'] = array('pass1'=>$params['cms_pass'],'pass2'=>$params['cms_pass']);
65 if(!empty($params['notify'])){
66 $form_state['input']['notify'] = $params['notify'];
69 $form_state['rebuild'] = FALSE;
70 $form_state['programmed'] = TRUE;
71 $form_state['complete form'] = FALSE;
72 $form_state['method'] = 'post';
73 $form_state['build_info']['args'] = array();
75 * if we want to submit this form more than once in a process (e.g. create more than one user)
76 * we must force it to validate each time for this form. Otherwise it will not validate
77 * subsequent submissions and the manner in which the password is passed in will be invalid
79 $form_state['must_validate'] = TRUE;
80 $config = CRM_Core_Config
::singleton();
82 // we also need to redirect b
83 $config->inCiviCRM
= TRUE;
85 $form = drupal_retrieve_form('user_register_form', $form_state);
86 $form_state['process_input'] = 1;
87 $form_state['submitted'] = 1;
88 $form['#array_parents'] = array();
89 $form['#tree'] = FALSE;
90 drupal_process_form('user_register_form', $form, $form_state);
92 $config->inCiviCRM
= FALSE;
94 if (form_get_errors()) {
97 return $form_state['user']->uid
;
101 * Change user name in host CMS
103 * @param integer $ufID User ID in CMS
104 * @param string $ufName User name
106 function updateCMSName($ufID, $ufName) {
108 if (function_exists('user_load')) {
109 $user = user_load($ufID);
110 if ($user->mail
!= $ufName) {
111 user_save($user, array('mail' => $ufName));
112 $user = user_load($ufID);
118 * Check if username and email exists in the drupal db
120 * @params $params array array of name and mail values
121 * @params $errors array array of errors
122 * @params $emailName string field label for the 'email'
126 static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
127 $config = CRM_Core_Config
::singleton();
129 $dao = new CRM_Core_DAO();
130 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
131 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
132 $errors = form_get_errors();
134 // unset drupal messages to avoid twice display of errors
135 unset($_SESSION['messages']);
138 if (CRM_Utils_Array
::value('name', $params)) {
139 if ($nameError = user_validate_name($params['name'])) {
140 $errors['cms_name'] = $nameError;
144 "SELECT uid FROM {users} WHERE name = :name",
145 array(':name' => $params['name'])
148 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
153 if (CRM_Utils_Array
::value('mail', $params)) {
154 if ($emailError = user_validate_mail($params['mail'])) {
155 $errors[$emailName] = $emailError;
159 "SELECT uid FROM {users} WHERE mail = :mail",
160 array(':mail' => $params['mail'])
163 $resetUrl = $config->userFrameworkBaseURL
. 'user/password';
164 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
165 array(1 => $params['mail'], 2 => $resetUrl)
173 * Function to get the drupal destination string. When this is passed in the
174 * URL the user will be directed to it after filling in the drupal form
176 * @param object $form Form object representing the 'current' form - to which the user will be returned
177 * @return string $destination destination value for URL
180 function getLoginDestination(&$form) {
183 $id = $form->get('id');
188 $gid = $form->get('gid');
190 $args .= "&gid=$gid";
193 // Setup Personal Campaign Page link uses pageId
194 $pageId = $form->get('pageId');
196 $component = $form->get('component');
197 $args .= "&pageId=$pageId&component=$component&action=add";
204 // append destination so user is returned to form they came from after login
205 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
211 * Get user login URL for hosting CMS (method declared in each CMS system class)
213 * @param string $destination - if present, add destination to querystring (works for Drupal only)
215 * @return string - loginURL for the current CMS
218 public function getLoginURL($destination = '') {
219 $config = CRM_Core_Config
::singleton();
220 $loginURL = $config->userFrameworkBaseURL
;
222 if (!empty($destination)) {
223 // append destination so user is returned to form they came from after login
224 $loginURL .= '?destination=' . urlencode($destination);
231 * sets the title of the page
233 * @param string $title
234 * @paqram string $pageTitle
239 function setTitle($title, $pageTitle = NULL) {
240 if (arg(0) == 'civicrm') {
245 drupal_set_title($pageTitle, PASS_THROUGH
);
250 * Append an additional breadcrumb tag to the existing breadcrumb
252 * @param string $title
258 function appendBreadCrumb($breadCrumbs) {
259 $breadCrumb = drupal_get_breadcrumb();
261 if (is_array($breadCrumbs)) {
262 foreach ($breadCrumbs as $crumbs) {
263 if (stripos($crumbs['url'], 'id%%')) {
264 $args = array('cid', 'mid');
265 foreach ($args as $a) {
266 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
270 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
274 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
277 drupal_set_breadcrumb($breadCrumb);
281 * Reset an additional breadcrumb tag to the existing breadcrumb
286 function resetBreadCrumb() {
288 drupal_set_breadcrumb($bc);
292 * Append a string to the head of the html file
294 * @param string $header the new string to be appended
299 function addHTMLHead($header) {
301 if (!empty($header)) {
302 $key = 'civi_' . ++
$count;
305 '#markup' => $header,
307 drupal_add_html_head($data, $key);
314 * @param $url: string, absolute path to file
315 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
317 * Note: This function is not to be called directly
318 * @see CRM_Core_Region::render()
320 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
323 public function addScriptUrl($url, $region) {
324 $params = array('group' => JS_LIBRARY
, 'weight' => 10);
328 $params['scope'] = substr($region, 5);
333 // If the path is within the drupal directory we can use the more efficient 'file' setting
334 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
335 drupal_add_js($url, $params);
340 * Add an inline script
342 * @param $code: string, javascript code
343 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
345 * Note: This function is not to be called directly
346 * @see CRM_Core_Region::render()
348 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
351 public function addScript($code, $region) {
352 $params = array('type' => 'inline', 'group' => JS_LIBRARY
, 'weight' => 10);
356 $params['scope'] = substr($region, 5);
361 drupal_add_js($code, $params);
368 * @param $url: string, absolute path to file
369 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
371 * Note: This function is not to be called directly
372 * @see CRM_Core_Region::render()
374 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
377 public function addStyleUrl($url, $region) {
378 if ($region != 'html-header') {
382 // If the path is within the drupal directory we can use the more efficient 'file' setting
383 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
384 drupal_add_css($url, $params);
389 * Add an inline style
391 * @param $code: string, css code
392 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
394 * Note: This function is not to be called directly
395 * @see CRM_Core_Region::render()
397 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
400 public function addStyle($code, $region) {
401 if ($region != 'html-header') {
404 $params = array('type' => 'inline');
405 drupal_add_css($code, $params);
410 * rewrite various system urls to https
417 function mapConfigToSSL() {
419 $base_url = str_replace('http://', 'https://', $base_url);
423 * figure out the post url for the form
425 * @param mix $action the default action if one is pre-specified
427 * @return string the url to post the form
430 function postURL($action) {
431 if (!empty($action)) {
435 return $this->url($_GET['q']);
440 * Authenticate the user against the drupal db
442 * @param string $name the user name
443 * @param string $password the password for the above user name
444 * @param boolean $loadCMSBootstrap load cms bootstrap?
445 * @param NULL|string $realPath filename of script
447 * @return mixed false if no auth
449 * contactID, ufID, unique string ) if success
452 static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
453 require_once 'DB.php';
455 $config = CRM_Core_Config
::singleton();
457 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
458 if (DB
::isError($dbDrupal)) {
459 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
462 $account = $userUid = $userMail = NULL;
463 if ($loadCMSBootstrap) {
464 $bootStrapParams = array();
465 if ($name && $password) {
466 $bootStrapParams = array(
471 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
475 $userUid = $user->uid
;
476 $userMail = $user->mail
;
481 // SOAP cannot load drupal bootstrap and hence we do it the old way
482 // Contact CiviSMTP folks if we run into issues with this :)
483 $cmsPath = $config->userSystem
->cmsRootPath($realPath);
485 require_once ("$cmsPath/includes/bootstrap.inc");
486 require_once ("$cmsPath/includes/password.inc");
488 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
489 $name = $dbDrupal->escapeSimple($strtolower($name));
492 FROM {$config->userFrameworkUsersTableName} u
493 WHERE LOWER(u.name) = '$name'
497 $query = $dbDrupal->query($sql);
498 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
501 $fakeDrupalAccount = drupal_anonymous_user();
502 $fakeDrupalAccount->name
= $name;
503 $fakeDrupalAccount->pass
= $row['pass'];
504 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
505 if ($passwordCheck) {
506 $userUid = $row['uid'];
507 $userMail = $row['mail'];
512 if ($userUid && $userMail) {
513 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
514 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
518 return array($contactID, $userUid, mt_rand());
524 * Load user into session
526 function loadUser($username) {
529 $user = user_load_by_name($username);
531 if (empty($user->uid
)) {
536 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
538 // lets store contact id and user id in session
539 $session = CRM_Core_Session
::singleton();
540 $session->set('ufID', $uid);
541 $session->set('userID', $contact_id);
546 * Perform any post login activities required by the UF -
547 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
548 * calls hook_user op 'login' and generates a new session.
550 * @param array params
552 * FIXME: Document values accepted/required by $params
554 function userLoginFinalize($params = array()){
555 user_login_finalize($params);
559 * Determine the native ID of the CMS user
564 function getUfId($username) {
565 $user = user_load_by_name($username);
566 if (empty($user->uid
)) {
573 * Set a message in the UF to display to a user
575 * @param string $message the message to set
579 function setMessage($message) {
580 drupal_set_message($message);
583 function permissionDenied() {
584 drupal_access_denied();
588 module_load_include('inc', 'user', 'user.pages');
589 return user_logout();
592 function updateCategories() {
593 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
600 * Get the default location for CiviCRM blocks
604 function getDefaultBlockLocation() {
605 return 'sidebar_first';
609 * Get the locale set in the hosting CMS
611 * @return string with the locale or null for none
613 function getUFLocale() {
614 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
615 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
616 // sometimes for CLI based on order called, this might not be set and/or empty
619 if (empty($language)) {
623 if ($language->language
== 'zh-hans') {
627 if ($language->language
== 'zh-hant') {
631 if (preg_match('/^.._..$/', $language->language
)) {
632 return $language->language
;
635 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
638 function getVersion() {
639 return defined('VERSION') ? VERSION
: 'Unknown';
643 * load drupal bootstrap
645 * @param array $params Either uid, or name & pass.
646 * @param boolean $loadUser boolean Require CMS user load.
647 * @param boolean $throwError If true, print error on failure and exit.
648 * @param boolean|string $realPath path to script
650 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
651 //take the cms root path.
652 $cmsPath = $this->cmsRootPath($realPath);
654 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
656 echo '<br />Sorry, could not locate bootstrap.inc\n';
661 // load drupal bootstrap
663 define('DRUPAL_ROOT', $cmsPath);
665 // For drupal multi-site CRM-11313
666 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
667 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
668 if (!empty($matches[1])) {
669 $_SERVER['HTTP_HOST'] = $matches[1];
672 require_once 'includes/bootstrap.inc';
673 // @ to suppress notices eg 'DRUPALFOO already defined'.
674 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
676 // explicitly setting error reporting, since we cannot handle drupal related notices
678 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
680 echo '<br />Sorry, could not load drupal bootstrap.';
686 // seems like we've bootstrapped drupal
687 $config = CRM_Core_Config
::singleton();
689 // lets also fix the clean url setting
691 $config->cleanURL
= (int) variable_get('clean_url', '0');
693 // we need to call the config hook again, since we now know
694 // all the modules that are listening on it, does not apply
695 // to J! and WP as yet
697 CRM_Utils_Hook
::config($config);
703 $uid = CRM_Utils_Array
::value('uid', $params);
705 //load user, we need to check drupal permissions.
706 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
707 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
710 $uid = user_authenticate($name, $pass);
713 echo '<br />Sorry, unrecognized username or password.';
722 $account = user_load($uid);
723 if ($account && $account->uid
) {
731 echo '<br />Sorry, can not load CMS user account.';
735 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
736 // which means that define(CIVICRM_CLEANURL) was correctly set.
738 $config = CRM_Core_Config
::singleton();
739 $config->cleanURL
= (int)variable_get('clean_url', '0');
741 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
742 CRM_Utils_Hook
::config($config);
750 function cmsRootPath($scriptFilename = NULL) {
751 $cmsRoot = $valid = NULL;
753 if (!is_null($scriptFilename)) {
754 $path = $scriptFilename;
757 $path = $_SERVER['SCRIPT_FILENAME'];
760 if (function_exists('drush_get_context')) {
761 // drush anyway takes care of multisite install etc
762 return drush_get_context('DRUSH_DRUPAL_ROOT');
765 $pathVars = explode('/',
766 str_replace('//', '/',
767 str_replace('\\', '/', $path)
771 //lets store first var,
772 //need to get back for windows.
773 $firstVar = array_shift($pathVars);
775 //lets remove sript name to reduce one iteration.
776 array_pop($pathVars);
778 //CRM-7429 --do check for upper most 'includes' dir,
779 //which would effectually work for multisite installation.
781 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
782 $cmsIncludePath = "$cmsRoot/includes";
783 //stop as we found bootstrap.
784 if (@opendir
($cmsIncludePath) &&
785 file_exists("$cmsIncludePath/bootstrap.inc")
790 //remove one directory level.
791 array_pop($pathVars);
792 } while (count($pathVars));
794 return ($valid) ?
$cmsRoot : NULL;
798 * check is user logged in.
800 * @return boolean true/false.
802 public function isUserLoggedIn() {
804 if (function_exists('user_is_logged_in')) {
805 $isloggedIn = user_is_logged_in();
812 * Get currently logged in user uf id.
814 * @return int $userID logged in user uf id.
816 public function getLoggedInUfID() {
818 if (function_exists('user_is_logged_in') &&
819 user_is_logged_in() &&
820 function_exists('user_uid_optional_to_arg')
822 $ufID = user_uid_optional_to_arg(array());
829 * Format the url as per language Negotiation.
833 * @return string $url, formatted url.
836 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
841 //CRM-7803 -from d7 onward.
842 $config = CRM_Core_Config
::singleton();
843 if (function_exists('variable_get') &&
844 module_exists('locale') &&
845 function_exists('language_negotiation_get')
849 //does user configuration allow language
850 //support from the URL (Path prefix or domain)
851 if (language_negotiation_get('language') == 'locale-url') {
852 $urlType = variable_get('locale_language_negotiation_url_part');
855 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
856 if (isset($language->prefix
) && $language->prefix
) {
857 if ($addLanguagePart) {
858 $url .= $language->prefix
. '/';
860 if ($removeLanguagePart) {
861 $url = str_replace("/{$language->prefix}/", '/', $url);
866 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
867 if (isset($language->domain
) && $language->domain
) {
868 if ($addLanguagePart) {
869 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $language->domain
. base_path();
871 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
872 $url = str_replace('\\', '/', $url);
873 $parseUrl = parse_url($url);
875 //kinda hackish but not sure how to do it right
876 //hope http_build_url() will help at some point.
877 if (is_array($parseUrl) && !empty($parseUrl)) {
878 $urlParts = explode('/', $url);
879 $hostKey = array_search($parseUrl['host'], $urlParts);
880 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
881 $urlParts[$hostKey] = $ufUrlParts['host'];
882 $url = implode('/', $urlParts);
894 * Find any users/roles/security-principals with the given permission
895 * and replace it with one or more permissions.
897 * @param $oldPerm string
898 * @param $newPerms array, strings
902 function replacePermission($oldPerm, $newPerms) {
903 $roles = user_roles(FALSE, $oldPerm);
904 if (!empty($roles)) {
905 foreach (array_keys($roles) as $rid) {
906 user_role_revoke_permissions($rid, array($oldPerm));
907 user_role_grant_permissions($rid, $newPerms);
913 * Get a list of all installed modules, including enabled and disabled ones
915 * @return array CRM_Core_Module
917 function getModules() {
919 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
920 foreach ($q as $row) {
921 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
927 * Wrapper for og_membership creation
929 * @param integer $ogID Organic Group ID
930 * @param integer $drupalID drupal User ID
932 function og_membership_create($ogID, $drupalID){
933 if (function_exists('og_entity_query_alter')) {
934 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
936 // @TODO Find more solid way to check - try system_get_info('module', 'og').
938 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
939 og_group('node', $ogID, array('entity' => user_load($drupalID)));
942 // Works for the OG 7.x-1.x branch
943 og_group($ogID, array('entity' => user_load($drupalID)));
948 * Wrapper for og_membership deletion
950 * @param integer $ogID Organic Group ID
951 * @param integer $drupalID drupal User ID
953 function og_membership_delete($ogID, $drupalID) {
954 if (function_exists('og_entity_query_alter')) {
955 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
956 // TODO: Find a more solid way to make this test
957 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
958 og_ungroup('node', $ogID, 'user', user_load($drupalID));
960 // Works for the OG 7.x-1.x branch
961 og_ungroup($ogID, 'user', user_load($drupalID));
966 * Get timezone from Drupal
967 * @return boolean|string
969 function getTimeZoneOffset(){
971 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
972 $timezone = $user->timezone
;
974 $timezone = variable_get('date_default_timezone', null);
976 $tzObj = new DateTimeZone($timezone);
977 $dateTime = new DateTime("now", $tzObj);
978 $tz = $tzObj->getOffset($dateTime);
984 $timeZoneOffset = sprintf("%02d:%02d", $tz / 3600, ($tz/60)%60
);
986 if($timeZoneOffset > 0){
987 $timeZoneOffset = '+' . $timeZoneOffset;
989 return $timeZoneOffset;
992 * Reset any system caches that may be required for proper CiviCRM
996 drupal_flush_all_caches();