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
51 public function createUser(&$params, $mail) {
52 $form_state = form_state_defaults();
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
108 * @param string $ufName
110 public function updateCMSName($ufID, $ufName) {
112 if (function_exists('user_load')) {
113 $user = user_load($ufID);
114 if ($user->mail
!= $ufName) {
115 user_save($user, array('mail' => $ufName));
116 $user = user_load($ufID);
122 * Check if username and email exists in the drupal db
124 * @param array $params array of name and mail values
125 * @param array $errors array of errors
126 * @param string $emailName field label for the 'email'
130 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
131 $config = CRM_Core_Config
::singleton();
133 $dao = new CRM_Core_DAO();
134 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
135 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
136 $errors = form_get_errors();
138 // unset drupal messages to avoid twice display of errors
139 unset($_SESSION['messages']);
142 if (!empty($params['name'])) {
143 if ($nameError = user_validate_name($params['name'])) {
144 $errors['cms_name'] = $nameError;
148 "SELECT uid FROM {users} WHERE name = :name",
149 array(':name' => $params['name'])
152 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
157 if (!empty($params['mail'])) {
158 if ($emailError = user_validate_mail($params['mail'])) {
159 $errors[$emailName] = $emailError;
163 "SELECT uid FROM {users} WHERE mail = :mail",
164 array(':mail' => $params['mail'])
167 $resetUrl = $config->userFrameworkBaseURL
. 'user/password';
168 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
169 array(1 => $params['mail'], 2 => $resetUrl)
177 * Get the drupal destination string. When this is passed in the
178 * URL the user will be directed to it after filling in the drupal form
180 * @param CRM_Core_Form $form Form object representing the 'current' form - to which the user will be returned
181 * @return string $destination destination value for URL
185 * @param CRM_Core_Form $form
187 * @return null|string
189 public function getLoginDestination(&$form) {
192 $id = $form->get('id');
197 $gid = $form->get('gid');
199 $args .= "&gid=$gid";
202 // Setup Personal Campaign Page link uses pageId
203 $pageId = $form->get('pageId');
205 $component = $form->get('component');
206 $args .= "&pageId=$pageId&component=$component&action=add";
213 // append destination so user is returned to form they came from after login
214 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
220 * Get user login URL for hosting CMS (method declared in each CMS system class)
222 * @param string $destination - if present, add destination to querystring (works for Drupal only)
224 * @return string - loginURL for the current CMS
227 public function getLoginURL($destination = '') {
228 $query = $destination ?
array('destination' => $destination) : array();
229 return url('user', array('query' => $query));
234 * Sets the title of the page
236 * @param string $title
237 * @param null $pageTitle
239 * @paqram string $pageTitle
243 public function setTitle($title, $pageTitle = NULL) {
244 if (arg(0) == 'civicrm') {
249 drupal_set_title($pageTitle, PASS_THROUGH
);
254 * Append an additional breadcrumb tag to the existing breadcrumb
256 * @param array $breadCrumbs
257 * @internal param string $title
258 * @internal param string $url
262 public function appendBreadCrumb($breadCrumbs) {
263 $breadCrumb = drupal_get_breadcrumb();
265 if (is_array($breadCrumbs)) {
266 foreach ($breadCrumbs as $crumbs) {
267 if (stripos($crumbs['url'], 'id%%')) {
268 $args = array('cid', 'mid');
269 foreach ($args as $a) {
270 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
274 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
278 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
281 drupal_set_breadcrumb($breadCrumb);
285 * Reset an additional breadcrumb tag to the existing breadcrumb
289 public function resetBreadCrumb() {
291 drupal_set_breadcrumb($bc);
295 * Append a string to the head of the html file
297 * @param string $header the new string to be appended
301 public function addHTMLHead($header) {
303 if (!empty($header)) {
304 $key = 'civi_' . ++
$count;
307 '#markup' => $header,
309 drupal_add_html_head($data, $key);
316 * @param $url: string, absolute path to file
317 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
319 * Note: This function is not to be called directly
320 * @see CRM_Core_Region::render()
322 * @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
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
376 public function addStyleUrl($url, $region) {
377 if ($region != 'html-header') {
381 // If the path is within the drupal directory we can use the more efficient 'file' setting
382 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
383 drupal_add_css($url, $params);
388 * Add an inline style
390 * @param $code: string, css code
391 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
393 * Note: This function is not to be called directly
394 * @see CRM_Core_Region::render()
396 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
398 public function addStyle($code, $region) {
399 if ($region != 'html-header') {
402 $params = array('type' => 'inline');
403 drupal_add_css($code, $params);
408 * Rewrite various system urls to https
414 public function mapConfigToSSL() {
416 $base_url = str_replace('http://', 'https://', $base_url);
420 * Figure out the post url for the form
422 * @param mix $action the default action if one is pre-specified
424 * @return string the url to post the form
426 public function postURL($action) {
427 if (!empty($action)) {
431 return $this->url($_GET['q']);
436 * Authenticate the user against the drupal db
438 * @param string $name the user name
439 * @param string $password the password for the above user name
440 * @param boolean $loadCMSBootstrap load cms bootstrap?
441 * @param NULL|string $realPath filename of script
443 * @return mixed false if no auth
445 * contactID, ufID, unique string ) if success
447 public static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
448 require_once 'DB.php';
450 $config = CRM_Core_Config
::singleton();
452 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
453 if (DB
::isError($dbDrupal)) {
454 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
457 $account = $userUid = $userMail = NULL;
458 if ($loadCMSBootstrap) {
459 $bootStrapParams = array();
460 if ($name && $password) {
461 $bootStrapParams = array(
466 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
470 $userUid = $user->uid
;
471 $userMail = $user->mail
;
476 // SOAP cannot load drupal bootstrap and hence we do it the old way
477 // Contact CiviSMTP folks if we run into issues with this :)
478 $cmsPath = $config->userSystem
->cmsRootPath($realPath);
480 require_once ("$cmsPath/includes/bootstrap.inc");
481 require_once ("$cmsPath/includes/password.inc");
483 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
484 $name = $dbDrupal->escapeSimple($strtolower($name));
487 FROM {$config->userFrameworkUsersTableName} u
488 WHERE LOWER(u.name) = '$name'
492 $query = $dbDrupal->query($sql);
493 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
496 $fakeDrupalAccount = drupal_anonymous_user();
497 $fakeDrupalAccount->name
= $name;
498 $fakeDrupalAccount->pass
= $row['pass'];
499 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
500 if ($passwordCheck) {
501 $userUid = $row['uid'];
502 $userMail = $row['mail'];
507 if ($userUid && $userMail) {
508 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
509 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
513 return array($contactID, $userUid, mt_rand());
519 * Load user into session
522 * @param string $username
526 public 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 public function userLoginFinalize($params = array()){
555 user_login_finalize($params);
559 * Determine the native ID of the CMS user
561 * @param string $username
564 public 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
578 public function setMessage($message) {
579 drupal_set_message($message);
585 public function logout() {
586 module_load_include('inc', 'user', 'user.pages');
587 return user_logout();
590 public function updateCategories() {
591 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
598 * Get the default location for CiviCRM blocks
602 public function getDefaultBlockLocation() {
603 return 'sidebar_first';
607 * Get the locale set in the hosting CMS
609 * @return string with the locale or null for none
611 public function getUFLocale() {
612 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
613 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
614 // sometimes for CLI based on order called, this might not be set and/or empty
617 if (empty($language)) {
621 if ($language->language
== 'zh-hans') {
625 if ($language->language
== 'zh-hant') {
629 if (preg_match('/^.._..$/', $language->language
)) {
630 return $language->language
;
633 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
639 public 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
653 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
654 //take the cms root path.
655 $cmsPath = $this->cmsRootPath($realPath);
657 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
659 echo '<br />Sorry, could not locate bootstrap.inc\n';
664 // load drupal bootstrap
666 define('DRUPAL_ROOT', $cmsPath);
668 // For drupal multi-site CRM-11313
669 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
670 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
671 if (!empty($matches[1])) {
672 $_SERVER['HTTP_HOST'] = $matches[1];
675 require_once 'includes/bootstrap.inc';
676 // @ to suppress notices eg 'DRUPALFOO already defined'.
677 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
679 // explicitly setting error reporting, since we cannot handle drupal related notices
681 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
683 echo '<br />Sorry, could not load drupal bootstrap.';
689 // seems like we've bootstrapped drupal
690 $config = CRM_Core_Config
::singleton();
692 // lets also fix the clean url setting
694 $config->cleanURL
= (int) variable_get('clean_url', '0');
696 // we need to call the config hook again, since we now know
697 // all the modules that are listening on it, does not apply
698 // to J! and WP as yet
700 CRM_Utils_Hook
::config($config);
706 $uid = CRM_Utils_Array
::value('uid', $params);
708 //load user, we need to check drupal permissions.
709 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
710 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
713 $uid = user_authenticate($name, $pass);
716 echo '<br />Sorry, unrecognized username or password.';
725 $account = user_load($uid);
726 if ($account && $account->uid
) {
734 echo '<br />Sorry, can not load CMS user account.';
738 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
739 // which means that define(CIVICRM_CLEANURL) was correctly set.
741 $config = CRM_Core_Config
::singleton();
742 $config->cleanURL
= (int)variable_get('clean_url', '0');
744 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
745 CRM_Utils_Hook
::config($config);
753 public function cmsRootPath($scriptFilename = NULL) {
754 $cmsRoot = $valid = NULL;
756 if (!is_null($scriptFilename)) {
757 $path = $scriptFilename;
760 $path = $_SERVER['SCRIPT_FILENAME'];
763 if (function_exists('drush_get_context')) {
764 // drush anyway takes care of multisite install etc
765 return drush_get_context('DRUSH_DRUPAL_ROOT');
768 $pathVars = explode('/',
769 str_replace('//', '/',
770 str_replace('\\', '/', $path)
774 //lets store first var,
775 //need to get back for windows.
776 $firstVar = array_shift($pathVars);
778 //lets remove sript name to reduce one iteration.
779 array_pop($pathVars);
781 //CRM-7429 --do check for upper most 'includes' dir,
782 //which would effectually work for multisite installation.
784 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
785 $cmsIncludePath = "$cmsRoot/includes";
786 //stop as we found bootstrap.
787 if (@opendir
($cmsIncludePath) &&
788 file_exists("$cmsIncludePath/bootstrap.inc")
793 //remove one directory level.
794 array_pop($pathVars);
795 } while (count($pathVars));
797 return ($valid) ?
$cmsRoot : NULL;
801 * Check is user logged in.
803 * @return boolean true/false.
805 public function isUserLoggedIn() {
807 if (function_exists('user_is_logged_in')) {
808 $isloggedIn = user_is_logged_in();
815 * Get currently logged in user uf id.
817 * @return int $userID logged in user uf id.
819 public function getLoggedInUfID() {
821 if (function_exists('user_is_logged_in') &&
822 user_is_logged_in() &&
823 function_exists('user_uid_optional_to_arg')
825 $ufID = user_uid_optional_to_arg(array());
832 * Format the url as per language Negotiation.
836 * @param bool $addLanguagePart
837 * @param bool $removeLanguagePart
839 * @return string $url, formatted url.
842 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
847 //CRM-7803 -from d7 onward.
848 $config = CRM_Core_Config
::singleton();
849 if (function_exists('variable_get') &&
850 module_exists('locale') &&
851 function_exists('language_negotiation_get')
855 //does user configuration allow language
856 //support from the URL (Path prefix or domain)
857 if (language_negotiation_get('language') == 'locale-url') {
858 $urlType = variable_get('locale_language_negotiation_url_part');
861 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
862 if (isset($language->prefix
) && $language->prefix
) {
863 if ($addLanguagePart) {
864 $url .= $language->prefix
. '/';
866 if ($removeLanguagePart) {
867 $url = str_replace("/{$language->prefix}/", '/', $url);
872 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
873 if (isset($language->domain
) && $language->domain
) {
874 if ($addLanguagePart) {
875 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain
);
876 // drupal function base_path() adds a "/" to the beginning and end of the returned path
877 if (substr($cleanedUrl, -1) == '/') {
878 $cleanedUrl = substr($cleanedUrl, 0, -1);
880 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $cleanedUrl . base_path();
882 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
883 $url = str_replace('\\', '/', $url);
884 $parseUrl = parse_url($url);
886 //kinda hackish but not sure how to do it right
887 //hope http_build_url() will help at some point.
888 if (is_array($parseUrl) && !empty($parseUrl)) {
889 $urlParts = explode('/', $url);
890 $hostKey = array_search($parseUrl['host'], $urlParts);
891 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
892 $urlParts[$hostKey] = $ufUrlParts['host'];
893 $url = implode('/', $urlParts);
905 * Find any users/roles/security-principals with the given permission
906 * and replace it with one or more permissions.
908 * @param $oldPerm string
909 * @param $newPerms array, strings
913 public function replacePermission($oldPerm, $newPerms) {
914 $roles = user_roles(FALSE, $oldPerm);
915 if (!empty($roles)) {
916 foreach (array_keys($roles) as $rid) {
917 user_role_revoke_permissions($rid, array($oldPerm));
918 user_role_grant_permissions($rid, $newPerms);
924 * Get a list of all installed modules, including enabled and disabled ones
926 * @return array CRM_Core_Module
928 public function getModules() {
930 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
931 foreach ($q as $row) {
932 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
938 * Wrapper for og_membership creation
940 * @param integer $ogID Organic Group ID
941 * @param integer $drupalID drupal User ID
943 public function og_membership_create($ogID, $drupalID){
944 if (function_exists('og_entity_query_alter')) {
945 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
947 // @TODO Find more solid way to check - try system_get_info('module', 'og').
949 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
950 og_group('node', $ogID, array('entity' => user_load($drupalID)));
953 // Works for the OG 7.x-1.x branch
954 og_group($ogID, array('entity' => user_load($drupalID)));
959 * Wrapper for og_membership deletion
961 * @param integer $ogID Organic Group ID
962 * @param integer $drupalID drupal User ID
964 public function og_membership_delete($ogID, $drupalID) {
965 if (function_exists('og_entity_query_alter')) {
966 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
967 // TODO: Find a more solid way to make this test
968 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
969 og_ungroup('node', $ogID, 'user', user_load($drupalID));
971 // Works for the OG 7.x-1.x branch
972 og_ungroup($ogID, 'user', user_load($drupalID));
977 * Over-ridable function to get timezone as a string eg.
978 * @return string Timezone e.g. 'America/Los_Angeles'
980 public function getTimeZoneString() {
982 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
983 $timezone = $user->timezone
;
985 $timezone = variable_get('date_default_timezone', null);
988 $timezone = parent
::getTimeZoneString();
993 * Reset any system caches that may be required for proper CiviCRM
996 public function flush() {
997 drupal_flush_all_caches();