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
46 * Email id for cms user.
49 * 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
125 * Array of name and mail values.
126 * @param array $errors
128 * @param string $emailName
129 * Field label for the 'email'.
133 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
134 $config = CRM_Core_Config
::singleton();
136 $dao = new CRM_Core_DAO();
137 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
138 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
139 $errors = form_get_errors();
141 // unset drupal messages to avoid twice display of errors
142 unset($_SESSION['messages']);
145 if (!empty($params['name'])) {
146 if ($nameError = user_validate_name($params['name'])) {
147 $errors['cms_name'] = $nameError;
151 "SELECT uid FROM {users} WHERE name = :name",
152 array(':name' => $params['name'])
155 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
160 if (!empty($params['mail'])) {
161 if ($emailError = user_validate_mail($params['mail'])) {
162 $errors[$emailName] = $emailError;
166 "SELECT uid FROM {users} WHERE mail = :mail",
167 array(':mail' => $params['mail'])
170 $resetUrl = $config->userFrameworkBaseURL
. 'user/password';
171 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
172 array(1 => $params['mail'], 2 => $resetUrl)
180 * Get the drupal destination string. When this is passed in the
181 * URL the user will be directed to it after filling in the drupal form
183 * @param CRM_Core_Form $form
184 * Form object representing the 'current' form - to which the user will be returned.
186 * destination value for URL
189 * @param CRM_Core_Form $form
191 * @return null|string
193 public function getLoginDestination(&$form) {
196 $id = $form->get('id');
201 $gid = $form->get('gid');
203 $args .= "&gid=$gid";
206 // Setup Personal Campaign Page link uses pageId
207 $pageId = $form->get('pageId');
209 $component = $form->get('component');
210 $args .= "&pageId=$pageId&component=$component&action=add";
217 // append destination so user is returned to form they came from after login
218 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
224 * Get user login URL for hosting CMS (method declared in each CMS system class)
226 * @param string $destination
227 * If present, add destination to querystring (works for Drupal only).
230 * loginURL for the current CMS
233 public function getLoginURL($destination = '') {
234 $query = $destination ?
array('destination' => $destination) : array();
235 return url('user', array('query' => $query));
240 * Sets the title of the page
242 * @param string $title
243 * @param null $pageTitle
245 * @paqram string $pageTitle
249 public 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 array $breadCrumbs
263 * @internal param string $title
264 * @internal param string $url
268 public function appendBreadCrumb($breadCrumbs) {
269 $breadCrumb = drupal_get_breadcrumb();
271 if (is_array($breadCrumbs)) {
272 foreach ($breadCrumbs as $crumbs) {
273 if (stripos($crumbs['url'], 'id%%')) {
274 $args = array('cid', 'mid');
275 foreach ($args as $a) {
276 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
280 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
284 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
287 drupal_set_breadcrumb($breadCrumb);
291 * Reset an additional breadcrumb tag to the existing breadcrumb
295 public function resetBreadCrumb() {
297 drupal_set_breadcrumb($bc);
301 * Append a string to the head of the html file
303 * @param string $header
304 * The new string to be appended.
308 public function addHTMLHead($header) {
310 if (!empty($header)) {
311 $key = 'civi_' . ++
$count;
314 '#markup' => $header,
316 drupal_add_html_head($data, $key);
323 * @param $url : string, absolute path to file
324 * @param string $region
325 * location within the document: 'html-header', 'page-header', 'page-footer'.
327 * Note: This function is not to be called directly
328 * @see CRM_Core_Region::render()
331 * TRUE if we support this operation in this CMS, FALSE otherwise
333 public function addScriptUrl($url, $region) {
334 $params = array('group' => JS_LIBRARY
, 'weight' => 10);
338 $params['scope'] = substr($region, 5);
344 // If the path is within the drupal directory we can use the more efficient 'file' setting
345 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
346 drupal_add_js($url, $params);
351 * Add an inline script
353 * @param $code : string, javascript code
354 * @param string $region
355 * 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()
361 * 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);
374 drupal_add_js($code, $params);
381 * @param $url : string, absolute path to file
382 * @param string $region
383 * location within the document: 'html-header', 'page-header', 'page-footer'.
385 * Note: This function is not to be called directly
386 * @see CRM_Core_Region::render()
389 * TRUE if we support this operation in this CMS, FALSE otherwise
391 public function addStyleUrl($url, $region) {
392 if ($region != 'html-header') {
396 // If the path is within the drupal directory we can use the more efficient 'file' setting
397 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
398 drupal_add_css($url, $params);
403 * Add an inline style
405 * @param $code : string, css code
406 * @param string $region
407 * location within the document: 'html-header', 'page-header', 'page-footer'.
409 * Note: This function is not to be called directly
410 * @see CRM_Core_Region::render()
413 * TRUE if we support this operation in this CMS, FALSE otherwise
415 public function addStyle($code, $region) {
416 if ($region != 'html-header') {
419 $params = array('type' => 'inline');
420 drupal_add_css($code, $params);
425 * Rewrite various system urls to https
431 public function mapConfigToSSL() {
433 $base_url = str_replace('http://', 'https://', $base_url);
437 * Figure out the post url for the form
440 * The default action if one is pre-specified.
443 * the url to post the form
445 public function postURL($action) {
446 if (!empty($action)) {
450 return $this->url($_GET['q']);
455 * Authenticate the user against the drupal db
457 * @param string $name
459 * @param string $password
460 * The password for the above user name.
461 * @param bool $loadCMSBootstrap
462 * Load cms bootstrap?.
463 * @param NULL|string $realPath filename of script
468 * contactID, ufID, unique string ) if success
470 public static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
471 require_once 'DB.php';
473 $config = CRM_Core_Config
::singleton();
475 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
476 if (DB
::isError($dbDrupal)) {
477 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
480 $account = $userUid = $userMail = NULL;
481 if ($loadCMSBootstrap) {
482 $bootStrapParams = array();
483 if ($name && $password) {
484 $bootStrapParams = array(
489 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
493 $userUid = $user->uid
;
494 $userMail = $user->mail
;
499 // SOAP cannot load drupal bootstrap and hence we do it the old way
500 // Contact CiviSMTP folks if we run into issues with this :)
501 $cmsPath = $config->userSystem
->cmsRootPath($realPath);
503 require_once "$cmsPath/includes/bootstrap.inc";
504 require_once "$cmsPath/includes/password.inc";
506 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
507 $name = $dbDrupal->escapeSimple($strtolower($name));
510 FROM {$config->userFrameworkUsersTableName} u
511 WHERE LOWER(u.name) = '$name'
515 $query = $dbDrupal->query($sql);
516 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
519 $fakeDrupalAccount = drupal_anonymous_user();
520 $fakeDrupalAccount->name
= $name;
521 $fakeDrupalAccount->pass
= $row['pass'];
522 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
523 if ($passwordCheck) {
524 $userUid = $row['uid'];
525 $userMail = $row['mail'];
530 if ($userUid && $userMail) {
531 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
532 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
536 return array($contactID, $userUid, mt_rand());
542 * Load user into session
545 * @param string $username
549 public function loadUser($username) {
552 $user = user_load_by_name($username);
554 if (empty($user->uid
)) {
559 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
561 // lets store contact id and user id in session
562 $session = CRM_Core_Session
::singleton();
563 $session->set('ufID', $uid);
564 $session->set('userID', $contact_id);
569 * Perform any post login activities required by the UF -
570 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
571 * calls hook_user op 'login' and generates a new session.
573 * @param array params
575 * FIXME: Document values accepted/required by $params
577 public function userLoginFinalize($params = array()) {
578 user_login_finalize($params);
582 * Determine the native ID of the CMS user
584 * @param string $username
587 public function getUfId($username) {
588 $user = user_load_by_name($username);
589 if (empty($user->uid
)) {
596 * Set a message in the UF to display to a user
598 * @param string $message
599 * The message to set.
601 public function setMessage($message) {
602 drupal_set_message($message);
608 public function logout() {
609 module_load_include('inc', 'user', 'user.pages');
610 return user_logout();
613 public function updateCategories() {
614 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
621 * Get the default location for CiviCRM blocks
625 public function getDefaultBlockLocation() {
626 return 'sidebar_first';
630 * Get the locale set in the hosting CMS
633 * with the locale or null for none
635 public function getUFLocale() {
636 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
637 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
638 // sometimes for CLI based on order called, this might not be set and/or empty
641 if (empty($language)) {
645 if ($language->language
== 'zh-hans') {
649 if ($language->language
== 'zh-hant') {
653 if (preg_match('/^.._..$/', $language->language
)) {
654 return $language->language
;
657 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
663 public function getVersion() {
664 return defined('VERSION') ? VERSION
: 'Unknown';
668 * Load drupal bootstrap
670 * @param array $params
671 * Either uid, or name & pass.
672 * @param bool $loadUser
673 * Boolean Require CMS user load.
674 * @param bool $throwError
675 * If true, print error on failure and exit.
676 * @param bool|string $realPath path to script
680 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
681 //take the cms root path.
682 $cmsPath = $this->cmsRootPath($realPath);
684 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
686 echo '<br />Sorry, could not locate bootstrap.inc\n';
691 // load drupal bootstrap
693 define('DRUPAL_ROOT', $cmsPath);
695 // For drupal multi-site CRM-11313
696 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
697 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
698 if (!empty($matches[1])) {
699 $_SERVER['HTTP_HOST'] = $matches[1];
702 require_once 'includes/bootstrap.inc';
703 // @ to suppress notices eg 'DRUPALFOO already defined'.
704 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
706 // explicitly setting error reporting, since we cannot handle drupal related notices
708 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
710 echo '<br />Sorry, could not load drupal bootstrap.';
716 // seems like we've bootstrapped drupal
717 $config = CRM_Core_Config
::singleton();
719 // lets also fix the clean url setting
721 $config->cleanURL
= (int) variable_get('clean_url', '0');
723 // we need to call the config hook again, since we now know
724 // all the modules that are listening on it, does not apply
725 // to J! and WP as yet
727 CRM_Utils_Hook
::config($config);
733 $uid = CRM_Utils_Array
::value('uid', $params);
735 //load user, we need to check drupal permissions.
736 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
737 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
740 $uid = user_authenticate($name, $pass);
743 echo '<br />Sorry, unrecognized username or password.';
752 $account = user_load($uid);
753 if ($account && $account->uid
) {
761 echo '<br />Sorry, can not load CMS user account.';
765 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
766 // which means that define(CIVICRM_CLEANURL) was correctly set.
768 $config = CRM_Core_Config
::singleton();
769 $config->cleanURL
= (int) variable_get('clean_url', '0');
771 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
772 CRM_Utils_Hook
::config($config);
779 public function cmsRootPath($scriptFilename = NULL) {
780 $cmsRoot = $valid = NULL;
782 if (!is_null($scriptFilename)) {
783 $path = $scriptFilename;
786 $path = $_SERVER['SCRIPT_FILENAME'];
789 if (function_exists('drush_get_context')) {
790 // drush anyway takes care of multisite install etc
791 return drush_get_context('DRUSH_DRUPAL_ROOT');
794 $pathVars = explode('/',
795 str_replace('//', '/',
796 str_replace('\\', '/', $path)
800 //lets store first var,
801 //need to get back for windows.
802 $firstVar = array_shift($pathVars);
804 //lets remove sript name to reduce one iteration.
805 array_pop($pathVars);
807 // CRM-7429 -- do check for uppermost 'includes' dir, which would
808 // work for multisite installation.
810 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
811 $cmsIncludePath = "$cmsRoot/includes";
812 // Stop if we find bootstrap.
813 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
817 //remove one directory level.
818 array_pop($pathVars);
819 } while (count($pathVars));
821 return ($valid) ?
$cmsRoot : NULL;
825 * Check is user logged in.
829 public function isUserLoggedIn() {
831 if (function_exists('user_is_logged_in')) {
832 $isloggedIn = user_is_logged_in();
839 * Get currently logged in user uf id.
842 * $userID logged in user uf id.
844 public function getLoggedInUfID() {
846 if (function_exists('user_is_logged_in') &&
847 user_is_logged_in() &&
848 function_exists('user_uid_optional_to_arg')
850 $ufID = user_uid_optional_to_arg(array());
857 * Format the url as per language Negotiation.
861 * @param bool $addLanguagePart
862 * @param bool $removeLanguagePart
868 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
873 //CRM-7803 -from d7 onward.
874 $config = CRM_Core_Config
::singleton();
875 if (function_exists('variable_get') &&
876 module_exists('locale') &&
877 function_exists('language_negotiation_get')
881 //does user configuration allow language
882 //support from the URL (Path prefix or domain)
883 if (language_negotiation_get('language') == 'locale-url') {
884 $urlType = variable_get('locale_language_negotiation_url_part');
887 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
) {
888 if (isset($language->prefix
) && $language->prefix
) {
889 if ($addLanguagePart) {
890 $url .= $language->prefix
. '/';
892 if ($removeLanguagePart) {
893 $url = str_replace("/{$language->prefix}/", '/', $url);
898 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
899 if (isset($language->domain
) && $language->domain
) {
900 if ($addLanguagePart) {
901 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain
);
902 // drupal function base_path() adds a "/" to the beginning and end of the returned path
903 if (substr($cleanedUrl, -1) == '/') {
904 $cleanedUrl = substr($cleanedUrl, 0, -1);
906 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $cleanedUrl . base_path();
908 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
909 $url = str_replace('\\', '/', $url);
910 $parseUrl = parse_url($url);
912 //kinda hackish but not sure how to do it right
913 //hope http_build_url() will help at some point.
914 if (is_array($parseUrl) && !empty($parseUrl)) {
915 $urlParts = explode('/', $url);
916 $hostKey = array_search($parseUrl['host'], $urlParts);
917 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
918 $urlParts[$hostKey] = $ufUrlParts['host'];
919 $url = implode('/', $urlParts);
931 * Find any users/roles/security-principals with the given permission
932 * and replace it with one or more permissions.
934 * @param string $oldPerm
935 * @param array $newPerms
940 public function replacePermission($oldPerm, $newPerms) {
941 $roles = user_roles(FALSE, $oldPerm);
942 if (!empty($roles)) {
943 foreach (array_keys($roles) as $rid) {
944 user_role_revoke_permissions($rid, array($oldPerm));
945 user_role_grant_permissions($rid, $newPerms);
951 * Get a list of all installed modules, including enabled and disabled ones
956 public function getModules() {
958 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
959 foreach ($q as $row) {
960 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
966 * Wrapper for og_membership creation
970 * @param int $drupalID
973 public function og_membership_create($ogID, $drupalID) {
974 if (function_exists('og_entity_query_alter')) {
975 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
977 // @TODO Find more solid way to check - try system_get_info('module', 'og').
979 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
980 og_group('node', $ogID, array('entity' => user_load($drupalID)));
983 // Works for the OG 7.x-1.x branch
984 og_group($ogID, array('entity' => user_load($drupalID)));
989 * Wrapper for og_membership deletion
993 * @param int $drupalID
996 public function og_membership_delete($ogID, $drupalID) {
997 if (function_exists('og_entity_query_alter')) {
998 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
999 // TODO: Find a more solid way to make this test
1000 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
1001 og_ungroup('node', $ogID, 'user', user_load($drupalID));
1004 // Works for the OG 7.x-1.x branch
1005 og_ungroup($ogID, 'user', user_load($drupalID));
1010 * Over-ridable function to get timezone as a string eg.
1012 * Timezone e.g. 'America/Los_Angeles'
1014 public function getTimeZoneString() {
1016 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
1017 $timezone = $user->timezone
;
1020 $timezone = variable_get('date_default_timezone', NULL);
1023 $timezone = parent
::getTimeZoneString();
1029 * Reset any system caches that may be required for proper CiviCRM
1032 public function flush() {
1033 drupal_flush_all_caches();