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
84 * Email id for cms user.
86 * @return 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 integer $ufID User ID in CMS
128 * @param string $ufName User name
132 * @param string $ufName
134 public function updateCMSName($ufID, $ufName) {
136 if (function_exists('user_load')) {
137 $user = user_load(array('uid' => $ufID));
138 if ($user->mail
!= $ufName) {
139 user_save($user, array('mail' => $ufName));
140 $user = user_load(array('uid' => $ufID));
146 * Check if username and email exists in the drupal db
148 * @param array $params
149 * Array of name and mail values.
150 * @param array $errors
152 * @param string $emailName
153 * Field label for the 'email'.
157 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
158 $config = CRM_Core_Config
::singleton();
160 $dao = new CRM_Core_DAO();
161 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
162 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
163 _user_edit_validate(NULL, $params);
164 $errors = form_get_errors();
166 if (!empty($errors['name'])) {
167 $errors['cms_name'] = $errors['name'];
169 if (!empty($errors['mail'])) {
170 $errors[$emailName] = $errors['mail'];
172 // also unset drupal messages to avoid twice display of errors
173 unset($_SESSION['messages']);
176 // Do the name check manually.
177 $nameError = user_validate_name($params['name']);
179 $errors['cms_name'] = $nameError;
185 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))
188 $result = db_query($sql);
189 $row = db_fetch_array($result);
197 $dbName = CRM_Utils_Array
::value('name', $row);
198 $dbEmail = CRM_Utils_Array
::value('mail', $row);
199 if (strtolower($dbName) == strtolower($name)) {
200 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
204 if (strtolower($dbEmail) == strtolower($email)) {
206 $errors[$emailName] = ts('You cannot create an email account for a contact with no email',
211 $errors[$emailName] = ts('This email %1 is already registered. Please select another email.',
220 * Get the drupal destination string. When this is passed in the
221 * URL the user will be directed to it after filling in the drupal form
223 * @param CRM_Core_Form $form
224 * Form object representing the 'current' form - to which the user will be returned.
226 * destination value for URL
228 public function getLoginDestination(&$form) {
231 $id = $form->get('id');
236 $gid = $form->get('gid');
238 $args .= "&gid=$gid";
241 // Setup Personal Campaign Page link uses pageId
242 $pageId = $form->get('pageId');
244 $component = $form->get('component');
245 $args .= "&pageId=$pageId&component=$component&action=add";
252 // append destination so user is returned to form they came from after login
253 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
259 * Sets the title of the page
261 * @param string $title
262 * @param null $pageTitle
264 * @paqram string $pageTitle
268 public function setTitle($title, $pageTitle = NULL) {
272 if (arg(0) == 'civicrm') {
274 drupal_set_title($pageTitle);
279 * Append an additional breadcrumb tag to the existing breadcrumb
281 * @param $breadCrumbs
283 * @internal param string $title
284 * @internal param string $url
288 public function appendBreadCrumb($breadCrumbs) {
289 $breadCrumb = drupal_get_breadcrumb();
291 if (is_array($breadCrumbs)) {
292 foreach ($breadCrumbs as $crumbs) {
293 if (stripos($crumbs['url'], 'id%%')) {
294 $args = array('cid', 'mid');
295 foreach ($args as $a) {
296 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
300 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
304 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
307 drupal_set_breadcrumb($breadCrumb);
311 * Reset an additional breadcrumb tag to the existing breadcrumb
315 public function resetBreadCrumb() {
317 drupal_set_breadcrumb($bc);
321 * Append a string to the head of the html file
323 * @param string $head
324 * The new string to be appended.
328 public function addHTMLHead($head) {
329 drupal_set_html_head($head);
335 * @param $url: string, absolute path to file
336 * @param string $region
337 * location within the document: 'html-header', 'page-header', 'page-footer'.
339 * Note: This function is not to be called directly
340 * @see CRM_Core_Region::render()
343 * TRUE if we support this operation in this CMS, FALSE otherwise
345 public function addScriptUrl($url, $region) {
346 // CRM-15450 - D6 doesn't order internal/external links correctly so we can't use drupal_add_js
351 * Add an inline script
353 * @param $code: string, javascript code
354 * @param string $region
355 * location within the document: 'html-header', 'page-header', 'page-footer'.
357 * Note: This function is not to be called directly
358 * @see CRM_Core_Region::render()
361 * TRUE if we support this operation in this CMS, FALSE otherwise
363 public function addScript($code, $region) {
364 // CRM-15450 - ensure scripts are in correct order
371 * @param $url: string, absolute path to file
372 * @param string $region
373 * location within the document: 'html-header', 'page-header', 'page-footer'.
375 * Note: This function is not to be called directly
376 * @see CRM_Core_Region::render()
379 * TRUE if we support this operation in this CMS, FALSE otherwise
381 public function addStyleUrl($url, $region) {
382 if ($region != 'html-header' ||
!$this->formatResourceUrl($url)) {
385 drupal_add_css($url);
390 * Add an inline style
392 * @param $code: string, css code
393 * @param string $region
394 * location within the document: 'html-header', 'page-header', 'page-footer'.
396 * Note: This function is not to be called directly
397 * @see CRM_Core_Region::render()
400 * TRUE if we support this operation in this CMS, FALSE otherwise
402 public function addStyle($code, $region) {
407 * Rewrite various system urls to https
413 public function mapConfigToSSL() {
415 $base_url = str_replace('http://', 'https://', $base_url);
419 * Figure out the post url for the form
422 * The default action if one is pre-specified.
425 * the url to post the form
427 public function postURL($action) {
428 if (!empty($action)) {
432 return $this->url($_GET['q']);
436 * Authenticate the user against the drupal db
438 * @param string $name
440 * @param string $password
441 * The password for the above user name.
442 * @param bool $loadCMSBootstrap
443 * Load cms bootstrap?.
444 * @param NULL|string $realPath filename of script
446 * @return mixed false if no auth
448 * contactID, ufID, unique string ) if success
450 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
451 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
453 // probably if bootstrap is loaded this call
454 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
455 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
456 // safe in the unknown situation where authenticate might be called & it is important that
458 require_once 'DB.php';
460 $config = CRM_Core_Config
::singleton();
462 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
463 if (DB
::isError($dbDrupal)) {
464 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
467 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
468 $dbpassword = md5($password);
469 $name = $dbDrupal->escapeSimple($strtolower($name));
470 $sql = 'SELECT u.* FROM ' . $config->userFrameworkUsersTableName
. " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
471 $query = $dbDrupal->query($sql);
474 // need to change this to make sure we matched only one row
475 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC
)) {
476 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
477 $contactID = CRM_Core_BAO_UFMatch
::getContactId($row['uid']);
482 if ($loadCMSBootstrap) {
483 $bootStrapParams = array();
484 if ($name && $password) {
485 $bootStrapParams = array(
490 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
492 return array($contactID, $row['uid'], mt_rand());
499 * Load user into session
501 public function loadUser($username) {
503 $user = user_load(array('name' => $username));
504 if (empty($user->uid
)) {
509 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
511 // lets store contact id and user id in session
512 $session = CRM_Core_Session
::singleton();
513 $session->set('ufID', $uid);
514 $session->set('userID', $contact_id);
519 * Perform any post login activities required by the UF -
520 * e.g. for drupal : records a watchdog message about the new session,
521 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
523 * @param array params
525 * FIXME: Document values accepted/required by $params
527 public function userLoginFinalize($params = array()) {
528 user_authenticate_finalize($params);
532 * Determine the native ID of the CMS user
534 * @param string $username
537 public function getUfId($username) {
538 $user = user_load(array('name' => $username));
539 if (empty($user->uid
)) {
546 * Set a message in the UF to display to a user
548 * @param string $message
549 * The message to set.
551 public function setMessage($message) {
552 drupal_set_message($message);
558 public function logout() {
559 module_load_include('inc', 'user', 'user.pages');
560 return user_logout();
563 public function updateCategories() {
564 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
571 * Get the locale set in the hosting CMS
574 * with the locale or null for none
576 public function getUFLocale() {
577 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
578 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
579 // sometimes for CLI based on order called, this might not be set and/or empty
582 if (empty($language)) {
586 if ($language->language
== 'zh-hans') {
590 if ($language->language
== 'zh-hant') {
594 if (preg_match('/^.._..$/', $language->language
)) {
595 return $language->language
;
598 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
604 public function getVersion() {
605 return defined('VERSION') ? VERSION
: 'Unknown';
609 * Load drupal bootstrap
611 * @param array $params
612 * Either uid, or name & pass.
613 * @param bool $loadUser
614 * Boolean Require CMS user load.
615 * @param bool $throwError
616 * If true, print error on failure and exit.
617 * @param bool|string $realPath path to script
621 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
622 //take the cms root path.
623 $cmsPath = $this->cmsRootPath($realPath);
625 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
627 echo '<br />Sorry, could not locate bootstrap.inc\n';
632 // load drupal bootstrap
634 define('DRUPAL_ROOT', $cmsPath);
636 // For drupal multi-site CRM-11313
637 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
638 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
639 if (!empty($matches[1])) {
640 $_SERVER['HTTP_HOST'] = $matches[1];
643 require_once 'includes/bootstrap.inc';
644 // @ to suppress notices eg 'DRUPALFOO already defined'.
645 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
647 // explicitly setting error reporting, since we cannot handle drupal related notices
649 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
651 echo '<br />Sorry, could not load drupal bootstrap.';
657 // seems like we've bootstrapped drupal
658 $config = CRM_Core_Config
::singleton();
660 // lets also fix the clean url setting
662 $config->cleanURL
= (int) variable_get('clean_url', '0');
664 // we need to call the config hook again, since we now know
665 // all the modules that are listening on it, does not apply
666 // to J! and WP as yet
668 CRM_Utils_Hook
::config($config);
674 // If $uid is passed in, authentication has been done already.
675 $uid = CRM_Utils_Array
::value('uid', $params);
677 //load user, we need to check drupal permissions.
678 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
679 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
682 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
685 echo '<br />Sorry, unrecognized username or password.';
697 $account = user_load($uid);
698 if ($account && $account->uid
) {
705 echo '<br />Sorry, can not load CMS user account.';
709 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
710 // which means that define(CIVICRM_CLEANURL) was correctly set.
712 $config = CRM_Core_Config
::singleton();
713 $config->cleanURL
= (int) variable_get('clean_url', '0');
715 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
716 CRM_Utils_Hook
::config($config);
723 public function cmsRootPath($scriptFilename = NULL) {
724 $cmsRoot = $valid = NULL;
726 if (!is_null($scriptFilename)) {
727 $path = $scriptFilename;
730 $path = $_SERVER['SCRIPT_FILENAME'];
733 if (function_exists('drush_get_context')) {
734 // drush anyway takes care of multisite install etc
735 return drush_get_context('DRUSH_DRUPAL_ROOT');
738 $pathVars = explode('/',
739 str_replace('//', '/',
740 str_replace('\\', '/', $path)
744 //lets store first var,
745 //need to get back for windows.
746 $firstVar = array_shift($pathVars);
748 //lets remove sript name to reduce one iteration.
749 array_pop($pathVars);
751 //CRM-7429 --do check for upper most 'includes' dir,
752 //which would effectually work for multisite installation.
754 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
755 $cmsIncludePath = "$cmsRoot/includes";
756 // Stop if we found bootstrap.
757 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
761 //remove one directory level.
762 array_pop($pathVars);
763 } while (count($pathVars));
765 return ($valid) ?
$cmsRoot : NULL;
769 * Check is user logged in.
773 public function isUserLoggedIn() {
775 if (function_exists('user_is_logged_in')) {
776 $isloggedIn = user_is_logged_in();
783 * Get currently logged in user uf id.
786 * $userID logged in user uf id.
788 public function getLoggedInUfID() {
790 if (function_exists('user_is_logged_in') &&
791 user_is_logged_in() &&
792 function_exists('user_uid_optional_to_arg')
794 $ufID = user_uid_optional_to_arg(array());
801 * Format the url as per language Negotiation.
805 * @param bool $addLanguagePart
806 * @param bool $removeLanguagePart
812 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
817 //upto d6 only, already we have code in place for d7
818 $config = CRM_Core_Config
::singleton();
819 if (function_exists('variable_get') &&
820 module_exists('locale')
825 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE
);
828 if (isset($language->prefix
) &&
830 in_array($mode, array(
831 LANGUAGE_NEGOTIATION_PATH
,
832 LANGUAGE_NEGOTIATION_PATH_DEFAULT
,
836 if ($addLanguagePart) {
837 $url .= $language->prefix
. '/';
839 if ($removeLanguagePart) {
840 $url = str_replace("/{$language->prefix}/", '/', $url);
843 if (isset($language->domain
) &&
845 $mode == LANGUAGE_NEGOTIATION_DOMAIN
848 if ($addLanguagePart) {
849 $url = CRM_Utils_File
::addTrailingSlash($language->domain
, '/');
851 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
852 $url = str_replace('\\', '/', $url);
853 $parseUrl = parse_url($url);
855 //kinda hackish but not sure how to do it right
856 //hope http_build_url() will help at some point.
857 if (is_array($parseUrl) && !empty($parseUrl)) {
858 $urlParts = explode('/', $url);
859 $hostKey = array_search($parseUrl['host'], $urlParts);
860 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
861 $urlParts[$hostKey] = $ufUrlParts['host'];
862 $url = implode('/', $urlParts);
872 * Find any users/roles/security-principals with the given permission
873 * and replace it with one or more permissions.
875 * @param string $oldPerm
876 * @param array $newPerms
881 public function replacePermission($oldPerm, $newPerms) {
882 $roles = user_roles(FALSE, $oldPerm);
883 foreach ($roles as $rid => $roleName) {
884 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
885 $perms = drupal_map_assoc(explode(', ', $permList));
886 unset($perms[$oldPerm]);
887 $perms = $perms +
drupal_map_assoc($newPerms);
888 $permList = implode(', ', $perms);
889 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
891 if ( ! empty( $roles ) ) {
892 $rids = implode(',', array_keys($roles));
893 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
894 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
895 $oldPerm, implode(', ', $newPerms) );*/
900 * Get a list of all installed modules, including enabled and disabled ones
905 public function getModules() {
907 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
908 while ($row = db_fetch_object($q)) {
909 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
915 * Get user login URL for hosting CMS (method declared in each CMS system class)
917 * @param string $destination
918 * If present, add destination to querystring (works for Drupal only).
921 * loginURL for the current CMS
924 public function getLoginURL($destination = '') {
925 $config = CRM_Core_Config
::singleton();
926 $loginURL = $config->userFrameworkBaseURL
;
928 if (!empty($destination)) {
929 // append destination so user is returned to form they came from after login
930 $loginURL .= '?destination=' . urlencode($destination);
936 * Wrapper for og_membership creation
940 * @param int $drupalID
943 public function og_membership_create($ogID, $drupalID) {
944 og_save_subscription($ogID, $drupalID, array('is_active' => 1));
948 * Wrapper for og_membership deletion
952 * @param int $drupalID
955 public function og_membership_delete($ogID, $drupalID) {
956 og_delete_subscription($ogID, $drupalID);
960 * Over-ridable function to get timezone as a string eg.
962 * Timezone e.g. 'America/Los_Angeles'
964 public function getTimeZoneString() {
966 if (variable_get('configurable_timezones', 1) && $user->uid
&& strlen($user->timezone
)) {
967 $timezone = $user->timezone
;
970 $timezone = variable_get('date_default_timezone', NULL);
973 $timezone = parent
::getTimeZoneString();
980 * Reset any system caches that may be required for proper CiviCRM
983 public function flush() {
984 drupal_flush_all_caches();