3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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
{
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
111 function updateCMSName($ufID, $ufName) {
113 if (function_exists('user_load')) {
114 $user = user_load($ufID);
115 if ($user->mail
!= $ufName) {
116 user_save($user, array('mail' => $ufName));
117 $user = user_load($ufID);
123 * Check if username and email exists in the drupal db
125 * @params $params array array of name and mail values
126 * @params $errors array array of errors
127 * @params $emailName string field label for the 'email'
131 * @param string $emailName
135 static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
136 $config = CRM_Core_Config
::singleton();
138 $dao = new CRM_Core_DAO();
139 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
140 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
141 $errors = form_get_errors();
143 // unset drupal messages to avoid twice display of errors
144 unset($_SESSION['messages']);
147 if (!empty($params['name'])) {
148 if ($nameError = user_validate_name($params['name'])) {
149 $errors['cms_name'] = $nameError;
153 "SELECT uid FROM {users} WHERE name = :name",
154 array(':name' => $params['name'])
157 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
162 if (!empty($params['mail'])) {
163 if ($emailError = user_validate_mail($params['mail'])) {
164 $errors[$emailName] = $emailError;
168 "SELECT uid FROM {users} WHERE mail = :mail",
169 array(':mail' => $params['mail'])
172 $resetUrl = $config->userFrameworkBaseURL
. 'user/password';
173 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
174 array(1 => $params['mail'], 2 => $resetUrl)
182 * Function to get the drupal destination string. When this is passed in the
183 * URL the user will be directed to it after filling in the drupal form
185 * @param object $form Form object representing the 'current' form - to which the user will be returned
186 * @return string $destination destination value for URL
192 * @return null|string
194 function getLoginDestination(&$form) {
197 $id = $form->get('id');
202 $gid = $form->get('gid');
204 $args .= "&gid=$gid";
207 // Setup Personal Campaign Page link uses pageId
208 $pageId = $form->get('pageId');
210 $component = $form->get('component');
211 $args .= "&pageId=$pageId&component=$component&action=add";
218 // append destination so user is returned to form they came from after login
219 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
225 * Get user login URL for hosting CMS (method declared in each CMS system class)
227 * @param string $destination - if present, add destination to querystring (works for Drupal only)
229 * @return string - loginURL for the current CMS
232 public function getLoginURL($destination = '') {
233 $query = $destination ?
array('destination' => $destination) : array();
234 return url('user', array('query' => $query));
239 * sets the title of the page
241 * @param string $title
242 * @param null $pageTitle
244 * @paqram string $pageTitle
249 function setTitle($title, $pageTitle = NULL) {
250 if (arg(0) == 'civicrm') {
255 drupal_set_title($pageTitle, PASS_THROUGH
);
260 * Append an additional breadcrumb tag to the existing breadcrumb
262 * @param $breadCrumbs
264 * @internal param string $title
265 * @internal param string $url
270 function appendBreadCrumb($breadCrumbs) {
271 $breadCrumb = drupal_get_breadcrumb();
273 if (is_array($breadCrumbs)) {
274 foreach ($breadCrumbs as $crumbs) {
275 if (stripos($crumbs['url'], 'id%%')) {
276 $args = array('cid', 'mid');
277 foreach ($args as $a) {
278 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
282 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
286 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
289 drupal_set_breadcrumb($breadCrumb);
293 * Reset an additional breadcrumb tag to the existing breadcrumb
298 function resetBreadCrumb() {
300 drupal_set_breadcrumb($bc);
304 * Append a string to the head of the html file
306 * @param string $header the new string to be appended
311 function addHTMLHead($header) {
313 if (!empty($header)) {
314 $key = 'civi_' . ++
$count;
317 '#markup' => $header,
319 drupal_add_html_head($data, $key);
326 * @param $url: string, absolute path to file
327 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
329 * Note: This function is not to be called directly
330 * @see CRM_Core_Region::render()
332 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
335 public function addScriptUrl($url, $region) {
336 $params = array('group' => JS_LIBRARY
, 'weight' => 10);
340 $params['scope'] = substr($region, 5);
345 // If the path is within the drupal directory we can use the more efficient 'file' setting
346 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
347 drupal_add_js($url, $params);
352 * Add an inline script
354 * @param $code: string, javascript code
355 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
357 * Note: This function is not to be called directly
358 * @see CRM_Core_Region::render()
360 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
363 public function addScript($code, $region) {
364 $params = array('type' => 'inline', 'group' => JS_LIBRARY
, 'weight' => 10);
368 $params['scope'] = substr($region, 5);
373 drupal_add_js($code, $params);
380 * @param $url: string, absolute path to file
381 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
383 * Note: This function is not to be called directly
384 * @see CRM_Core_Region::render()
386 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
389 public function addStyleUrl($url, $region) {
390 if ($region != 'html-header') {
394 // If the path is within the drupal directory we can use the more efficient 'file' setting
395 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
396 drupal_add_css($url, $params);
401 * Add an inline style
403 * @param $code: string, css code
404 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
406 * Note: This function is not to be called directly
407 * @see CRM_Core_Region::render()
409 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
412 public function addStyle($code, $region) {
413 if ($region != 'html-header') {
416 $params = array('type' => 'inline');
417 drupal_add_css($code, $params);
422 * rewrite various system urls to https
429 function mapConfigToSSL() {
431 $base_url = str_replace('http://', 'https://', $base_url);
435 * figure out the post url for the form
437 * @param mix $action the default action if one is pre-specified
439 * @return string the url to post the form
442 function postURL($action) {
443 if (!empty($action)) {
447 return $this->url($_GET['q']);
452 * Authenticate the user against the drupal db
454 * @param string $name the user name
455 * @param string $password the password for the above user name
456 * @param boolean $loadCMSBootstrap load cms bootstrap?
457 * @param NULL|string $realPath filename of script
459 * @return mixed false if no auth
461 * contactID, ufID, unique string ) if success
464 static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
465 require_once 'DB.php';
467 $config = CRM_Core_Config
::singleton();
469 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
470 if (DB
::isError($dbDrupal)) {
471 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
474 $account = $userUid = $userMail = NULL;
475 if ($loadCMSBootstrap) {
476 $bootStrapParams = array();
477 if ($name && $password) {
478 $bootStrapParams = array(
483 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
487 $userUid = $user->uid
;
488 $userMail = $user->mail
;
493 // SOAP cannot load drupal bootstrap and hence we do it the old way
494 // Contact CiviSMTP folks if we run into issues with this :)
495 $cmsPath = $config->userSystem
->cmsRootPath($realPath);
497 require_once ("$cmsPath/includes/bootstrap.inc");
498 require_once ("$cmsPath/includes/password.inc");
500 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
501 $name = $dbDrupal->escapeSimple($strtolower($name));
504 FROM {$config->userFrameworkUsersTableName} u
505 WHERE LOWER(u.name) = '$name'
509 $query = $dbDrupal->query($sql);
510 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
513 $fakeDrupalAccount = drupal_anonymous_user();
514 $fakeDrupalAccount->name
= $name;
515 $fakeDrupalAccount->pass
= $row['pass'];
516 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
517 if ($passwordCheck) {
518 $userUid = $row['uid'];
519 $userMail = $row['mail'];
524 if ($userUid && $userMail) {
525 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
526 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
530 return array($contactID, $userUid, mt_rand());
536 * Load user into session
543 function loadUser($username) {
546 $user = user_load_by_name($username);
548 if (empty($user->uid
)) {
553 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
555 // lets store contact id and user id in session
556 $session = CRM_Core_Session
::singleton();
557 $session->set('ufID', $uid);
558 $session->set('userID', $contact_id);
563 * Perform any post login activities required by the UF -
564 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
565 * calls hook_user op 'login' and generates a new session.
567 * @param array params
569 * FIXME: Document values accepted/required by $params
571 function userLoginFinalize($params = array()){
572 user_login_finalize($params);
576 * Determine the native ID of the CMS user
581 function getUfId($username) {
582 $user = user_load_by_name($username);
583 if (empty($user->uid
)) {
590 * Set a message in the UF to display to a user
592 * @param string $message the message to set
596 function setMessage($message) {
597 drupal_set_message($message);
604 module_load_include('inc', 'user', 'user.pages');
605 return user_logout();
608 function updateCategories() {
609 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
616 * Get the default location for CiviCRM blocks
620 function getDefaultBlockLocation() {
621 return 'sidebar_first';
625 * Get the locale set in the hosting CMS
627 * @return string with the locale or null for none
629 function getUFLocale() {
630 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
631 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
632 // sometimes for CLI based on order called, this might not be set and/or empty
635 if (empty($language)) {
639 if ($language->language
== 'zh-hans') {
643 if ($language->language
== 'zh-hant') {
647 if (preg_match('/^.._..$/', $language->language
)) {
648 return $language->language
;
651 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
657 function getVersion() {
658 return defined('VERSION') ? VERSION
: 'Unknown';
662 * load drupal bootstrap
664 * @param array $params Either uid, or name & pass.
665 * @param boolean $loadUser boolean Require CMS user load.
666 * @param boolean $throwError If true, print error on failure and exit.
667 * @param boolean|string $realPath path to script
671 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
672 //take the cms root path.
673 $cmsPath = $this->cmsRootPath($realPath);
675 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
677 echo '<br />Sorry, could not locate bootstrap.inc\n';
682 // load drupal bootstrap
684 define('DRUPAL_ROOT', $cmsPath);
686 // For drupal multi-site CRM-11313
687 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
688 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
689 if (!empty($matches[1])) {
690 $_SERVER['HTTP_HOST'] = $matches[1];
693 require_once 'includes/bootstrap.inc';
694 // @ to suppress notices eg 'DRUPALFOO already defined'.
695 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
697 // explicitly setting error reporting, since we cannot handle drupal related notices
699 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
701 echo '<br />Sorry, could not load drupal bootstrap.';
707 // seems like we've bootstrapped drupal
708 $config = CRM_Core_Config
::singleton();
710 // lets also fix the clean url setting
712 $config->cleanURL
= (int) variable_get('clean_url', '0');
714 // we need to call the config hook again, since we now know
715 // all the modules that are listening on it, does not apply
716 // to J! and WP as yet
718 CRM_Utils_Hook
::config($config);
724 $uid = CRM_Utils_Array
::value('uid', $params);
726 //load user, we need to check drupal permissions.
727 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
728 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
731 $uid = user_authenticate($name, $pass);
734 echo '<br />Sorry, unrecognized username or password.';
743 $account = user_load($uid);
744 if ($account && $account->uid
) {
752 echo '<br />Sorry, can not load CMS user account.';
756 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
757 // which means that define(CIVICRM_CLEANURL) was correctly set.
759 $config = CRM_Core_Config
::singleton();
760 $config->cleanURL
= (int)variable_get('clean_url', '0');
762 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
763 CRM_Utils_Hook
::config($config);
771 function cmsRootPath($scriptFilename = NULL) {
772 $cmsRoot = $valid = NULL;
774 if (!is_null($scriptFilename)) {
775 $path = $scriptFilename;
778 $path = $_SERVER['SCRIPT_FILENAME'];
781 if (function_exists('drush_get_context')) {
782 // drush anyway takes care of multisite install etc
783 return drush_get_context('DRUSH_DRUPAL_ROOT');
786 $pathVars = explode('/',
787 str_replace('//', '/',
788 str_replace('\\', '/', $path)
792 //lets store first var,
793 //need to get back for windows.
794 $firstVar = array_shift($pathVars);
796 //lets remove sript name to reduce one iteration.
797 array_pop($pathVars);
799 //CRM-7429 --do check for upper most 'includes' dir,
800 //which would effectually work for multisite installation.
802 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
803 $cmsIncludePath = "$cmsRoot/includes";
804 //stop as we found bootstrap.
805 if (@opendir
($cmsIncludePath) &&
806 file_exists("$cmsIncludePath/bootstrap.inc")
811 //remove one directory level.
812 array_pop($pathVars);
813 } while (count($pathVars));
815 return ($valid) ?
$cmsRoot : NULL;
819 * check is user logged in.
821 * @return boolean true/false.
823 public function isUserLoggedIn() {
825 if (function_exists('user_is_logged_in')) {
826 $isloggedIn = user_is_logged_in();
833 * Get currently logged in user uf id.
835 * @return int $userID logged in user uf id.
837 public function getLoggedInUfID() {
839 if (function_exists('user_is_logged_in') &&
840 user_is_logged_in() &&
841 function_exists('user_uid_optional_to_arg')
843 $ufID = user_uid_optional_to_arg(array());
850 * Format the url as per language Negotiation.
854 * @param bool $addLanguagePart
855 * @param bool $removeLanguagePart
857 * @return string $url, formatted url.
860 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
865 //CRM-7803 -from d7 onward.
866 $config = CRM_Core_Config
::singleton();
867 if (function_exists('variable_get') &&
868 module_exists('locale') &&
869 function_exists('language_negotiation_get')
873 //does user configuration allow language
874 //support from the URL (Path prefix or domain)
875 if (language_negotiation_get('language') == 'locale-url') {
876 $urlType = variable_get('locale_language_negotiation_url_part');
879 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
880 if (isset($language->prefix
) && $language->prefix
) {
881 if ($addLanguagePart) {
882 $url .= $language->prefix
. '/';
884 if ($removeLanguagePart) {
885 $url = str_replace("/{$language->prefix}/", '/', $url);
890 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
891 if (isset($language->domain
) && $language->domain
) {
892 if ($addLanguagePart) {
893 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain
);
894 // drupal function base_path() adds a "/" to the beginning and end of the returned path
895 if (substr($cleanedUrl, -1) == '/') {
896 $cleanedUrl = substr($cleanedUrl, 0, -1);
898 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $cleanedUrl . base_path();
900 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
901 $url = str_replace('\\', '/', $url);
902 $parseUrl = parse_url($url);
904 //kinda hackish but not sure how to do it right
905 //hope http_build_url() will help at some point.
906 if (is_array($parseUrl) && !empty($parseUrl)) {
907 $urlParts = explode('/', $url);
908 $hostKey = array_search($parseUrl['host'], $urlParts);
909 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
910 $urlParts[$hostKey] = $ufUrlParts['host'];
911 $url = implode('/', $urlParts);
923 * Find any users/roles/security-principals with the given permission
924 * and replace it with one or more permissions.
926 * @param $oldPerm string
927 * @param $newPerms array, strings
931 function replacePermission($oldPerm, $newPerms) {
932 $roles = user_roles(FALSE, $oldPerm);
933 if (!empty($roles)) {
934 foreach (array_keys($roles) as $rid) {
935 user_role_revoke_permissions($rid, array($oldPerm));
936 user_role_grant_permissions($rid, $newPerms);
942 * Get a list of all installed modules, including enabled and disabled ones
944 * @return array CRM_Core_Module
946 function getModules() {
948 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
949 foreach ($q as $row) {
950 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
956 * Wrapper for og_membership creation
958 * @param integer $ogID Organic Group ID
959 * @param integer $drupalID drupal User ID
961 function og_membership_create($ogID, $drupalID){
962 if (function_exists('og_entity_query_alter')) {
963 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
965 // @TODO Find more solid way to check - try system_get_info('module', 'og').
967 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
968 og_group('node', $ogID, array('entity' => user_load($drupalID)));
971 // Works for the OG 7.x-1.x branch
972 og_group($ogID, array('entity' => user_load($drupalID)));
977 * Wrapper for og_membership deletion
979 * @param integer $ogID Organic Group ID
980 * @param integer $drupalID drupal User ID
982 function og_membership_delete($ogID, $drupalID) {
983 if (function_exists('og_entity_query_alter')) {
984 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
985 // TODO: Find a more solid way to make this test
986 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
987 og_ungroup('node', $ogID, 'user', user_load($drupalID));
989 // Works for the OG 7.x-1.x branch
990 og_ungroup($ogID, 'user', user_load($drupalID));
995 * Over-ridable function to get timezone as a string eg.
996 * @return string Timezone e.g. 'America/Los_Angeles'
998 function getTimeZoneString() {
1000 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
1001 $timezone = $user->timezone
;
1003 $timezone = variable_get('date_default_timezone', null);
1006 $timezone = parent
::getTimeZoneString();
1011 * Reset any system caches that may be required for proper CiviCRM
1015 drupal_flush_all_caches();