3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
37 * Drupal specific stuff goes here
39 class CRM_Utils_System_Drupal6
extends CRM_Utils_System_Base
{
40 function __construct() {
41 $this->is_drupal
= TRUE;
42 $this->supports_form_extensions
= TRUE;
46 * if we are using a theming system, invoke theme, else just print the
49 * @param string $content the content that will be themed
50 * @param boolean $print are we displaying to the screen or bypassing theming?
51 * @param boolean $maintenance for maintenance mode
53 * @return void prints content on stdout
56 function theme(&$content, $print = FALSE, $maintenance = FALSE) {
57 // TODO: Simplify; this was copied verbatim from CiviCRM 3.4's multi-UF theming function, but that's more complex than necessary
58 if (function_exists('theme') && !$print) {
60 drupal_set_breadcrumb('');
61 drupal_maintenance_theme();
64 // Arg 3 for D6 theme() is "show_blocks". Previously, we passed
65 // through a badly named variable ("$args") which was almost always
66 // TRUE (except on fatal error screen). However, this feature is
67 // non-functional on D6 default themes, was purposefully removed from
68 // D7, has no analog in other our other CMS's, and clutters the code.
69 // Hard-wiring to TRUE should be OK.
70 $out = theme('page', $content, TRUE);
80 * Function to create a user in Drupal.
82 * @param array $params associated array
83 * @param string $mail email id for cms user
85 * @return uid if user exists, false otherwise
89 function createUser(&$params, $mail) {
90 $form_state = array();
91 $form_state['values'] = array(
92 'name' => $params['cms_name'],
93 'mail' => $params[$mail],
94 'op' => 'Create new account',
97 $admin = user_access('administer users');
98 if (!variable_get('user_email_verification', TRUE) ||
$admin) {
99 $form_state['values']['pass']['pass1'] = $params['cms_pass'];
100 $form_state['values']['pass']['pass2'] = $params['cms_pass'];
103 $config = CRM_Core_Config
::singleton();
105 // we also need to redirect b
106 $config->inCiviCRM
= TRUE;
108 $form = drupal_retrieve_form('user_register', $form_state);
109 $form['#post'] = $form_state['values'];
110 drupal_prepare_form('user_register', $form, $form_state);
112 // remove the captcha element from the form prior to processing
113 unset($form['captcha']);
115 drupal_process_form('user_register', $form, $form_state);
117 $config->inCiviCRM
= FALSE;
119 if (form_get_errors() ||
!isset($form_state['user'])) {
123 return $form_state['user']->uid
;
128 * Change user name in host CMS
130 * @param integer $ufID User ID in CMS
131 * @param string $ufName User name
133 function updateCMSName($ufID, $ufName) {
135 if (function_exists('user_load')) {
136 $user = user_load(array('uid' => $ufID));
137 if ($user->mail
!= $ufName) {
138 user_save($user, array('mail' => $ufName));
139 $user = user_load(array('uid' => $ufID));
145 * Check if username and email exists in the drupal db
147 * @params $params array array of name and mail values
148 * @params $errors array array of errors
149 * @params $emailName string field label for the 'email'
153 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();
163 if (CRM_Utils_Array
::value('name', $errors)) {
164 $errors['cms_name'] = $errors['name'];
166 if (CRM_Utils_Array
::value('mail', $errors)) {
167 $errors[$emailName] = $errors['mail'];
169 // also unset drupal messages to avoid twice display of errors
170 unset($_SESSION['messages']);
173 // drupal api sucks do the name check manually
174 $nameError = user_validate_name($params['name']);
176 $errors['cms_name'] = $nameError;
181 FROM {$config->userFrameworkUsersTableName}
182 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))";
185 $db_cms = DB
::connect($config->userFrameworkDSN
);
186 if (DB
::isError($db_cms)) {
187 die("Cannot connect to UF db via $dsn, " . $db_cms->getMessage());
189 $query = $db_cms->query($sql);
190 $row = $query->fetchRow();
192 $dbName = CRM_Utils_Array
::value(0, $row);
193 $dbEmail = CRM_Utils_Array
::value(1, $row);
194 if (strtolower($dbName) == strtolower($name)) {
195 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
199 if (strtolower($dbEmail) == strtolower($email)) {
200 $resetUrl = $config->userFrameworkBaseURL
. 'user/password';
201 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
202 array(1 => $email, 2 => $resetUrl)
209 * Function to get the drupal destination string. When this is passed in the
210 * URL the user will be directed to it after filling in the drupal form
212 * @param object $form Form object representing the 'current' form - to which the user will be returned
213 * @return string $destination destination value for URL
216 function getLoginDestination(&$form) {
219 $id = $form->get('id');
224 $gid = $form->get('gid');
226 $args .= "&gid=$gid";
229 // Setup Personal Campaign Page link uses pageId
230 $pageId = $form->get('pageId');
232 $component = $form->get('component');
233 $args .= "&pageId=$pageId&component=$component&action=add";
240 // append destination so user is returned to form they came from after login
241 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
247 * sets the title of the page
249 * @param string $title
250 * @paqram string $pageTitle
255 function setTitle($title, $pageTitle = NULL) {
259 if (arg(0) == 'civicrm') {
261 drupal_set_title($pageTitle);
266 * Append an additional breadcrumb tag to the existing breadcrumb
268 * @param string $title
274 function appendBreadCrumb($breadCrumbs) {
275 $breadCrumb = drupal_get_breadcrumb();
277 if (is_array($breadCrumbs)) {
278 foreach ($breadCrumbs as $crumbs) {
279 if (stripos($crumbs['url'], 'id%%')) {
280 $args = array('cid', 'mid');
281 foreach ($args as $a) {
282 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
286 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
290 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
293 drupal_set_breadcrumb($breadCrumb);
297 * Reset an additional breadcrumb tag to the existing breadcrumb
302 function resetBreadCrumb() {
304 drupal_set_breadcrumb($bc);
308 * Append a string to the head of the html file
310 * @param string $head the new string to be appended
315 function addHTMLHead($head) {
316 drupal_set_html_head($head);
322 * @param $url: string, absolute path to file
323 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
325 * Note: This function is not to be called directly
326 * @see CRM_Core_Region::render()
328 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
331 public function addScriptUrl($url, $region) {
335 $scope = substr($region, 5);
340 // If the path is within the drupal directory we can add in the normal way
341 if (CRM_Utils_System_Drupal
::formatResourceUrl($url)) {
342 drupal_add_js($url, 'module', $scope);
349 * Add an inline script
351 * @param $code: string, javascript code
352 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
354 * Note: This function is not to be called directly
355 * @see CRM_Core_Region::render()
357 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
360 public function addScript($code, $region) {
364 $scope = substr($region, 5);
369 drupal_add_js($code, 'inline', $scope);
376 * @param $url: string, absolute path to file
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
385 public function addStyleUrl($url, $region) {
386 if ($region != 'html-header' ||
!CRM_Utils_System_Drupal
::formatResourceUrl($url)) {
389 drupal_add_css($url);
394 * Add an inline style
396 * @param $code: string, css code
397 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
399 * Note: This function is not to be called directly
400 * @see CRM_Core_Region::render()
402 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
405 public function addStyle($code, $region) {
410 * rewrite various system urls to https
417 function mapConfigToSSL() {
419 $base_url = str_replace('http://', 'https://', $base_url);
423 * figure out the post url for the form
425 * @param mix $action the default action if one is pre-specified
427 * @return string the url to post the form
431 function postURL($action) {
432 if (!empty($action)) {
436 return $this->url($_GET['q']);
440 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
442 * @param $path string The path being linked to, such as "civicrm/add"
443 * @param $query string A query string to append to the link.
444 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
445 * Useful for links that will be displayed outside the site, such as in an
447 * @param $fragment string A fragment identifier (named anchor) to append to the link.
448 * @param $htmlize boolean whether to convert to html eqivalant
449 * @param $frontend boolean a gross joomla hack
451 * @return string an HTML string containing a link to the given path.
455 function url($path = NULL, $query = NULL, $absolute = FALSE,
456 $fragment = NULL, $htmlize = TRUE,
459 $config = CRM_Core_Config
::singleton();
460 $script = 'index.php';
462 $path = CRM_Utils_String
::stripPathChars($path);
464 if (isset($fragment)) {
465 $fragment = '#' . $fragment;
468 if (!isset($config->useFrameworkRelativeBase
)) {
469 $base = parse_url($config->userFrameworkBaseURL
);
470 $config->useFrameworkRelativeBase
= $base['path'];
472 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
474 $separator = $htmlize ?
'&' : '&';
476 if (!$config->cleanURL
) {
479 return $base . $script . '?q=' . $path . $separator . $query . $fragment;
482 return $base . $script . '?q=' . $path . $fragment;
487 return $base . $script . '?' . $query . $fragment;
490 return $base . $fragment;
497 return $base . $path . '?' . $query . $fragment;
500 return $base . $path . $fragment;
505 return $base . $script . '?' . $query . $fragment;
508 return $base . $fragment;
515 * Authenticate the user against the drupal db
517 * @param string $name the user name
518 * @param string $password the password for the above user name
520 * @return mixed false if no auth
522 * contactID, ufID, unique string ) if success
525 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
526 require_once 'DB.php';
528 $config = CRM_Core_Config
::singleton();
530 $dbDrupal = DB
::connect($config->userFrameworkDSN
);
531 if (DB
::isError($dbDrupal)) {
532 CRM_Core_Error
::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
535 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
536 $dbpassword = md5($password);
537 $name = $dbDrupal->escapeSimple($strtolower($name));
538 $sql = 'SELECT u.* FROM ' . $config->userFrameworkUsersTableName
. " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
539 $query = $dbDrupal->query($sql);
542 // need to change this to make sure we matched only one row
543 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC
)) {
544 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
545 $contactID = CRM_Core_BAO_UFMatch
::getContactId($row['uid']);
550 if ($loadCMSBootstrap) {
551 $bootStrapParams = array();
552 if ($name && $password) {
553 $bootStrapParams = array(
558 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
560 return array($contactID, $row['uid'], mt_rand());
567 * Load user into session
569 function loadUser($username) {
571 $user = user_load(array('name' => $username));
572 if (empty($user->uid
)) {
577 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
579 // lets store contact id and user id in session
580 $session = CRM_Core_Session
::singleton();
581 $session->set('ufID', $uid);
582 $session->set('userID', $contact_id);
587 * Perform an post login activities required by the UF -
588 * e.g. for drupal : records a watchdog message about the new session, saves the login timestamp, calls hook_user op 'login' and generates a new session.
589 * @param array $edit: The array of form values submitted by the user.
591 function userLoginFinalize($edit = array()){
592 user_authenticate_finalize(&$edit);
596 * Set a message in the UF to display to a user
598 * @param string $message the message to set
602 function setMessage($message) {
603 drupal_set_message($message);
606 function permissionDenied() {
607 drupal_access_denied();
611 module_load_include('inc', 'user', 'user.pages');
612 return user_logout();
615 function updateCategories() {
616 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
623 * Get the locale set in the hosting CMS
625 * @return string with the locale or null for none
627 function getUFLocale() {
628 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
629 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
632 case $language->language
== 'zh-hans':
635 case $language->language
== 'zh-hant':
638 case preg_match('/^.._..$/', $language->language
):
639 return $language->language
;
642 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->language
, 0, 2));
646 function getVersion() {
647 return defined('VERSION') ? VERSION
: 'Unknown';
651 * load drupal bootstrap
653 * @param $name string optional username for login
654 * @param $pass string optional password for login
656 function loadBootStrap($params = array(
657 ), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
658 $uid = CRM_Utils_Array
::value('uid', $params);
659 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
660 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
662 //take the cms root path.
663 $cmsPath = $this->cmsRootPath($realPath);
664 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
665 echo '<br />Sorry, unable to locate bootstrap.inc.';
670 require_once 'includes/bootstrap.inc';
671 @drupal_bootstrap
(DRUPAL_BOOTSTRAP_FULL
);
673 if (!function_exists('module_exists') ||
674 !module_exists('civicrm')
676 echo '<br />Sorry, could not able to load drupal bootstrap.';
679 // lets also fix the clean url setting
681 $config->cleanURL
= (int) variable_get('clean_url', '0');
683 // we need to call the config hook again, since we now know
684 // all the modules that are listening on it, does not apply
685 // to J! and WP as yet
687 CRM_Utils_Hook
::config($config);
692 //load user, we need to check drupal permissions.
694 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
695 if (empty($user->uid
)) {
696 echo '<br />Sorry, unrecognized username or password.';
701 $account = user_load(array('uid' => $uid));
702 if (empty($account->uid
)) {
703 echo '<br />Sorry, unrecognized user id.';
713 function cmsRootPath($scriptFilename = NULL) {
714 $cmsRoot = $valid = NULL;
716 if (!is_null($scriptFilename)) {
717 $path = $scriptFilename;
720 $path = $_SERVER['SCRIPT_FILENAME'];
722 if (function_exists('drush_get_context')) {
723 // drush anyway takes care of multisite install etc
724 return drush_get_context('DRUSH_DRUPAL_ROOT');
727 $pathVars = explode('/',
728 str_replace('//', '/',
729 str_replace('\\', '/', $path)
733 //lets store first var,
734 //need to get back for windows.
735 $firstVar = array_shift($pathVars);
737 //lets remove sript name to reduce one iteration.
738 array_pop($pathVars);
740 //CRM-7429 --do check for upper most 'includes' dir,
741 //which would effectually work for multisite installation.
743 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
744 $cmsIncludePath = "$cmsRoot/includes";
745 //stop as we found bootstrap.
746 if (@opendir
($cmsIncludePath) &&
747 file_exists("$cmsIncludePath/bootstrap.inc")
752 //remove one directory level.
753 array_pop($pathVars);
754 } while (count($pathVars));
756 return ($valid) ?
$cmsRoot : NULL;
760 * check is user logged in.
762 * @return boolean true/false.
764 public function isUserLoggedIn() {
766 if (function_exists('user_is_logged_in')) {
767 $isloggedIn = user_is_logged_in();
774 * Get currently logged in user uf id.
776 * @return int $userID logged in user uf id.
778 public function getLoggedInUfID() {
780 if (function_exists('user_is_logged_in') &&
781 user_is_logged_in() &&
782 function_exists('user_uid_optional_to_arg')
784 $ufID = user_uid_optional_to_arg(array());
791 * Format the url as per language Negotiation.
795 * @return string $url, formatted url.
798 function languageNegotiationURL($url,
799 $addLanguagePart = TRUE,
800 $removeLanguagePart = FALSE
806 //upto d6 only, already we have code in place for d7
807 $config = CRM_Core_Config
::singleton();
808 if (function_exists('variable_get') &&
809 module_exists('locale')
814 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE
);
817 if (isset($language->prefix
) &&
819 in_array($mode, array(
820 LANGUAGE_NEGOTIATION_PATH
,
821 LANGUAGE_NEGOTIATION_PATH_DEFAULT
,
825 if ($addLanguagePart) {
826 $url .= $language->prefix
. '/';
828 if ($removeLanguagePart) {
829 $url = str_replace("/{$language->prefix}/", '/', $url);
832 if (isset($language->domain
) &&
834 $mode == LANGUAGE_NEGOTIATION_DOMAIN
837 if ($addLanguagePart) {
838 $url = CRM_Utils_File
::addTrailingSlash($language->domain
, '/');
840 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
841 $url = str_replace('\\', '/', $url);
842 $parseUrl = parse_url($url);
844 //kinda hackish but not sure how to do it right
845 //hope http_build_url() will help at some point.
846 if (is_array($parseUrl) && !empty($parseUrl)) {
847 $urlParts = explode('/', $url);
848 $hostKey = array_search($parseUrl['host'], $urlParts);
849 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
850 $urlParts[$hostKey] = $ufUrlParts['host'];
851 $url = implode('/', $urlParts);
861 * Find any users/roles/security-principals with the given permission
862 * and replace it with one or more permissions.
864 * @param $oldPerm string
865 * @param $newPerms array, strings
869 function replacePermission($oldPerm, $newPerms) {
870 $roles = user_roles(FALSE, $oldPerm);
871 foreach ($roles as $rid => $roleName) {
872 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
873 $perms = drupal_map_assoc(explode(', ', $permList));
874 unset($perms[$oldPerm]);
875 $perms = $perms +
drupal_map_assoc($newPerms);
876 $permList = implode(', ', $perms);
877 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
879 if ( ! empty( $roles ) ) {
880 $rids = implode(',', array_keys($roles));
881 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
882 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
883 $oldPerm, implode(', ', $newPerms) );*/
888 * Get a list of all installed modules, including enabled and disabled ones
890 * @return array CRM_Core_Module
892 function getModules() {
894 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
895 while ($row = db_fetch_object($q)) {
896 $result[] = new CRM_Core_Module('drupal.' . $row->name
, ($row->status
== 1) ?
TRUE : FALSE);
902 * Get user login URL for hosting CMS (method declared in each CMS system class)
904 * @param string $destination - if present, add destination to querystring (works for Drupal only)
906 * @return string - loginURL for the current CMS
909 public function getLoginURL($destination = '') {
910 $config = CRM_Core_Config
::singleton();
911 $loginURL = $config->userFrameworkBaseURL
;
913 if (!empty($destination)) {
914 // append destination so user is returned to form they came from after login
915 $loginURL .= '?destination=' . urlencode($destination);
921 * Wrapper for og_membership creation
923 * @param integer $ogID Organic Group ID
924 * @param integer $drupalID drupal User ID
926 function og_membership_create($ogID, $drupalID){
927 og_save_subscription( $ogID, $drupalID, array( 'is_active' => 1 ) );
931 * Wrapper for og_membership deletion
933 * @param integer $ogID Organic Group ID
934 * @param integer $drupalID drupal User ID
936 function og_membership_delete($ogID, $drupalID) {
937 og_delete_subscription( $ogID, $drupalID );
941 * Reset any system caches that may be required for proper CiviCRM
945 drupal_flush_all_caches();