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) {
348 $scope = substr($region, 5);
353 // If the path is within the drupal directory we can add in the normal way
354 if ($this->formatResourceUrl($url)) {
355 drupal_add_js($url, 'module', $scope);
362 * Add an inline script
364 * @param $code: string, javascript code
365 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
367 * Note: This function is not to be called directly
368 * @see CRM_Core_Region::render()
370 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
373 public function addScript($code, $region) {
377 $scope = substr($region, 5);
382 drupal_add_js($code, 'inline', $scope);
389 * @param $url: string, absolute path to file
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 addStyleUrl($url, $region) {
399 if ($region != 'html-header' ||
!$this->formatResourceUrl($url)) {
402 drupal_add_css($url);
407 * Add an inline style
409 * @param $code: string, css code
410 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
412 * Note: This function is not to be called directly
413 * @see CRM_Core_Region::render()
415 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
418 public function addStyle($code, $region) {
423 * rewrite various system urls to https
430 function mapConfigToSSL() {
432 $base_url = str_replace('http://', 'https://', $base_url);
436 * figure out the post url for the form
438 * @param mix $action the default action if one is pre-specified
440 * @return string the url to post the form
443 function postURL($action) {
444 if (!empty($action)) {
448 return $this->url($_GET['q']);
452 * Authenticate the user against the drupal db
454 * @param string $name the user name
455 * @param string $password the password for the above user name
456 * @param boolean $loadCMSBootstrap load cms bootstrap?
457 * @param NULL|string $realPath filename of script
459 * @return mixed false if no auth
461 * contactID, ufID, unique string ) if success
464 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
465 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
467 // probably if bootstrap is loaded this call
468 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
469 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
470 // safe in the unknown situation where authenticate might be called & it is important that
472 require_once 'DB.php';
474 $config = CRM_Core_Config
::singleton();
476 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
477 if (DB
::isError($dbDrupal)) {
478 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
481 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
482 $dbpassword = md5($password);
483 $name = $dbDrupal->escapeSimple($strtolower($name));
484 $sql = 'SELECT u.* FROM ' . $config->userFrameworkUsersTableName
. " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
485 $query = $dbDrupal->query($sql);
488 // need to change this to make sure we matched only one row
489 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC
)) {
490 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
491 $contactID = CRM_Core_BAO_UFMatch
::getContactId($row['uid']);
496 if ($loadCMSBootstrap) {
497 $bootStrapParams = array();
498 if ($name && $password) {
499 $bootStrapParams = array(
504 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
506 return array($contactID, $row['uid'], mt_rand());
513 * Load user into session
515 function loadUser($username) {
517 $user = user_load(array('name' => $username));
518 if (empty($user->uid
)) {
523 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
525 // lets store contact id and user id in session
526 $session = CRM_Core_Session
::singleton();
527 $session->set('ufID', $uid);
528 $session->set('userID', $contact_id);
533 * Perform any post login activities required by the UF -
534 * e.g. for drupal : records a watchdog message about the new session,
535 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
537 * @param array params
539 * FIXME: Document values accepted/required by $params
541 function userLoginFinalize($params = array()) {
542 user_authenticate_finalize($params);
546 * Determine the native ID of the CMS user
551 function getUfId($username) {
552 $user = user_load(array('name' => $username));
553 if (empty($user->uid
)) {
560 * Set a message in the UF to display to a user
562 * @param string $message the message to set
566 function setMessage($message) {
567 drupal_set_message($message);
574 module_load_include('inc', 'user', 'user.pages');
575 return user_logout();
578 function updateCategories() {
579 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
586 * Get the locale set in the hosting CMS
588 * @return string with the locale or null for none
590 function getUFLocale() {
591 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
592 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
593 // sometimes for CLI based on order called, this might not be set and/or empty
596 if (empty($language)) {
600 if ($language->language
== 'zh-hans') {
604 if ($language->language
== 'zh-hant') {
608 if (preg_match('/^.._..$/', $language->language
)) {
609 return $language->language
;
612 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
618 function getVersion() {
619 return defined('VERSION') ? VERSION
: 'Unknown';
623 * load drupal bootstrap
625 * @param array $params Either uid, or name & pass.
626 * @param boolean $loadUser boolean Require CMS user load.
627 * @param boolean $throwError If true, print error on failure and exit.
628 * @param boolean|string $realPath path to script
632 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
633 //take the cms root path.
634 $cmsPath = $this->cmsRootPath($realPath);
636 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
638 echo '<br />Sorry, could not locate bootstrap.inc\n';
643 // load drupal bootstrap
645 define('DRUPAL_ROOT', $cmsPath);
647 // For drupal multi-site CRM-11313
648 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
649 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
650 if (!empty($matches[1])) {
651 $_SERVER['HTTP_HOST'] = $matches[1];
654 require_once 'includes/bootstrap.inc';
655 // @ to suppress notices eg 'DRUPALFOO already defined'.
656 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
658 // explicitly setting error reporting, since we cannot handle drupal related notices
660 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
662 echo '<br />Sorry, could not load drupal bootstrap.';
668 // seems like we've bootstrapped drupal
669 $config = CRM_Core_Config
::singleton();
671 // lets also fix the clean url setting
673 $config->cleanURL
= (int) variable_get('clean_url', '0');
675 // we need to call the config hook again, since we now know
676 // all the modules that are listening on it, does not apply
677 // to J! and WP as yet
679 CRM_Utils_Hook
::config($config);
685 // If $uid is passed in, authentication has been done already.
686 $uid = CRM_Utils_Array
::value('uid', $params);
688 //load user, we need to check drupal permissions.
689 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
690 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
693 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
696 echo '<br />Sorry, unrecognized username or password.';
708 $account = user_load($uid);
709 if ($account && $account->uid
) {
716 echo '<br />Sorry, can not load CMS user account.';
720 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
721 // which means that define(CIVICRM_CLEANURL) was correctly set.
723 $config = CRM_Core_Config
::singleton();
724 $config->cleanURL
= (int)variable_get('clean_url', '0');
726 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
727 CRM_Utils_Hook
::config($config);
735 function cmsRootPath($scriptFilename = NULL) {
736 $cmsRoot = $valid = NULL;
738 if (!is_null($scriptFilename)) {
739 $path = $scriptFilename;
742 $path = $_SERVER['SCRIPT_FILENAME'];
745 if (function_exists('drush_get_context')) {
746 // drush anyway takes care of multisite install etc
747 return drush_get_context('DRUSH_DRUPAL_ROOT');
750 $pathVars = explode('/',
751 str_replace('//', '/',
752 str_replace('\\', '/', $path)
756 //lets store first var,
757 //need to get back for windows.
758 $firstVar = array_shift($pathVars);
760 //lets remove sript name to reduce one iteration.
761 array_pop($pathVars);
763 //CRM-7429 --do check for upper most 'includes' dir,
764 //which would effectually work for multisite installation.
766 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
767 $cmsIncludePath = "$cmsRoot/includes";
768 //stop as we found bootstrap.
769 if (@opendir
($cmsIncludePath) &&
770 file_exists("$cmsIncludePath/bootstrap.inc")
775 //remove one directory level.
776 array_pop($pathVars);
777 } while (count($pathVars));
779 return ($valid) ?
$cmsRoot : NULL;
783 * check is user logged in.
785 * @return boolean true/false.
787 public function isUserLoggedIn() {
789 if (function_exists('user_is_logged_in')) {
790 $isloggedIn = user_is_logged_in();
797 * Get currently logged in user uf id.
799 * @return int $userID logged in user uf id.
801 public function getLoggedInUfID() {
803 if (function_exists('user_is_logged_in') &&
804 user_is_logged_in() &&
805 function_exists('user_uid_optional_to_arg')
807 $ufID = user_uid_optional_to_arg(array());
814 * Format the url as per language Negotiation.
818 * @param bool $addLanguagePart
819 * @param bool $removeLanguagePart
821 * @return string $url, formatted url.
824 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
829 //upto d6 only, already we have code in place for d7
830 $config = CRM_Core_Config
::singleton();
831 if (function_exists('variable_get') &&
832 module_exists('locale')
837 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE
);
840 if (isset($language->prefix
) &&
842 in_array($mode, array(
843 LANGUAGE_NEGOTIATION_PATH
,
844 LANGUAGE_NEGOTIATION_PATH_DEFAULT
,
848 if ($addLanguagePart) {
849 $url .= $language->prefix
. '/';
851 if ($removeLanguagePart) {
852 $url = str_replace("/{$language->prefix}/", '/', $url);
855 if (isset($language->domain
) &&
857 $mode == LANGUAGE_NEGOTIATION_DOMAIN
860 if ($addLanguagePart) {
861 $url = CRM_Utils_File
::addTrailingSlash($language->domain
, '/');
863 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
864 $url = str_replace('\\', '/', $url);
865 $parseUrl = parse_url($url);
867 //kinda hackish but not sure how to do it right
868 //hope http_build_url() will help at some point.
869 if (is_array($parseUrl) && !empty($parseUrl)) {
870 $urlParts = explode('/', $url);
871 $hostKey = array_search($parseUrl['host'], $urlParts);
872 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
873 $urlParts[$hostKey] = $ufUrlParts['host'];
874 $url = implode('/', $urlParts);
884 * Find any users/roles/security-principals with the given permission
885 * and replace it with one or more permissions.
887 * @param $oldPerm string
888 * @param $newPerms array, strings
892 function replacePermission($oldPerm, $newPerms) {
893 $roles = user_roles(FALSE, $oldPerm);
894 foreach ($roles as $rid => $roleName) {
895 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
896 $perms = drupal_map_assoc(explode(', ', $permList));
897 unset($perms[$oldPerm]);
898 $perms = $perms +
drupal_map_assoc($newPerms);
899 $permList = implode(', ', $perms);
900 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
902 if ( ! empty( $roles ) ) {
903 $rids = implode(',', array_keys($roles));
904 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
905 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
906 $oldPerm, implode(', ', $newPerms) );*/
911 * Get a list of all installed modules, including enabled and disabled ones
913 * @return array CRM_Core_Module
915 function getModules() {
917 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
918 while ($row = db_fetch_object($q)) {
919 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
925 * Get user login URL for hosting CMS (method declared in each CMS system class)
927 * @param string $destination - if present, add destination to querystring (works for Drupal only)
929 * @return string - loginURL for the current CMS
932 public function getLoginURL($destination = '') {
933 $config = CRM_Core_Config
::singleton();
934 $loginURL = $config->userFrameworkBaseURL
;
936 if (!empty($destination)) {
937 // append destination so user is returned to form they came from after login
938 $loginURL .= '?destination=' . urlencode($destination);
944 * Wrapper for og_membership creation
946 * @param integer $ogID Organic Group ID
947 * @param integer $drupalID drupal User ID
949 function og_membership_create($ogID, $drupalID){
950 og_save_subscription( $ogID, $drupalID, array( 'is_active' => 1 ) );
954 * Wrapper for og_membership deletion
956 * @param integer $ogID Organic Group ID
957 * @param integer $drupalID drupal User ID
959 function og_membership_delete($ogID, $drupalID) {
960 og_delete_subscription( $ogID, $drupalID );
964 * Over-ridable function to get timezone as a string eg.
965 * @return string Timezone e.g. 'America/Los_Angeles'
967 function getTimeZoneString() {
969 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
970 $timezone = $user->timezone
;
972 $timezone = variable_get('date_default_timezone', null);
975 $timezone = parent
::getTimeZoneString();
982 * Reset any system caches that may be required for proper CiviCRM
986 drupal_flush_all_caches();