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
46 * The content that will be themed.
48 * Are we displaying to the screen or bypassing theming?.
49 * @param bool $maintenance
50 * For maintenance mode.
53 * prints content on stdout
55 public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
56 // TODO: Simplify; this was copied verbatim from CiviCRM 3.4's multi-UF theming function, but that's more complex than necessary
57 if (function_exists('theme') && !$print) {
59 drupal_set_breadcrumb('');
60 drupal_maintenance_theme();
63 // Arg 3 for D6 theme() is "show_blocks". Previously, we passed
64 // through a badly named variable ("$args") which was almost always
65 // TRUE (except on fatal error screen). However, this feature is
66 // non-functional on D6 default themes, was purposefully removed from
67 // D7, has no analog in other our other CMS's, and clutters the code.
68 // Hard-wiring to TRUE should be OK.
69 $out = theme('page', $content, TRUE);
79 * Create a user in Drupal.
81 * @param array $params
83 * Email id for cms user.
86 * uid if user exists, false otherwise
88 public function createUser(&$params, $mail) {
89 $form_state = array();
90 $form_state['values'] = array(
91 'name' => $params['cms_name'],
92 'mail' => $params[$mail],
93 'op' => 'Create new account',
96 $admin = user_access('administer users');
97 if (!variable_get('user_email_verification', TRUE) ||
$admin) {
98 $form_state['values']['pass']['pass1'] = $params['cms_pass'];
99 $form_state['values']['pass']['pass2'] = $params['cms_pass'];
102 $config = CRM_Core_Config
::singleton();
104 // we also need to redirect b
105 $config->inCiviCRM
= TRUE;
107 $form = drupal_retrieve_form('user_register', $form_state);
108 $form['#post'] = $form_state['values'];
109 drupal_prepare_form('user_register', $form, $form_state);
111 // remove the captcha element from the form prior to processing
112 unset($form['captcha']);
114 drupal_process_form('user_register', $form, $form_state);
116 $config->inCiviCRM
= FALSE;
118 if (form_get_errors() ||
!isset($form_state['user'])) {
121 return $form_state['user']->uid
;
125 * Change user name in host CMS
127 * @param int $ufID User ID in CMS
128 * @param string $ufName User name
130 public function updateCMSName($ufID, $ufName) {
132 if (function_exists('user_load')) {
133 $user = user_load(array('uid' => $ufID));
134 if ($user->mail
!= $ufName) {
135 user_save($user, array('mail' => $ufName));
136 $user = user_load(array('uid' => $ufID));
142 * Check if username and email exists in the drupal db
144 * @param array $params
145 * Array of name and mail values.
146 * @param array $errors
148 * @param string $emailName
149 * Field label for the 'email'.
153 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
154 $config = CRM_Core_Config
::singleton();
156 $dao = new CRM_Core_DAO();
157 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
158 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
159 _user_edit_validate(NULL, $params);
160 $errors = form_get_errors();
162 if (!empty($errors['name'])) {
163 $errors['cms_name'] = $errors['name'];
165 if (!empty($errors['mail'])) {
166 $errors[$emailName] = $errors['mail'];
168 // also unset drupal messages to avoid twice display of errors
169 unset($_SESSION['messages']);
172 // Do the name check manually.
173 $nameError = user_validate_name($params['name']);
175 $errors['cms_name'] = $nameError;
181 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))
184 $result = db_query($sql);
185 $row = db_fetch_array($result);
193 $dbName = CRM_Utils_Array
::value('name', $row);
194 $dbEmail = CRM_Utils_Array
::value('mail', $row);
195 if (strtolower($dbName) == strtolower($name)) {
196 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
200 if (strtolower($dbEmail) == strtolower($email)) {
202 $errors[$emailName] = ts('You cannot create an email account for a contact with no email',
207 $errors[$emailName] = ts('This email %1 is already registered. Please select another email.',
216 * Get the drupal destination string. When this is passed in the
217 * URL the user will be directed to it after filling in the drupal form
219 * @param CRM_Core_Form $form
220 * Form object representing the 'current' form - to which the user will be returned.
222 * destination value for URL
224 public function getLoginDestination(&$form) {
227 $id = $form->get('id');
232 $gid = $form->get('gid');
234 $args .= "&gid=$gid";
237 // Setup Personal Campaign Page link uses pageId
238 $pageId = $form->get('pageId');
240 $component = $form->get('component');
241 $args .= "&pageId=$pageId&component=$component&action=add";
248 // append destination so user is returned to form they came from after login
249 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
255 * Sets the title of the page
257 * @param string $title
258 * @param null $pageTitle
260 * @paqram string $pageTitle
264 public function setTitle($title, $pageTitle = NULL) {
268 if (arg(0) == 'civicrm') {
270 drupal_set_title($pageTitle);
275 * Append an additional breadcrumb tag to the existing breadcrumb
277 * @param $breadCrumbs
279 * @internal param string $title
280 * @internal param string $url
284 public function appendBreadCrumb($breadCrumbs) {
285 $breadCrumb = drupal_get_breadcrumb();
287 if (is_array($breadCrumbs)) {
288 foreach ($breadCrumbs as $crumbs) {
289 if (stripos($crumbs['url'], 'id%%')) {
290 $args = array('cid', 'mid');
291 foreach ($args as $a) {
292 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
296 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
300 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
303 drupal_set_breadcrumb($breadCrumb);
307 * Reset an additional breadcrumb tag to the existing breadcrumb
311 public function resetBreadCrumb() {
313 drupal_set_breadcrumb($bc);
317 * Append a string to the head of the html file
319 * @param string $head
320 * The new string to be appended.
324 public function addHTMLHead($head) {
325 drupal_set_html_head($head);
331 * @param $url : string, absolute path to file
332 * @param string $region
333 * location within the document: 'html-header', 'page-header', 'page-footer'.
335 * Note: This function is not to be called directly
336 * @see CRM_Core_Region::render()
339 * TRUE if we support this operation in this CMS, FALSE otherwise
341 public function addScriptUrl($url, $region) {
342 // CRM-15450 - D6 doesn't order internal/external links correctly so we can't use drupal_add_js
347 * Add an inline script
349 * @param $code : string, javascript code
350 * @param string $region
351 * location within the document: 'html-header', 'page-header', 'page-footer'.
353 * Note: This function is not to be called directly
354 * @see CRM_Core_Region::render()
357 * TRUE if we support this operation in this CMS, FALSE otherwise
359 public function addScript($code, $region) {
360 // CRM-15450 - ensure scripts are in correct order
367 * @param $url : string, absolute path to file
368 * @param string $region
369 * location within the document: 'html-header', 'page-header', 'page-footer'.
371 * Note: This function is not to be called directly
372 * @see CRM_Core_Region::render()
375 * TRUE if we support this operation in this CMS, FALSE otherwise
377 public function addStyleUrl($url, $region) {
378 if ($region != 'html-header' ||
!$this->formatResourceUrl($url)) {
381 drupal_add_css($url);
386 * Add an inline style
388 * @param $code : string, css code
389 * @param string $region
390 * 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()
396 * TRUE if we support this operation in this CMS, FALSE otherwise
398 public function addStyle($code, $region) {
403 * Rewrite various system urls to https
409 public function mapConfigToSSL() {
411 $base_url = str_replace('http://', 'https://', $base_url);
415 * Figure out the post url for the form
418 * The default action if one is pre-specified.
421 * the url to post the form
423 public 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
436 * @param string $password
437 * The password for the above user name.
438 * @param bool $loadCMSBootstrap
439 * Load cms bootstrap?.
440 * @param NULL|string $realPath filename of script
443 * [contactID, ufID, uniqueString] if success else false if no auth
445 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
446 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
448 // probably if bootstrap is loaded this call
449 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
450 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
451 // safe in the unknown situation where authenticate might be called & it is important that
453 require_once 'DB.php';
455 $config = CRM_Core_Config
::singleton();
457 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
458 if (DB
::isError($dbDrupal)) {
459 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
462 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
463 $dbpassword = md5($password);
464 $name = $dbDrupal->escapeSimple($strtolower($name));
465 $sql = 'SELECT u.* FROM ' . $config->userFrameworkUsersTableName
. " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
466 $query = $dbDrupal->query($sql);
469 // need to change this to make sure we matched only one row
470 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC
)) {
471 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
472 $contactID = CRM_Core_BAO_UFMatch
::getContactId($row['uid']);
477 if ($loadCMSBootstrap) {
478 $bootStrapParams = array();
479 if ($name && $password) {
480 $bootStrapParams = array(
485 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
487 return array($contactID, $row['uid'], mt_rand());
494 * Load user into session
496 public function loadUser($username) {
498 $user = user_load(array('name' => $username));
499 if (empty($user->uid
)) {
504 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
506 // lets store contact id and user id in session
507 $session = CRM_Core_Session
::singleton();
508 $session->set('ufID', $uid);
509 $session->set('userID', $contact_id);
514 * Perform any post login activities required by the UF -
515 * e.g. for drupal : records a watchdog message about the new session,
516 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
518 * @param array params
520 * FIXME: Document values accepted/required by $params
522 public function userLoginFinalize($params = array()) {
523 user_authenticate_finalize($params);
527 * Determine the native ID of the CMS user
529 * @param string $username
532 public function getUfId($username) {
533 $user = user_load(array('name' => $username));
534 if (empty($user->uid
)) {
541 * Set a message in the UF to display to a user
543 * @param string $message
544 * The message to set.
546 public function setMessage($message) {
547 drupal_set_message($message);
553 public function logout() {
554 module_load_include('inc', 'user', 'user.pages');
555 return user_logout();
558 public 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
569 * with the locale or null for none
571 public function getUFLocale() {
572 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
573 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
574 // sometimes for CLI based on order called, this might not be set and/or empty
577 if (empty($language)) {
581 if ($language->language
== 'zh-hans') {
585 if ($language->language
== 'zh-hant') {
589 if (preg_match('/^.._..$/', $language->language
)) {
590 return $language->language
;
593 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
599 public function getVersion() {
600 return defined('VERSION') ? VERSION
: 'Unknown';
604 * Load drupal bootstrap
606 * @param array $params
607 * Either uid, or name & pass.
608 * @param bool $loadUser
609 * Boolean Require CMS user load.
610 * @param bool $throwError
611 * If true, print error on failure and exit.
612 * @param bool|string $realPath path to script
616 public 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);
718 public function cmsRootPath($scriptFilename = NULL) {
719 $cmsRoot = $valid = NULL;
721 if (!is_null($scriptFilename)) {
722 $path = $scriptFilename;
725 $path = $_SERVER['SCRIPT_FILENAME'];
728 if (function_exists('drush_get_context')) {
729 // drush anyway takes care of multisite install etc
730 return drush_get_context('DRUSH_DRUPAL_ROOT');
733 $pathVars = explode('/',
734 str_replace('//', '/',
735 str_replace('\\', '/', $path)
739 //lets store first var,
740 //need to get back for windows.
741 $firstVar = array_shift($pathVars);
743 //lets remove sript name to reduce one iteration.
744 array_pop($pathVars);
746 //CRM-7429 --do check for upper most 'includes' dir,
747 //which would effectually work for multisite installation.
749 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
750 $cmsIncludePath = "$cmsRoot/includes";
751 // Stop if we found bootstrap.
752 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
756 //remove one directory level.
757 array_pop($pathVars);
758 } while (count($pathVars));
760 return ($valid) ?
$cmsRoot : NULL;
764 * Check is user logged in.
768 public function isUserLoggedIn() {
770 if (function_exists('user_is_logged_in')) {
771 $isloggedIn = user_is_logged_in();
778 * Get currently logged in user uf id.
781 * $userID logged in user uf id.
783 public function getLoggedInUfID() {
785 if (function_exists('user_is_logged_in') &&
786 user_is_logged_in() &&
787 function_exists('user_uid_optional_to_arg')
789 $ufID = user_uid_optional_to_arg(array());
796 * Format the url as per language Negotiation.
800 * @param bool $addLanguagePart
801 * @param bool $removeLanguagePart
807 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
812 //upto d6 only, already we have code in place for d7
813 $config = CRM_Core_Config
::singleton();
814 if (function_exists('variable_get') &&
815 module_exists('locale')
820 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE
);
823 if (isset($language->prefix
) &&
825 in_array($mode, array(
826 LANGUAGE_NEGOTIATION_PATH
,
827 LANGUAGE_NEGOTIATION_PATH_DEFAULT
,
831 if ($addLanguagePart) {
832 $url .= $language->prefix
. '/';
834 if ($removeLanguagePart) {
835 $url = str_replace("/{$language->prefix}/", '/', $url);
838 if (isset($language->domain
) &&
840 $mode == LANGUAGE_NEGOTIATION_DOMAIN
843 if ($addLanguagePart) {
844 $url = CRM_Utils_File
::addTrailingSlash($language->domain
, '/');
846 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
847 $url = str_replace('\\', '/', $url);
848 $parseUrl = parse_url($url);
850 //kinda hackish but not sure how to do it right
851 //hope http_build_url() will help at some point.
852 if (is_array($parseUrl) && !empty($parseUrl)) {
853 $urlParts = explode('/', $url);
854 $hostKey = array_search($parseUrl['host'], $urlParts);
855 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
856 $urlParts[$hostKey] = $ufUrlParts['host'];
857 $url = implode('/', $urlParts);
867 * Find any users/roles/security-principals with the given permission
868 * and replace it with one or more permissions.
870 * @param string $oldPerm
871 * @param array $newPerms
876 public function replacePermission($oldPerm, $newPerms) {
877 $roles = user_roles(FALSE, $oldPerm);
878 foreach ($roles as $rid => $roleName) {
879 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
880 $perms = drupal_map_assoc(explode(', ', $permList));
881 unset($perms[$oldPerm]);
882 $perms = $perms +
drupal_map_assoc($newPerms);
883 $permList = implode(', ', $perms);
884 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
886 if ( ! empty( $roles ) ) {
887 $rids = implode(',', array_keys($roles));
888 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
889 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
890 $oldPerm, implode(', ', $newPerms) );*/
895 * Get a list of all installed modules, including enabled and disabled ones
900 public function getModules() {
902 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
903 while ($row = db_fetch_object($q)) {
904 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
910 * Get user login URL for hosting CMS (method declared in each CMS system class)
912 * @param string $destination
913 * If present, add destination to querystring (works for Drupal only).
916 * loginURL for the current CMS
919 public function getLoginURL($destination = '') {
920 $config = CRM_Core_Config
::singleton();
921 $loginURL = $config->userFrameworkBaseURL
;
923 if (!empty($destination)) {
924 // append destination so user is returned to form they came from after login
925 $loginURL .= '?destination=' . urlencode($destination);
931 * Wrapper for og_membership creation
935 * @param int $drupalID
938 public function og_membership_create($ogID, $drupalID) {
939 og_save_subscription($ogID, $drupalID, array('is_active' => 1));
943 * Wrapper for og_membership deletion
947 * @param int $drupalID
950 public function og_membership_delete($ogID, $drupalID) {
951 og_delete_subscription($ogID, $drupalID);
955 * Over-ridable function to get timezone as a string eg.
957 * Timezone e.g. 'America/Los_Angeles'
959 public function getTimeZoneString() {
961 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
962 $timezone = $user->timezone
;
965 $timezone = variable_get('date_default_timezone', NULL);
968 $timezone = parent
::getTimeZoneString();
975 * Reset any system caches that may be required for proper CiviCRM
978 public function flush() {
979 drupal_flush_all_caches();