3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Drupal specific stuff goes here
39 class CRM_Utils_System_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
131 function updateCMSName($ufID, $ufName) {
133 if (function_exists('user_load')) {
134 $user = user_load(array('uid' => $ufID));
135 if ($user->mail
!= $ufName) {
136 user_save($user, array('mail' => $ufName));
137 $user = user_load(array('uid' => $ufID));
143 * Check if username and email exists in the drupal db
145 * @params $params array array of name and mail values
146 * @params $errors array array of errors
147 * @params $emailName string field label for the 'email'
151 * @param string $emailName
155 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
156 $config = CRM_Core_Config
::singleton();
158 $dao = new CRM_Core_DAO();
159 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
160 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
161 _user_edit_validate(NULL, $params);
162 $errors = form_get_errors();
164 if (!empty($errors['name'])) {
165 $errors['cms_name'] = $errors['name'];
167 if (!empty($errors['mail'])) {
168 $errors[$emailName] = $errors['mail'];
170 // also unset drupal messages to avoid twice display of errors
171 unset($_SESSION['messages']);
174 // Do the name check manually.
175 $nameError = user_validate_name($params['name']);
177 $errors['cms_name'] = $nameError;
183 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))
186 $result = db_query($sql);
187 $row = db_fetch_array($result);
195 $dbName = CRM_Utils_Array
::value('name', $row);
196 $dbEmail = CRM_Utils_Array
::value('mail', $row);
197 if (strtolower($dbName) == strtolower($name)) {
198 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
202 if (strtolower($dbEmail) == strtolower($email)) {
204 $errors[$emailName] = ts('You cannot create an email account for a contact with no email',
209 $errors[$emailName] = ts('This email %1 is already registered. Please select another email.',
218 * Function to get the drupal destination string. When this is passed in the
219 * URL the user will be directed to it after filling in the drupal form
221 * @param object $form Form object representing the 'current' form - to which the user will be returned
222 * @return string $destination destination value for URL
225 function getLoginDestination(&$form) {
228 $id = $form->get('id');
233 $gid = $form->get('gid');
235 $args .= "&gid=$gid";
238 // Setup Personal Campaign Page link uses pageId
239 $pageId = $form->get('pageId');
241 $component = $form->get('component');
242 $args .= "&pageId=$pageId&component=$component&action=add";
249 // append destination so user is returned to form they came from after login
250 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
256 * sets the title of the page
258 * @param string $title
259 * @param null $pageTitle
261 * @paqram string $pageTitle
266 function setTitle($title, $pageTitle = NULL) {
270 if (arg(0) == 'civicrm') {
272 drupal_set_title($pageTitle);
277 * Append an additional breadcrumb tag to the existing breadcrumb
279 * @param $breadCrumbs
281 * @internal param string $title
282 * @internal param string $url
287 function appendBreadCrumb($breadCrumbs) {
288 $breadCrumb = drupal_get_breadcrumb();
290 if (is_array($breadCrumbs)) {
291 foreach ($breadCrumbs as $crumbs) {
292 if (stripos($crumbs['url'], 'id%%')) {
293 $args = array('cid', 'mid');
294 foreach ($args as $a) {
295 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
299 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
303 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
306 drupal_set_breadcrumb($breadCrumb);
310 * Reset an additional breadcrumb tag to the existing breadcrumb
315 function resetBreadCrumb() {
317 drupal_set_breadcrumb($bc);
321 * Append a string to the head of the html file
323 * @param string $head the new string to be appended
328 function addHTMLHead($head) {
329 drupal_set_html_head($head);
335 * @param $url: string, absolute path to file
336 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
338 * Note: This function is not to be called directly
339 * @see CRM_Core_Region::render()
341 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
344 public function addScriptUrl($url, $region) {
345 // CRM-15450 - D6 doesn't order internal/external links correctly so we can't use drupal_add_js
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) {
362 // CRM-15450 - ensure scripts are in correct order
369 * @param $url: string, absolute path to file
370 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
372 * Note: This function is not to be called directly
373 * @see CRM_Core_Region::render()
375 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
378 public function addStyleUrl($url, $region) {
379 if ($region != 'html-header' ||
!$this->formatResourceUrl($url)) {
382 drupal_add_css($url);
387 * Add an inline style
389 * @param $code: string, css code
390 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
392 * Note: This function is not to be called directly
393 * @see CRM_Core_Region::render()
395 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
398 public function addStyle($code, $region) {
403 * rewrite various system urls to https
410 function mapConfigToSSL() {
412 $base_url = str_replace('http://', 'https://', $base_url);
416 * figure out the post url for the form
418 * @param mix $action the default action if one is pre-specified
420 * @return string the url to post the form
423 function postURL($action) {
424 if (!empty($action)) {
428 return $this->url($_GET['q']);
432 * Authenticate the user against the drupal db
434 * @param string $name the user name
435 * @param string $password the password for the above user name
436 * @param boolean $loadCMSBootstrap load cms bootstrap?
437 * @param NULL|string $realPath filename of script
439 * @return mixed false if no auth
441 * contactID, ufID, unique string ) if success
444 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
445 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
447 // probably if bootstrap is loaded this call
448 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
449 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
450 // safe in the unknown situation where authenticate might be called & it is important that
452 require_once 'DB.php';
454 $config = CRM_Core_Config
::singleton();
456 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
457 if (DB
::isError($dbDrupal)) {
458 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
461 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
462 $dbpassword = md5($password);
463 $name = $dbDrupal->escapeSimple($strtolower($name));
464 $sql = 'SELECT u.* FROM ' . $config->userFrameworkUsersTableName
. " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
465 $query = $dbDrupal->query($sql);
468 // need to change this to make sure we matched only one row
469 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC
)) {
470 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
471 $contactID = CRM_Core_BAO_UFMatch
::getContactId($row['uid']);
476 if ($loadCMSBootstrap) {
477 $bootStrapParams = array();
478 if ($name && $password) {
479 $bootStrapParams = array(
484 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
486 return array($contactID, $row['uid'], mt_rand());
493 * Load user into session
495 function loadUser($username) {
497 $user = user_load(array('name' => $username));
498 if (empty($user->uid
)) {
503 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
505 // lets store contact id and user id in session
506 $session = CRM_Core_Session
::singleton();
507 $session->set('ufID', $uid);
508 $session->set('userID', $contact_id);
513 * Perform any post login activities required by the UF -
514 * e.g. for drupal : records a watchdog message about the new session,
515 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
517 * @param array params
519 * FIXME: Document values accepted/required by $params
521 function userLoginFinalize($params = array()) {
522 user_authenticate_finalize($params);
526 * Determine the native ID of the CMS user
531 function getUfId($username) {
532 $user = user_load(array('name' => $username));
533 if (empty($user->uid
)) {
540 * Set a message in the UF to display to a user
542 * @param string $message the message to set
546 function setMessage($message) {
547 drupal_set_message($message);
554 module_load_include('inc', 'user', 'user.pages');
555 return user_logout();
558 function updateCategories() {
559 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
566 * Get the locale set in the hosting CMS
568 * @return string with the locale or null for none
570 function getUFLocale() {
571 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
572 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
573 // sometimes for CLI based on order called, this might not be set and/or empty
576 if (empty($language)) {
580 if ($language->language
== 'zh-hans') {
584 if ($language->language
== 'zh-hant') {
588 if (preg_match('/^.._..$/', $language->language
)) {
589 return $language->language
;
592 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
598 function getVersion() {
599 return defined('VERSION') ? VERSION
: 'Unknown';
603 * load drupal bootstrap
605 * @param array $params Either uid, or name & pass.
606 * @param boolean $loadUser boolean Require CMS user load.
607 * @param boolean $throwError If true, print error on failure and exit.
608 * @param boolean|string $realPath path to script
612 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
613 //take the cms root path.
614 $cmsPath = $this->cmsRootPath($realPath);
616 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
618 echo '<br />Sorry, could not locate bootstrap.inc\n';
623 // load drupal bootstrap
625 define('DRUPAL_ROOT', $cmsPath);
627 // For drupal multi-site CRM-11313
628 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
629 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
630 if (!empty($matches[1])) {
631 $_SERVER['HTTP_HOST'] = $matches[1];
634 require_once 'includes/bootstrap.inc';
635 // @ to suppress notices eg 'DRUPALFOO already defined'.
636 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
638 // explicitly setting error reporting, since we cannot handle drupal related notices
640 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
642 echo '<br />Sorry, could not load drupal bootstrap.';
648 // seems like we've bootstrapped drupal
649 $config = CRM_Core_Config
::singleton();
651 // lets also fix the clean url setting
653 $config->cleanURL
= (int) variable_get('clean_url', '0');
655 // we need to call the config hook again, since we now know
656 // all the modules that are listening on it, does not apply
657 // to J! and WP as yet
659 CRM_Utils_Hook
::config($config);
665 // If $uid is passed in, authentication has been done already.
666 $uid = CRM_Utils_Array
::value('uid', $params);
668 //load user, we need to check drupal permissions.
669 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
670 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
673 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
676 echo '<br />Sorry, unrecognized username or password.';
688 $account = user_load($uid);
689 if ($account && $account->uid
) {
696 echo '<br />Sorry, can not load CMS user account.';
700 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
701 // which means that define(CIVICRM_CLEANURL) was correctly set.
703 $config = CRM_Core_Config
::singleton();
704 $config->cleanURL
= (int)variable_get('clean_url', '0');
706 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
707 CRM_Utils_Hook
::config($config);
715 function cmsRootPath($scriptFilename = NULL) {
716 $cmsRoot = $valid = NULL;
718 if (!is_null($scriptFilename)) {
719 $path = $scriptFilename;
722 $path = $_SERVER['SCRIPT_FILENAME'];
725 if (function_exists('drush_get_context')) {
726 // drush anyway takes care of multisite install etc
727 return drush_get_context('DRUSH_DRUPAL_ROOT');
730 $pathVars = explode('/',
731 str_replace('//', '/',
732 str_replace('\\', '/', $path)
736 //lets store first var,
737 //need to get back for windows.
738 $firstVar = array_shift($pathVars);
740 //lets remove sript name to reduce one iteration.
741 array_pop($pathVars);
743 //CRM-7429 --do check for upper most 'includes' dir,
744 //which would effectually work for multisite installation.
746 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
747 $cmsIncludePath = "$cmsRoot/includes";
748 //stop as we found bootstrap.
749 if (@opendir
($cmsIncludePath) &&
750 file_exists("$cmsIncludePath/bootstrap.inc")
755 //remove one directory level.
756 array_pop($pathVars);
757 } while (count($pathVars));
759 return ($valid) ?
$cmsRoot : NULL;
763 * check is user logged in.
765 * @return boolean true/false.
767 public function isUserLoggedIn() {
769 if (function_exists('user_is_logged_in')) {
770 $isloggedIn = user_is_logged_in();
777 * Get currently logged in user uf id.
779 * @return int $userID logged in user uf id.
781 public function getLoggedInUfID() {
783 if (function_exists('user_is_logged_in') &&
784 user_is_logged_in() &&
785 function_exists('user_uid_optional_to_arg')
787 $ufID = user_uid_optional_to_arg(array());
794 * Format the url as per language Negotiation.
798 * @param bool $addLanguagePart
799 * @param bool $removeLanguagePart
801 * @return string $url, formatted url.
804 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
809 //upto d6 only, already we have code in place for d7
810 $config = CRM_Core_Config
::singleton();
811 if (function_exists('variable_get') &&
812 module_exists('locale')
817 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE
);
820 if (isset($language->prefix
) &&
822 in_array($mode, array(
823 LANGUAGE_NEGOTIATION_PATH
,
824 LANGUAGE_NEGOTIATION_PATH_DEFAULT
,
828 if ($addLanguagePart) {
829 $url .= $language->prefix
. '/';
831 if ($removeLanguagePart) {
832 $url = str_replace("/{$language->prefix}/", '/', $url);
835 if (isset($language->domain
) &&
837 $mode == LANGUAGE_NEGOTIATION_DOMAIN
840 if ($addLanguagePart) {
841 $url = CRM_Utils_File
::addTrailingSlash($language->domain
, '/');
843 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
844 $url = str_replace('\\', '/', $url);
845 $parseUrl = parse_url($url);
847 //kinda hackish but not sure how to do it right
848 //hope http_build_url() will help at some point.
849 if (is_array($parseUrl) && !empty($parseUrl)) {
850 $urlParts = explode('/', $url);
851 $hostKey = array_search($parseUrl['host'], $urlParts);
852 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
853 $urlParts[$hostKey] = $ufUrlParts['host'];
854 $url = implode('/', $urlParts);
864 * Find any users/roles/security-principals with the given permission
865 * and replace it with one or more permissions.
867 * @param $oldPerm string
868 * @param $newPerms array, strings
872 function replacePermission($oldPerm, $newPerms) {
873 $roles = user_roles(FALSE, $oldPerm);
874 foreach ($roles as $rid => $roleName) {
875 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
876 $perms = drupal_map_assoc(explode(', ', $permList));
877 unset($perms[$oldPerm]);
878 $perms = $perms +
drupal_map_assoc($newPerms);
879 $permList = implode(', ', $perms);
880 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
882 if ( ! empty( $roles ) ) {
883 $rids = implode(',', array_keys($roles));
884 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
885 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
886 $oldPerm, implode(', ', $newPerms) );*/
891 * Get a list of all installed modules, including enabled and disabled ones
893 * @return array CRM_Core_Module
895 function getModules() {
897 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
898 while ($row = db_fetch_object($q)) {
899 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
905 * Get user login URL for hosting CMS (method declared in each CMS system class)
907 * @param string $destination - if present, add destination to querystring (works for Drupal only)
909 * @return string - loginURL for the current CMS
912 public function getLoginURL($destination = '') {
913 $config = CRM_Core_Config
::singleton();
914 $loginURL = $config->userFrameworkBaseURL
;
916 if (!empty($destination)) {
917 // append destination so user is returned to form they came from after login
918 $loginURL .= '?destination=' . urlencode($destination);
924 * Wrapper for og_membership creation
926 * @param integer $ogID Organic Group ID
927 * @param integer $drupalID drupal User ID
929 function og_membership_create($ogID, $drupalID){
930 og_save_subscription( $ogID, $drupalID, array( 'is_active' => 1 ) );
934 * Wrapper for og_membership deletion
936 * @param integer $ogID Organic Group ID
937 * @param integer $drupalID drupal User ID
939 function og_membership_delete($ogID, $drupalID) {
940 og_delete_subscription( $ogID, $drupalID );
944 * Over-ridable function to get timezone as a string eg.
945 * @return string Timezone e.g. 'America/Los_Angeles'
947 function getTimeZoneString() {
949 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
950 $timezone = $user->timezone
;
952 $timezone = variable_get('date_default_timezone', null);
955 $timezone = parent
::getTimeZoneString();
962 * Reset any system caches that may be required for proper CiviCRM
966 drupal_flush_all_caches();