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_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
51 public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
52 // TODO: Simplify; this was copied verbatim from CiviCRM 3.4's multi-UF theming function, but that's more complex than necessary
53 if (function_exists('theme') && !$print) {
55 drupal_set_breadcrumb('');
56 drupal_maintenance_theme();
59 // Arg 3 for D6 theme() is "show_blocks". Previously, we passed
60 // through a badly named variable ("$args") which was almost always
61 // TRUE (except on fatal error screen). However, this feature is
62 // non-functional on D6 default themes, was purposefully removed from
63 // D7, has no analog in other our other CMS's, and clutters the code.
64 // Hard-wiring to TRUE should be OK.
65 $out = theme('page', $content, TRUE);
75 * Create a user in Drupal.
77 * @param array $params associated array
78 * @param string $mail email id for cms user
80 * @return uid if user exists, false otherwise
83 public function createUser(&$params, $mail) {
84 $form_state = array();
85 $form_state['values'] = array(
86 'name' => $params['cms_name'],
87 'mail' => $params[$mail],
88 'op' => 'Create new account',
91 $admin = user_access('administer users');
92 if (!variable_get('user_email_verification', TRUE) ||
$admin) {
93 $form_state['values']['pass']['pass1'] = $params['cms_pass'];
94 $form_state['values']['pass']['pass2'] = $params['cms_pass'];
97 $config = CRM_Core_Config
::singleton();
99 // we also need to redirect b
100 $config->inCiviCRM
= TRUE;
102 $form = drupal_retrieve_form('user_register', $form_state);
103 $form['#post'] = $form_state['values'];
104 drupal_prepare_form('user_register', $form, $form_state);
106 // remove the captcha element from the form prior to processing
107 unset($form['captcha']);
109 drupal_process_form('user_register', $form, $form_state);
111 $config->inCiviCRM
= FALSE;
113 if (form_get_errors() ||
!isset($form_state['user'])) {
116 return $form_state['user']->uid
;
120 * Change user name in host CMS
122 * @param integer $ufID User ID in CMS
123 * @param string $ufName User name
127 * @param string $ufName
129 public function updateCMSName($ufID, $ufName) {
131 if (function_exists('user_load')) {
132 $user = user_load(array('uid' => $ufID));
133 if ($user->mail
!= $ufName) {
134 user_save($user, array('mail' => $ufName));
135 $user = user_load(array('uid' => $ufID));
141 * Check if username and email exists in the drupal db
143 * @param array $params array of name and mail values
144 * @param array $errors array of errors
145 * @param string $emailName field label for the 'email'
149 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
150 $config = CRM_Core_Config
::singleton();
152 $dao = new CRM_Core_DAO();
153 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
154 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
155 _user_edit_validate(NULL, $params);
156 $errors = form_get_errors();
158 if (!empty($errors['name'])) {
159 $errors['cms_name'] = $errors['name'];
161 if (!empty($errors['mail'])) {
162 $errors[$emailName] = $errors['mail'];
164 // also unset drupal messages to avoid twice display of errors
165 unset($_SESSION['messages']);
168 // Do the name check manually.
169 $nameError = user_validate_name($params['name']);
171 $errors['cms_name'] = $nameError;
177 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))
180 $result = db_query($sql);
181 $row = db_fetch_array($result);
189 $dbName = CRM_Utils_Array
::value('name', $row);
190 $dbEmail = CRM_Utils_Array
::value('mail', $row);
191 if (strtolower($dbName) == strtolower($name)) {
192 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
196 if (strtolower($dbEmail) == strtolower($email)) {
198 $errors[$emailName] = ts('You cannot create an email account for a contact with no email',
203 $errors[$emailName] = ts('This email %1 is already registered. Please select another email.',
212 * Get the drupal destination string. When this is passed in the
213 * URL the user will be directed to it after filling in the drupal form
215 * @param CRM_Core_Form $form Form object representing the 'current' form - to which the user will be returned
216 * @return string $destination destination value for URL
219 public function getLoginDestination(&$form) {
222 $id = $form->get('id');
227 $gid = $form->get('gid');
229 $args .= "&gid=$gid";
232 // Setup Personal Campaign Page link uses pageId
233 $pageId = $form->get('pageId');
235 $component = $form->get('component');
236 $args .= "&pageId=$pageId&component=$component&action=add";
243 // append destination so user is returned to form they came from after login
244 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
250 * Sets the title of the page
252 * @param string $title
253 * @param null $pageTitle
255 * @paqram string $pageTitle
259 public function setTitle($title, $pageTitle = NULL) {
263 if (arg(0) == 'civicrm') {
265 drupal_set_title($pageTitle);
270 * Append an additional breadcrumb tag to the existing breadcrumb
272 * @param $breadCrumbs
274 * @internal param string $title
275 * @internal param string $url
279 public function appendBreadCrumb($breadCrumbs) {
280 $breadCrumb = drupal_get_breadcrumb();
282 if (is_array($breadCrumbs)) {
283 foreach ($breadCrumbs as $crumbs) {
284 if (stripos($crumbs['url'], 'id%%')) {
285 $args = array('cid', 'mid');
286 foreach ($args as $a) {
287 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
291 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
295 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
298 drupal_set_breadcrumb($breadCrumb);
302 * Reset an additional breadcrumb tag to the existing breadcrumb
306 public function resetBreadCrumb() {
308 drupal_set_breadcrumb($bc);
312 * Append a string to the head of the html file
314 * @param string $head the new string to be appended
318 public function addHTMLHead($head) {
319 drupal_set_html_head($head);
325 * @param $url: string, absolute path to file
326 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
328 * Note: This function is not to be called directly
329 * @see CRM_Core_Region::render()
331 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
333 public function addScriptUrl($url, $region) {
334 // CRM-15450 - D6 doesn't order internal/external links correctly so we can't use drupal_add_js
339 * Add an inline script
341 * @param $code: string, javascript code
342 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
344 * Note: This function is not to be called directly
345 * @see CRM_Core_Region::render()
347 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
349 public function addScript($code, $region) {
350 // CRM-15450 - ensure scripts are in correct order
357 * @param $url: string, absolute path to file
358 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
360 * Note: This function is not to be called directly
361 * @see CRM_Core_Region::render()
363 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
365 public function addStyleUrl($url, $region) {
366 if ($region != 'html-header' ||
!$this->formatResourceUrl($url)) {
369 drupal_add_css($url);
374 * Add an inline style
376 * @param $code: string, css code
377 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
379 * Note: This function is not to be called directly
380 * @see CRM_Core_Region::render()
382 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
384 public function addStyle($code, $region) {
389 * Rewrite various system urls to https
395 public function mapConfigToSSL() {
397 $base_url = str_replace('http://', 'https://', $base_url);
401 * Figure out the post url for the form
403 * @param mix $action the default action if one is pre-specified
405 * @return string the url to post the form
407 public function postURL($action) {
408 if (!empty($action)) {
412 return $this->url($_GET['q']);
416 * Authenticate the user against the drupal db
418 * @param string $name the user name
419 * @param string $password the password for the above user name
420 * @param boolean $loadCMSBootstrap load cms bootstrap?
421 * @param NULL|string $realPath filename of script
423 * @return mixed false if no auth
425 * contactID, ufID, unique string ) if success
427 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
428 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
430 // probably if bootstrap is loaded this call
431 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
432 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
433 // safe in the unknown situation where authenticate might be called & it is important that
435 require_once 'DB.php';
437 $config = CRM_Core_Config
::singleton();
439 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
440 if (DB
::isError($dbDrupal)) {
441 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
444 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
445 $dbpassword = md5($password);
446 $name = $dbDrupal->escapeSimple($strtolower($name));
447 $sql = 'SELECT u.* FROM ' . $config->userFrameworkUsersTableName
. " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
448 $query = $dbDrupal->query($sql);
451 // need to change this to make sure we matched only one row
452 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC
)) {
453 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
454 $contactID = CRM_Core_BAO_UFMatch
::getContactId($row['uid']);
459 if ($loadCMSBootstrap) {
460 $bootStrapParams = array();
461 if ($name && $password) {
462 $bootStrapParams = array(
467 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
469 return array($contactID, $row['uid'], mt_rand());
476 * Load user into session
478 public function loadUser($username) {
480 $user = user_load(array('name' => $username));
481 if (empty($user->uid
)) {
486 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
488 // lets store contact id and user id in session
489 $session = CRM_Core_Session
::singleton();
490 $session->set('ufID', $uid);
491 $session->set('userID', $contact_id);
496 * Perform any post login activities required by the UF -
497 * e.g. for drupal : records a watchdog message about the new session,
498 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
500 * @param array params
502 * FIXME: Document values accepted/required by $params
504 public function userLoginFinalize($params = array()) {
505 user_authenticate_finalize($params);
509 * Determine the native ID of the CMS user
511 * @param string $username
514 public function getUfId($username) {
515 $user = user_load(array('name' => $username));
516 if (empty($user->uid
)) {
523 * Set a message in the UF to display to a user
525 * @param string $message the message to set
528 public function setMessage($message) {
529 drupal_set_message($message);
535 public function logout() {
536 module_load_include('inc', 'user', 'user.pages');
537 return user_logout();
540 public function updateCategories() {
541 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
548 * Get the locale set in the hosting CMS
550 * @return string with the locale or null for none
552 public function getUFLocale() {
553 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
554 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
555 // sometimes for CLI based on order called, this might not be set and/or empty
558 if (empty($language)) {
562 if ($language->language
== 'zh-hans') {
566 if ($language->language
== 'zh-hant') {
570 if (preg_match('/^.._..$/', $language->language
)) {
571 return $language->language
;
574 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
580 public function getVersion() {
581 return defined('VERSION') ? VERSION
: 'Unknown';
585 * Load drupal bootstrap
587 * @param array $params Either uid, or name & pass.
588 * @param boolean $loadUser boolean Require CMS user load.
589 * @param boolean $throwError If true, print error on failure and exit.
590 * @param boolean|string $realPath path to script
594 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
595 //take the cms root path.
596 $cmsPath = $this->cmsRootPath($realPath);
598 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
600 echo '<br />Sorry, could not locate bootstrap.inc\n';
605 // load drupal bootstrap
607 define('DRUPAL_ROOT', $cmsPath);
609 // For drupal multi-site CRM-11313
610 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
611 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
612 if (!empty($matches[1])) {
613 $_SERVER['HTTP_HOST'] = $matches[1];
616 require_once 'includes/bootstrap.inc';
617 // @ to suppress notices eg 'DRUPALFOO already defined'.
618 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
620 // explicitly setting error reporting, since we cannot handle drupal related notices
622 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
624 echo '<br />Sorry, could not load drupal bootstrap.';
630 // seems like we've bootstrapped drupal
631 $config = CRM_Core_Config
::singleton();
633 // lets also fix the clean url setting
635 $config->cleanURL
= (int) variable_get('clean_url', '0');
637 // we need to call the config hook again, since we now know
638 // all the modules that are listening on it, does not apply
639 // to J! and WP as yet
641 CRM_Utils_Hook
::config($config);
647 // If $uid is passed in, authentication has been done already.
648 $uid = CRM_Utils_Array
::value('uid', $params);
650 //load user, we need to check drupal permissions.
651 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
652 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
655 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
658 echo '<br />Sorry, unrecognized username or password.';
670 $account = user_load($uid);
671 if ($account && $account->uid
) {
678 echo '<br />Sorry, can not load CMS user account.';
682 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
683 // which means that define(CIVICRM_CLEANURL) was correctly set.
685 $config = CRM_Core_Config
::singleton();
686 $config->cleanURL
= (int)variable_get('clean_url', '0');
688 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
689 CRM_Utils_Hook
::config($config);
697 public function cmsRootPath($scriptFilename = NULL) {
698 $cmsRoot = $valid = NULL;
700 if (!is_null($scriptFilename)) {
701 $path = $scriptFilename;
704 $path = $_SERVER['SCRIPT_FILENAME'];
707 if (function_exists('drush_get_context')) {
708 // drush anyway takes care of multisite install etc
709 return drush_get_context('DRUSH_DRUPAL_ROOT');
712 $pathVars = explode('/',
713 str_replace('//', '/',
714 str_replace('\\', '/', $path)
718 //lets store first var,
719 //need to get back for windows.
720 $firstVar = array_shift($pathVars);
722 //lets remove sript name to reduce one iteration.
723 array_pop($pathVars);
725 //CRM-7429 --do check for upper most 'includes' dir,
726 //which would effectually work for multisite installation.
728 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
729 $cmsIncludePath = "$cmsRoot/includes";
730 //stop as we found bootstrap.
731 if (@opendir
($cmsIncludePath) &&
732 file_exists("$cmsIncludePath/bootstrap.inc")
737 //remove one directory level.
738 array_pop($pathVars);
739 } while (count($pathVars));
741 return ($valid) ?
$cmsRoot : NULL;
745 * Check is user logged in.
747 * @return boolean true/false.
749 public function isUserLoggedIn() {
751 if (function_exists('user_is_logged_in')) {
752 $isloggedIn = user_is_logged_in();
759 * Get currently logged in user uf id.
761 * @return int $userID logged in user uf id.
763 public function getLoggedInUfID() {
765 if (function_exists('user_is_logged_in') &&
766 user_is_logged_in() &&
767 function_exists('user_uid_optional_to_arg')
769 $ufID = user_uid_optional_to_arg(array());
776 * Format the url as per language Negotiation.
780 * @param bool $addLanguagePart
781 * @param bool $removeLanguagePart
783 * @return string $url, formatted url.
786 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
791 //upto d6 only, already we have code in place for d7
792 $config = CRM_Core_Config
::singleton();
793 if (function_exists('variable_get') &&
794 module_exists('locale')
799 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE
);
802 if (isset($language->prefix
) &&
804 in_array($mode, array(
805 LANGUAGE_NEGOTIATION_PATH
,
806 LANGUAGE_NEGOTIATION_PATH_DEFAULT
,
810 if ($addLanguagePart) {
811 $url .= $language->prefix
. '/';
813 if ($removeLanguagePart) {
814 $url = str_replace("/{$language->prefix}/", '/', $url);
817 if (isset($language->domain
) &&
819 $mode == LANGUAGE_NEGOTIATION_DOMAIN
822 if ($addLanguagePart) {
823 $url = CRM_Utils_File
::addTrailingSlash($language->domain
, '/');
825 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
826 $url = str_replace('\\', '/', $url);
827 $parseUrl = parse_url($url);
829 //kinda hackish but not sure how to do it right
830 //hope http_build_url() will help at some point.
831 if (is_array($parseUrl) && !empty($parseUrl)) {
832 $urlParts = explode('/', $url);
833 $hostKey = array_search($parseUrl['host'], $urlParts);
834 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
835 $urlParts[$hostKey] = $ufUrlParts['host'];
836 $url = implode('/', $urlParts);
846 * Find any users/roles/security-principals with the given permission
847 * and replace it with one or more permissions.
849 * @param $oldPerm string
850 * @param $newPerms array, strings
854 public function replacePermission($oldPerm, $newPerms) {
855 $roles = user_roles(FALSE, $oldPerm);
856 foreach ($roles as $rid => $roleName) {
857 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
858 $perms = drupal_map_assoc(explode(', ', $permList));
859 unset($perms[$oldPerm]);
860 $perms = $perms +
drupal_map_assoc($newPerms);
861 $permList = implode(', ', $perms);
862 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
864 if ( ! empty( $roles ) ) {
865 $rids = implode(',', array_keys($roles));
866 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
867 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
868 $oldPerm, implode(', ', $newPerms) );*/
873 * Get a list of all installed modules, including enabled and disabled ones
875 * @return array CRM_Core_Module
877 public function getModules() {
879 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
880 while ($row = db_fetch_object($q)) {
881 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
887 * Get user login URL for hosting CMS (method declared in each CMS system class)
889 * @param string $destination - if present, add destination to querystring (works for Drupal only)
891 * @return string - loginURL for the current CMS
894 public function getLoginURL($destination = '') {
895 $config = CRM_Core_Config
::singleton();
896 $loginURL = $config->userFrameworkBaseURL
;
898 if (!empty($destination)) {
899 // append destination so user is returned to form they came from after login
900 $loginURL .= '?destination=' . urlencode($destination);
906 * Wrapper for og_membership creation
908 * @param integer $ogID Organic Group ID
909 * @param integer $drupalID drupal User ID
911 public function og_membership_create($ogID, $drupalID){
912 og_save_subscription( $ogID, $drupalID, array( 'is_active' => 1 ) );
916 * Wrapper for og_membership deletion
918 * @param integer $ogID Organic Group ID
919 * @param integer $drupalID drupal User ID
921 public function og_membership_delete($ogID, $drupalID) {
922 og_delete_subscription( $ogID, $drupalID );
926 * Over-ridable function to get timezone as a string eg.
927 * @return string Timezone e.g. 'America/Los_Angeles'
929 public function getTimeZoneString() {
931 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
932 $timezone = $user->timezone
;
934 $timezone = variable_get('date_default_timezone', null);
937 $timezone = parent
::getTimeZoneString();
944 * Reset any system caches that may be required for proper CiviCRM
947 public function flush() {
948 drupal_flush_all_caches();