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
{
42 * 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
109 * @param string $ufName
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 * @param array $params array of name and mail values
126 * @param array $errors array of errors
127 * @param string $emailName field label for the 'email'
131 static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
132 $config = CRM_Core_Config
::singleton();
134 $dao = new CRM_Core_DAO();
135 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
136 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
137 $errors = form_get_errors();
139 // unset drupal messages to avoid twice display of errors
140 unset($_SESSION['messages']);
143 if (!empty($params['name'])) {
144 if ($nameError = user_validate_name($params['name'])) {
145 $errors['cms_name'] = $nameError;
149 "SELECT uid FROM {users} WHERE name = :name",
150 array(':name' => $params['name'])
153 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
158 if (!empty($params['mail'])) {
159 if ($emailError = user_validate_mail($params['mail'])) {
160 $errors[$emailName] = $emailError;
164 "SELECT uid FROM {users} WHERE mail = :mail",
165 array(':mail' => $params['mail'])
168 $resetUrl = $config->userFrameworkBaseURL
. 'user/password';
169 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
170 array(1 => $params['mail'], 2 => $resetUrl)
178 * Get the drupal destination string. When this is passed in the
179 * URL the user will be directed to it after filling in the drupal form
181 * @param CRM_Core_Form $form Form object representing the 'current' form - to which the user will be returned
182 * @return string $destination destination value for URL
186 * @param CRM_Core_Form $form
188 * @return null|string
190 function getLoginDestination(&$form) {
193 $id = $form->get('id');
198 $gid = $form->get('gid');
200 $args .= "&gid=$gid";
203 // Setup Personal Campaign Page link uses pageId
204 $pageId = $form->get('pageId');
206 $component = $form->get('component');
207 $args .= "&pageId=$pageId&component=$component&action=add";
214 // append destination so user is returned to form they came from after login
215 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
221 * Get user login URL for hosting CMS (method declared in each CMS system class)
223 * @param string $destination - if present, add destination to querystring (works for Drupal only)
225 * @return string - loginURL for the current CMS
228 public function getLoginURL($destination = '') {
229 $query = $destination ?
array('destination' => $destination) : array();
230 return url('user', array('query' => $query));
235 * Sets the title of the page
237 * @param string $title
238 * @param null $pageTitle
240 * @paqram string $pageTitle
245 function setTitle($title, $pageTitle = NULL) {
246 if (arg(0) == 'civicrm') {
251 drupal_set_title($pageTitle, PASS_THROUGH
);
256 * Append an additional breadcrumb tag to the existing breadcrumb
258 * @param array $breadCrumbs
259 * @internal param string $title
260 * @internal param string $url
265 function appendBreadCrumb($breadCrumbs) {
266 $breadCrumb = drupal_get_breadcrumb();
268 if (is_array($breadCrumbs)) {
269 foreach ($breadCrumbs as $crumbs) {
270 if (stripos($crumbs['url'], 'id%%')) {
271 $args = array('cid', 'mid');
272 foreach ($args as $a) {
273 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
277 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
281 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
284 drupal_set_breadcrumb($breadCrumb);
288 * Reset an additional breadcrumb tag to the existing breadcrumb
293 function resetBreadCrumb() {
295 drupal_set_breadcrumb($bc);
299 * Append a string to the head of the html file
301 * @param string $header the new string to be appended
306 function addHTMLHead($header) {
308 if (!empty($header)) {
309 $key = 'civi_' . ++
$count;
312 '#markup' => $header,
314 drupal_add_html_head($data, $key);
321 * @param $url: string, absolute path to file
322 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
324 * Note: This function is not to be called directly
325 * @see CRM_Core_Region::render()
327 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
330 public function addScriptUrl($url, $region) {
331 $params = array('group' => JS_LIBRARY
, 'weight' => 10);
335 $params['scope'] = substr($region, 5);
340 // If the path is within the drupal directory we can use the more efficient 'file' setting
341 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
342 drupal_add_js($url, $params);
347 * Add an inline script
349 * @param $code: string, javascript code
350 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
352 * Note: This function is not to be called directly
353 * @see CRM_Core_Region::render()
355 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
358 public function addScript($code, $region) {
359 $params = array('type' => 'inline', 'group' => JS_LIBRARY
, 'weight' => 10);
363 $params['scope'] = substr($region, 5);
368 drupal_add_js($code, $params);
375 * @param $url: string, absolute path to file
376 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
378 * Note: This function is not to be called directly
379 * @see CRM_Core_Region::render()
381 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
384 public function addStyleUrl($url, $region) {
385 if ($region != 'html-header') {
389 // If the path is within the drupal directory we can use the more efficient 'file' setting
390 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
391 drupal_add_css($url, $params);
396 * Add an inline style
398 * @param $code: string, css code
399 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
401 * Note: This function is not to be called directly
402 * @see CRM_Core_Region::render()
404 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
407 public function addStyle($code, $region) {
408 if ($region != 'html-header') {
411 $params = array('type' => 'inline');
412 drupal_add_css($code, $params);
417 * Rewrite various system urls to https
424 function mapConfigToSSL() {
426 $base_url = str_replace('http://', 'https://', $base_url);
430 * Figure out the post url for the form
432 * @param mix $action the default action if one is pre-specified
434 * @return string the url to post the form
437 function postURL($action) {
438 if (!empty($action)) {
442 return $this->url($_GET['q']);
447 * Authenticate the user against the drupal db
449 * @param string $name the user name
450 * @param string $password the password for the above user name
451 * @param boolean $loadCMSBootstrap load cms bootstrap?
452 * @param NULL|string $realPath filename of script
454 * @return mixed false if no auth
456 * contactID, ufID, unique string ) if success
459 static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
460 require_once 'DB.php';
462 $config = CRM_Core_Config
::singleton();
464 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
465 if (DB
::isError($dbDrupal)) {
466 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
469 $account = $userUid = $userMail = NULL;
470 if ($loadCMSBootstrap) {
471 $bootStrapParams = array();
472 if ($name && $password) {
473 $bootStrapParams = array(
478 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
482 $userUid = $user->uid
;
483 $userMail = $user->mail
;
488 // SOAP cannot load drupal bootstrap and hence we do it the old way
489 // Contact CiviSMTP folks if we run into issues with this :)
490 $cmsPath = $config->userSystem
->cmsRootPath($realPath);
492 require_once ("$cmsPath/includes/bootstrap.inc");
493 require_once ("$cmsPath/includes/password.inc");
495 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
496 $name = $dbDrupal->escapeSimple($strtolower($name));
499 FROM {$config->userFrameworkUsersTableName} u
500 WHERE LOWER(u.name) = '$name'
504 $query = $dbDrupal->query($sql);
505 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
508 $fakeDrupalAccount = drupal_anonymous_user();
509 $fakeDrupalAccount->name
= $name;
510 $fakeDrupalAccount->pass
= $row['pass'];
511 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
512 if ($passwordCheck) {
513 $userUid = $row['uid'];
514 $userMail = $row['mail'];
519 if ($userUid && $userMail) {
520 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
521 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
525 return array($contactID, $userUid, mt_rand());
531 * Load user into session
534 * @param string $username
538 function loadUser($username) {
541 $user = user_load_by_name($username);
543 if (empty($user->uid
)) {
548 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
550 // lets store contact id and user id in session
551 $session = CRM_Core_Session
::singleton();
552 $session->set('ufID', $uid);
553 $session->set('userID', $contact_id);
558 * Perform any post login activities required by the UF -
559 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
560 * calls hook_user op 'login' and generates a new session.
562 * @param array params
564 * FIXME: Document values accepted/required by $params
566 function userLoginFinalize($params = array()){
567 user_login_finalize($params);
571 * Determine the native ID of the CMS user
573 * @param string $username
576 function getUfId($username) {
577 $user = user_load_by_name($username);
578 if (empty($user->uid
)) {
585 * Set a message in the UF to display to a user
587 * @param string $message the message to set
591 function setMessage($message) {
592 drupal_set_message($message);
599 module_load_include('inc', 'user', 'user.pages');
600 return user_logout();
603 function updateCategories() {
604 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
611 * Get the default location for CiviCRM blocks
615 function getDefaultBlockLocation() {
616 return 'sidebar_first';
620 * Get the locale set in the hosting CMS
622 * @return string with the locale or null for none
624 function getUFLocale() {
625 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
626 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
627 // sometimes for CLI based on order called, this might not be set and/or empty
630 if (empty($language)) {
634 if ($language->language
== 'zh-hans') {
638 if ($language->language
== 'zh-hant') {
642 if (preg_match('/^.._..$/', $language->language
)) {
643 return $language->language
;
646 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
652 function getVersion() {
653 return defined('VERSION') ? VERSION
: 'Unknown';
657 * Load drupal bootstrap
659 * @param array $params Either uid, or name & pass.
660 * @param boolean $loadUser boolean Require CMS user load.
661 * @param boolean $throwError If true, print error on failure and exit.
662 * @param boolean|string $realPath path to script
666 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
667 //take the cms root path.
668 $cmsPath = $this->cmsRootPath($realPath);
670 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
672 echo '<br />Sorry, could not locate bootstrap.inc\n';
677 // load drupal bootstrap
679 define('DRUPAL_ROOT', $cmsPath);
681 // For drupal multi-site CRM-11313
682 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
683 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
684 if (!empty($matches[1])) {
685 $_SERVER['HTTP_HOST'] = $matches[1];
688 require_once 'includes/bootstrap.inc';
689 // @ to suppress notices eg 'DRUPALFOO already defined'.
690 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
692 // explicitly setting error reporting, since we cannot handle drupal related notices
694 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
696 echo '<br />Sorry, could not load drupal bootstrap.';
702 // seems like we've bootstrapped drupal
703 $config = CRM_Core_Config
::singleton();
705 // lets also fix the clean url setting
707 $config->cleanURL
= (int) variable_get('clean_url', '0');
709 // we need to call the config hook again, since we now know
710 // all the modules that are listening on it, does not apply
711 // to J! and WP as yet
713 CRM_Utils_Hook
::config($config);
719 $uid = CRM_Utils_Array
::value('uid', $params);
721 //load user, we need to check drupal permissions.
722 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
723 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
726 $uid = user_authenticate($name, $pass);
729 echo '<br />Sorry, unrecognized username or password.';
738 $account = user_load($uid);
739 if ($account && $account->uid
) {
747 echo '<br />Sorry, can not load CMS user account.';
751 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
752 // which means that define(CIVICRM_CLEANURL) was correctly set.
754 $config = CRM_Core_Config
::singleton();
755 $config->cleanURL
= (int)variable_get('clean_url', '0');
757 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
758 CRM_Utils_Hook
::config($config);
766 function cmsRootPath($scriptFilename = NULL) {
767 $cmsRoot = $valid = NULL;
769 if (!is_null($scriptFilename)) {
770 $path = $scriptFilename;
773 $path = $_SERVER['SCRIPT_FILENAME'];
776 if (function_exists('drush_get_context')) {
777 // drush anyway takes care of multisite install etc
778 return drush_get_context('DRUSH_DRUPAL_ROOT');
781 $pathVars = explode('/',
782 str_replace('//', '/',
783 str_replace('\\', '/', $path)
787 //lets store first var,
788 //need to get back for windows.
789 $firstVar = array_shift($pathVars);
791 //lets remove sript name to reduce one iteration.
792 array_pop($pathVars);
794 //CRM-7429 --do check for upper most 'includes' dir,
795 //which would effectually work for multisite installation.
797 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
798 $cmsIncludePath = "$cmsRoot/includes";
799 //stop as we found bootstrap.
800 if (@opendir
($cmsIncludePath) &&
801 file_exists("$cmsIncludePath/bootstrap.inc")
806 //remove one directory level.
807 array_pop($pathVars);
808 } while (count($pathVars));
810 return ($valid) ?
$cmsRoot : NULL;
814 * Check is user logged in.
816 * @return boolean true/false.
818 public function isUserLoggedIn() {
820 if (function_exists('user_is_logged_in')) {
821 $isloggedIn = user_is_logged_in();
828 * Get currently logged in user uf id.
830 * @return int $userID logged in user uf id.
832 public function getLoggedInUfID() {
834 if (function_exists('user_is_logged_in') &&
835 user_is_logged_in() &&
836 function_exists('user_uid_optional_to_arg')
838 $ufID = user_uid_optional_to_arg(array());
845 * Format the url as per language Negotiation.
849 * @param bool $addLanguagePart
850 * @param bool $removeLanguagePart
852 * @return string $url, formatted url.
855 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
860 //CRM-7803 -from d7 onward.
861 $config = CRM_Core_Config
::singleton();
862 if (function_exists('variable_get') &&
863 module_exists('locale') &&
864 function_exists('language_negotiation_get')
868 //does user configuration allow language
869 //support from the URL (Path prefix or domain)
870 if (language_negotiation_get('language') == 'locale-url') {
871 $urlType = variable_get('locale_language_negotiation_url_part');
874 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
875 if (isset($language->prefix
) && $language->prefix
) {
876 if ($addLanguagePart) {
877 $url .= $language->prefix
. '/';
879 if ($removeLanguagePart) {
880 $url = str_replace("/{$language->prefix}/", '/', $url);
885 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
886 if (isset($language->domain
) && $language->domain
) {
887 if ($addLanguagePart) {
888 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain
);
889 // drupal function base_path() adds a "/" to the beginning and end of the returned path
890 if (substr($cleanedUrl, -1) == '/') {
891 $cleanedUrl = substr($cleanedUrl, 0, -1);
893 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $cleanedUrl . base_path();
895 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
896 $url = str_replace('\\', '/', $url);
897 $parseUrl = parse_url($url);
899 //kinda hackish but not sure how to do it right
900 //hope http_build_url() will help at some point.
901 if (is_array($parseUrl) && !empty($parseUrl)) {
902 $urlParts = explode('/', $url);
903 $hostKey = array_search($parseUrl['host'], $urlParts);
904 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
905 $urlParts[$hostKey] = $ufUrlParts['host'];
906 $url = implode('/', $urlParts);
918 * Find any users/roles/security-principals with the given permission
919 * and replace it with one or more permissions.
921 * @param $oldPerm string
922 * @param $newPerms array, strings
926 function replacePermission($oldPerm, $newPerms) {
927 $roles = user_roles(FALSE, $oldPerm);
928 if (!empty($roles)) {
929 foreach (array_keys($roles) as $rid) {
930 user_role_revoke_permissions($rid, array($oldPerm));
931 user_role_grant_permissions($rid, $newPerms);
937 * Get a list of all installed modules, including enabled and disabled ones
939 * @return array CRM_Core_Module
941 function getModules() {
943 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
944 foreach ($q as $row) {
945 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
951 * Wrapper for og_membership creation
953 * @param integer $ogID Organic Group ID
954 * @param integer $drupalID drupal User ID
956 function og_membership_create($ogID, $drupalID){
957 if (function_exists('og_entity_query_alter')) {
958 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
960 // @TODO Find more solid way to check - try system_get_info('module', 'og').
962 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
963 og_group('node', $ogID, array('entity' => user_load($drupalID)));
966 // Works for the OG 7.x-1.x branch
967 og_group($ogID, array('entity' => user_load($drupalID)));
972 * Wrapper for og_membership deletion
974 * @param integer $ogID Organic Group ID
975 * @param integer $drupalID drupal User ID
977 function og_membership_delete($ogID, $drupalID) {
978 if (function_exists('og_entity_query_alter')) {
979 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
980 // TODO: Find a more solid way to make this test
981 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
982 og_ungroup('node', $ogID, 'user', user_load($drupalID));
984 // Works for the OG 7.x-1.x branch
985 og_ungroup($ogID, 'user', user_load($drupalID));
990 * Over-ridable function to get timezone as a string eg.
991 * @return string Timezone e.g. 'America/Los_Angeles'
993 function getTimeZoneString() {
995 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
996 $timezone = $user->timezone
;
998 $timezone = variable_get('date_default_timezone', null);
1001 $timezone = parent
::getTimeZoneString();
1006 * Reset any system caches that may be required for proper CiviCRM
1010 drupal_flush_all_caches();