3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * Drupal specific stuff goes here
39 class CRM_Utils_System_Drupal6
extends CRM_Utils_System_DrupalBase
{
42 * if we are using a theming system, invoke theme, else just print the
45 * @param string $content the content that will be themed
46 * @param boolean $print are we displaying to the screen or bypassing theming?
47 * @param boolean $maintenance for maintenance mode
49 * @return void prints content on stdout
52 function theme(&$content, $print = FALSE, $maintenance = FALSE) {
53 // TODO: Simplify; this was copied verbatim from CiviCRM 3.4's multi-UF theming function, but that's more complex than necessary
54 if (function_exists('theme') && !$print) {
56 drupal_set_breadcrumb('');
57 drupal_maintenance_theme();
60 // Arg 3 for D6 theme() is "show_blocks". Previously, we passed
61 // through a badly named variable ("$args") which was almost always
62 // TRUE (except on fatal error screen). However, this feature is
63 // non-functional on D6 default themes, was purposefully removed from
64 // D7, has no analog in other our other CMS's, and clutters the code.
65 // Hard-wiring to TRUE should be OK.
66 $out = theme('page', $content, TRUE);
76 * Function to create a user in Drupal.
78 * @param array $params associated array
79 * @param string $mail email id for cms user
81 * @return uid if user exists, false otherwise
85 function createUser(&$params, $mail) {
86 $form_state = array();
87 $form_state['values'] = array(
88 'name' => $params['cms_name'],
89 'mail' => $params[$mail],
90 'op' => 'Create new account',
93 $admin = user_access('administer users');
94 if (!variable_get('user_email_verification', TRUE) ||
$admin) {
95 $form_state['values']['pass']['pass1'] = $params['cms_pass'];
96 $form_state['values']['pass']['pass2'] = $params['cms_pass'];
99 $config = CRM_Core_Config
::singleton();
101 // we also need to redirect b
102 $config->inCiviCRM
= TRUE;
104 $form = drupal_retrieve_form('user_register', $form_state);
105 $form['#post'] = $form_state['values'];
106 drupal_prepare_form('user_register', $form, $form_state);
108 // remove the captcha element from the form prior to processing
109 unset($form['captcha']);
111 drupal_process_form('user_register', $form, $form_state);
113 $config->inCiviCRM
= FALSE;
115 if (form_get_errors() ||
!isset($form_state['user'])) {
118 return $form_state['user']->uid
;
122 * Change user name in host CMS
124 * @param integer $ufID User ID in CMS
125 * @param string $ufName User name
127 function updateCMSName($ufID, $ufName) {
129 if (function_exists('user_load')) {
130 $user = user_load(array('uid' => $ufID));
131 if ($user->mail
!= $ufName) {
132 user_save($user, array('mail' => $ufName));
133 $user = user_load(array('uid' => $ufID));
139 * Check if username and email exists in the drupal db
141 * @params $params array array of name and mail values
142 * @params $errors array array of errors
143 * @params $emailName string field label for the 'email'
147 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
148 $config = CRM_Core_Config
::singleton();
150 $dao = new CRM_Core_DAO();
151 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
152 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
153 _user_edit_validate(NULL, $params);
154 $errors = form_get_errors();
156 if (CRM_Utils_Array
::value('name', $errors)) {
157 $errors['cms_name'] = $errors['name'];
159 if (CRM_Utils_Array
::value('mail', $errors)) {
160 $errors[$emailName] = $errors['mail'];
162 // also unset drupal messages to avoid twice display of errors
163 unset($_SESSION['messages']);
166 // Do the name check manually.
167 $nameError = user_validate_name($params['name']);
169 $errors['cms_name'] = $nameError;
175 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))
178 $result = db_query($sql);
179 $row = db_fetch_array($result);
187 $dbName = CRM_Utils_Array
::value('name', $row);
188 $dbEmail = CRM_Utils_Array
::value('mail', $row);
189 if (strtolower($dbName) == strtolower($name)) {
190 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
194 if (strtolower($dbEmail) == strtolower($email)) {
196 $errors[$emailName] = ts('You cannot create an email account for a contact with no email',
201 $errors[$emailName] = ts('This email %1 is already registered. Please select another email.',
210 * Function to get the drupal destination string. When this is passed in the
211 * URL the user will be directed to it after filling in the drupal form
213 * @param object $form Form object representing the 'current' form - to which the user will be returned
214 * @return string $destination destination value for URL
217 function getLoginDestination(&$form) {
220 $id = $form->get('id');
225 $gid = $form->get('gid');
227 $args .= "&gid=$gid";
230 // Setup Personal Campaign Page link uses pageId
231 $pageId = $form->get('pageId');
233 $component = $form->get('component');
234 $args .= "&pageId=$pageId&component=$component&action=add";
241 // append destination so user is returned to form they came from after login
242 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
248 * sets the title of the page
250 * @param string $title
251 * @paqram string $pageTitle
256 function setTitle($title, $pageTitle = NULL) {
260 if (arg(0) == 'civicrm') {
262 drupal_set_title($pageTitle);
267 * Append an additional breadcrumb tag to the existing breadcrumb
269 * @param string $title
275 function appendBreadCrumb($breadCrumbs) {
276 $breadCrumb = drupal_get_breadcrumb();
278 if (is_array($breadCrumbs)) {
279 foreach ($breadCrumbs as $crumbs) {
280 if (stripos($crumbs['url'], 'id%%')) {
281 $args = array('cid', 'mid');
282 foreach ($args as $a) {
283 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
287 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
291 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
294 drupal_set_breadcrumb($breadCrumb);
298 * Reset an additional breadcrumb tag to the existing breadcrumb
303 function resetBreadCrumb() {
305 drupal_set_breadcrumb($bc);
309 * Append a string to the head of the html file
311 * @param string $head the new string to be appended
316 function addHTMLHead($head) {
317 drupal_set_html_head($head);
323 * @param $url: string, absolute path to file
324 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
326 * Note: This function is not to be called directly
327 * @see CRM_Core_Region::render()
329 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
332 public function addScriptUrl($url, $region) {
336 $scope = substr($region, 5);
341 // If the path is within the drupal directory we can add in the normal way
342 if ($this->formatResourceUrl($url)) {
343 drupal_add_js($url, 'module', $scope);
350 * Add an inline script
352 * @param $code: string, javascript code
353 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
355 * Note: This function is not to be called directly
356 * @see CRM_Core_Region::render()
358 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
361 public function addScript($code, $region) {
365 $scope = substr($region, 5);
370 drupal_add_js($code, 'inline', $scope);
377 * @param $url: string, absolute path to file
378 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
380 * Note: This function is not to be called directly
381 * @see CRM_Core_Region::render()
383 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
386 public function addStyleUrl($url, $region) {
387 if ($region != 'html-header' ||
!$this->formatResourceUrl($url)) {
390 drupal_add_css($url);
395 * Add an inline style
397 * @param $code: string, css code
398 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
400 * Note: This function is not to be called directly
401 * @see CRM_Core_Region::render()
403 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
406 public function addStyle($code, $region) {
411 * rewrite various system urls to https
418 function mapConfigToSSL() {
420 $base_url = str_replace('http://', 'https://', $base_url);
424 * figure out the post url for the form
426 * @param mix $action the default action if one is pre-specified
428 * @return string the url to post the form
431 function postURL($action) {
432 if (!empty($action)) {
436 return $this->url($_GET['q']);
440 * Authenticate the user against the drupal db
442 * @param string $name the user name
443 * @param string $password the password for the above user name
444 * @param boolean $loadCMSBootstrap load cms bootstrap?
445 * @param NULL|string $realPath filename of script
447 * @return mixed false if no auth
449 * contactID, ufID, unique string ) if success
452 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
453 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
455 // probably if bootstrap is loaded this call
456 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
457 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
458 // safe in the unknown situation where authenticate might be called & it is important that
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 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
470 $dbpassword = md5($password);
471 $name = $dbDrupal->escapeSimple($strtolower($name));
472 $sql = 'SELECT u.* FROM ' . $config->userFrameworkUsersTableName
. " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
473 $query = $dbDrupal->query($sql);
476 // need to change this to make sure we matched only one row
477 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC
)) {
478 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
479 $contactID = CRM_Core_BAO_UFMatch
::getContactId($row['uid']);
484 if ($loadCMSBootstrap) {
485 $bootStrapParams = array();
486 if ($name && $password) {
487 $bootStrapParams = array(
492 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
494 return array($contactID, $row['uid'], mt_rand());
501 * Load user into session
503 function loadUser($username) {
505 $user = user_load(array('name' => $username));
506 if (empty($user->uid
)) {
511 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
513 // lets store contact id and user id in session
514 $session = CRM_Core_Session
::singleton();
515 $session->set('ufID', $uid);
516 $session->set('userID', $contact_id);
521 * Perform any post login activities required by the UF -
522 * e.g. for drupal : records a watchdog message about the new session,
523 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
525 * @param array params
527 * FIXME: Document values accepted/required by $params
529 function userLoginFinalize($params = array()) {
530 user_authenticate_finalize($params);
534 * Determine the native ID of the CMS user
539 function getUfId($username) {
540 $user = user_load(array('name' => $username));
541 if (empty($user->uid
)) {
548 * Set a message in the UF to display to a user
550 * @param string $message the message to set
554 function setMessage($message) {
555 drupal_set_message($message);
558 function permissionDenied() {
559 drupal_access_denied();
563 module_load_include('inc', 'user', 'user.pages');
564 return user_logout();
567 function updateCategories() {
568 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
575 * Get the locale set in the hosting CMS
577 * @return string with the locale or null for none
579 function getUFLocale() {
580 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
581 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
582 // sometimes for CLI based on order called, this might not be set and/or empty
585 if (empty($language)) {
589 if ($language->language
== 'zh-hans') {
593 if ($language->language
== 'zh-hant') {
597 if (preg_match('/^.._..$/', $language->language
)) {
598 return $language->language
;
601 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
604 function getVersion() {
605 return defined('VERSION') ? VERSION
: 'Unknown';
609 * load drupal bootstrap
611 * @param array $params Either uid, or name & pass.
612 * @param boolean $loadUser boolean Require CMS user load.
613 * @param boolean $throwError If true, print error on failure and exit.
614 * @param boolean|string $realPath path to script
616 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
617 //take the cms root path.
618 $cmsPath = $this->cmsRootPath($realPath);
620 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
622 echo '<br />Sorry, could not locate bootstrap.inc\n';
627 // load drupal bootstrap
629 define('DRUPAL_ROOT', $cmsPath);
631 // For drupal multi-site CRM-11313
632 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
633 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
634 if (!empty($matches[1])) {
635 $_SERVER['HTTP_HOST'] = $matches[1];
638 require_once 'includes/bootstrap.inc';
639 // @ to suppress notices eg 'DRUPALFOO already defined'.
640 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
642 // explicitly setting error reporting, since we cannot handle drupal related notices
644 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
646 echo '<br />Sorry, could not load drupal bootstrap.';
652 // seems like we've bootstrapped drupal
653 $config = CRM_Core_Config
::singleton();
655 // lets also fix the clean url setting
657 $config->cleanURL
= (int) variable_get('clean_url', '0');
659 // we need to call the config hook again, since we now know
660 // all the modules that are listening on it, does not apply
661 // to J! and WP as yet
663 CRM_Utils_Hook
::config($config);
669 // If $uid is passed in, authentication has been done already.
670 $uid = CRM_Utils_Array
::value('uid', $params);
672 //load user, we need to check drupal permissions.
673 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
674 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
677 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
680 echo '<br />Sorry, unrecognized username or password.';
692 $account = user_load($uid);
693 if ($account && $account->uid
) {
700 echo '<br />Sorry, can not load CMS user account.';
704 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
705 // which means that define(CIVICRM_CLEANURL) was correctly set.
707 $config = CRM_Core_Config
::singleton();
708 $config->cleanURL
= (int)variable_get('clean_url', '0');
710 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
711 CRM_Utils_Hook
::config($config);
719 function cmsRootPath($scriptFilename = NULL) {
720 $cmsRoot = $valid = NULL;
722 if (!is_null($scriptFilename)) {
723 $path = $scriptFilename;
726 $path = $_SERVER['SCRIPT_FILENAME'];
729 if (function_exists('drush_get_context')) {
730 // drush anyway takes care of multisite install etc
731 return drush_get_context('DRUSH_DRUPAL_ROOT');
734 $pathVars = explode('/',
735 str_replace('//', '/',
736 str_replace('\\', '/', $path)
740 //lets store first var,
741 //need to get back for windows.
742 $firstVar = array_shift($pathVars);
744 //lets remove sript name to reduce one iteration.
745 array_pop($pathVars);
747 //CRM-7429 --do check for upper most 'includes' dir,
748 //which would effectually work for multisite installation.
750 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
751 $cmsIncludePath = "$cmsRoot/includes";
752 //stop as we found bootstrap.
753 if (@opendir
($cmsIncludePath) &&
754 file_exists("$cmsIncludePath/bootstrap.inc")
759 //remove one directory level.
760 array_pop($pathVars);
761 } while (count($pathVars));
763 return ($valid) ?
$cmsRoot : NULL;
767 * check is user logged in.
769 * @return boolean true/false.
771 public function isUserLoggedIn() {
773 if (function_exists('user_is_logged_in')) {
774 $isloggedIn = user_is_logged_in();
781 * Get currently logged in user uf id.
783 * @return int $userID logged in user uf id.
785 public function getLoggedInUfID() {
787 if (function_exists('user_is_logged_in') &&
788 user_is_logged_in() &&
789 function_exists('user_uid_optional_to_arg')
791 $ufID = user_uid_optional_to_arg(array());
798 * Format the url as per language Negotiation.
802 * @return string $url, formatted url.
805 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
810 //upto d6 only, already we have code in place for d7
811 $config = CRM_Core_Config
::singleton();
812 if (function_exists('variable_get') &&
813 module_exists('locale')
818 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE
);
821 if (isset($language->prefix
) &&
823 in_array($mode, array(
824 LANGUAGE_NEGOTIATION_PATH
,
825 LANGUAGE_NEGOTIATION_PATH_DEFAULT
,
829 if ($addLanguagePart) {
830 $url .= $language->prefix
. '/';
832 if ($removeLanguagePart) {
833 $url = str_replace("/{$language->prefix}/", '/', $url);
836 if (isset($language->domain
) &&
838 $mode == LANGUAGE_NEGOTIATION_DOMAIN
841 if ($addLanguagePart) {
842 $url = CRM_Utils_File
::addTrailingSlash($language->domain
, '/');
844 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
845 $url = str_replace('\\', '/', $url);
846 $parseUrl = parse_url($url);
848 //kinda hackish but not sure how to do it right
849 //hope http_build_url() will help at some point.
850 if (is_array($parseUrl) && !empty($parseUrl)) {
851 $urlParts = explode('/', $url);
852 $hostKey = array_search($parseUrl['host'], $urlParts);
853 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
854 $urlParts[$hostKey] = $ufUrlParts['host'];
855 $url = implode('/', $urlParts);
865 * Find any users/roles/security-principals with the given permission
866 * and replace it with one or more permissions.
868 * @param $oldPerm string
869 * @param $newPerms array, strings
873 function replacePermission($oldPerm, $newPerms) {
874 $roles = user_roles(FALSE, $oldPerm);
875 foreach ($roles as $rid => $roleName) {
876 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
877 $perms = drupal_map_assoc(explode(', ', $permList));
878 unset($perms[$oldPerm]);
879 $perms = $perms +
drupal_map_assoc($newPerms);
880 $permList = implode(', ', $perms);
881 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
883 if ( ! empty( $roles ) ) {
884 $rids = implode(',', array_keys($roles));
885 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
886 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
887 $oldPerm, implode(', ', $newPerms) );*/
892 * Get a list of all installed modules, including enabled and disabled ones
894 * @return array CRM_Core_Module
896 function getModules() {
898 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
899 while ($row = db_fetch_object($q)) {
900 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
906 * Get user login URL for hosting CMS (method declared in each CMS system class)
908 * @param string $destination - if present, add destination to querystring (works for Drupal only)
910 * @return string - loginURL for the current CMS
913 public function getLoginURL($destination = '') {
914 $config = CRM_Core_Config
::singleton();
915 $loginURL = $config->userFrameworkBaseURL
;
917 if (!empty($destination)) {
918 // append destination so user is returned to form they came from after login
919 $loginURL .= '?destination=' . urlencode($destination);
925 * Wrapper for og_membership creation
927 * @param integer $ogID Organic Group ID
928 * @param integer $drupalID drupal User ID
930 function og_membership_create($ogID, $drupalID){
931 og_save_subscription( $ogID, $drupalID, array( 'is_active' => 1 ) );
935 * Wrapper for og_membership deletion
937 * @param integer $ogID Organic Group ID
938 * @param integer $drupalID drupal User ID
940 function og_membership_delete($ogID, $drupalID) {
941 og_delete_subscription( $ogID, $drupalID );
945 * Get timezone from Drupal
946 * @return boolean|string
948 function getTimeZoneOffset(){
950 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
951 $timezone = $user->timezone
;
953 $timezone = variable_get('date_default_timezone', null);
955 if(empty($timezone)){
958 $hour = $user->timezone
/ 3600;
959 $timeZoneOffset = sprintf("%02d:%02d", $timezone / 3600, ($timezone/60)%60
);
960 if($timeZoneOffset > 0){
961 $timeZoneOffset = '+' . $timeZoneOffset;
963 return $timeZoneOffset;
968 * Reset any system caches that may be required for proper CiviCRM
972 drupal_flush_all_caches();