CRM-13014 support userLoginFinalize() for UF classes (fix civimobile)
[civicrm-core.git] / CRM / Utils / System / Drupal6.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * Drupal specific stuff goes here
38 */
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;
43 }
44
45 /**
46 * if we are using a theming system, invoke theme, else just print the
47 * content
48 *
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
52 *
53 * @return void prints content on stdout
54 * @access public
55 */
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) {
59 if ($maintenance) {
60 drupal_set_breadcrumb('');
61 drupal_maintenance_theme();
62 }
63
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);
71 }
72 else {
73 $out = $content;
74 }
75
76 print $out;
77 }
78
79 /**
80 * Function to create a user in Drupal.
81 *
82 * @param array $params associated array
83 * @param string $mail email id for cms user
84 *
85 * @return uid if user exists, false otherwise
86 *
87 * @access public
88 */
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',
95 );
96
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'];
101 }
102
103 $config = CRM_Core_Config::singleton();
104
105 // we also need to redirect b
106 $config->inCiviCRM = TRUE;
107
108 $form = drupal_retrieve_form('user_register', $form_state);
109 $form['#post'] = $form_state['values'];
110 drupal_prepare_form('user_register', $form, $form_state);
111
112 // remove the captcha element from the form prior to processing
113 unset($form['captcha']);
114
115 drupal_process_form('user_register', $form, $form_state);
116
117 $config->inCiviCRM = FALSE;
118
119 if (form_get_errors() || !isset($form_state['user'])) {
120 return FALSE;
121 }
122
123 return $form_state['user']->uid;
124
125 }
126
127 /*
128 * Change user name in host CMS
129 *
130 * @param integer $ufID User ID in CMS
131 * @param string $ufName User name
132 */
133 function updateCMSName($ufID, $ufName) {
134 // CRM-5555
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));
140 }
141 }
142 }
143
144 /**
145 * Check if username and email exists in the drupal db
146 *
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'
150 *
151 * @return void
152 */
153 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
154 $config = CRM_Core_Config::singleton();
155
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();
161
162 if ($errors) {
163 if (CRM_Utils_Array::value('name', $errors)) {
164 $errors['cms_name'] = $errors['name'];
165 }
166 if (CRM_Utils_Array::value('mail', $errors)) {
167 $errors[$emailName] = $errors['mail'];
168 }
169 // also unset drupal messages to avoid twice display of errors
170 unset($_SESSION['messages']);
171 }
172
173 // drupal api sucks do the name check manually
174 $nameError = user_validate_name($params['name']);
175 if ($nameError) {
176 $errors['cms_name'] = $nameError;
177 }
178
179 $sql = "
180 SELECT name, mail
181 FROM {$config->userFrameworkUsersTableName}
182 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))";
183
184
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());
188 }
189 $query = $db_cms->query($sql);
190 $row = $query->fetchRow();
191 if (!empty($row)) {
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.',
196 array(1 => $name)
197 );
198 }
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)
203 );
204 }
205 }
206 }
207
208 /*
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
211 *
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
214 *
215 */
216 function getLoginDestination(&$form) {
217 $args = NULL;
218
219 $id = $form->get('id');
220 if ($id) {
221 $args .= "&id=$id";
222 }
223 else {
224 $gid = $form->get('gid');
225 if ($gid) {
226 $args .= "&gid=$gid";
227 }
228 else {
229 // Setup Personal Campaign Page link uses pageId
230 $pageId = $form->get('pageId');
231 if ($pageId) {
232 $component = $form->get('component');
233 $args .= "&pageId=$pageId&component=$component&action=add";
234 }
235 }
236 }
237
238 $destination = NULL;
239 if ($args) {
240 // append destination so user is returned to form they came from after login
241 $destination = CRM_Utils_System::currentPath() . '?reset=1' . $args;
242 }
243 return $destination;
244 }
245
246 /**
247 * sets the title of the page
248 *
249 * @param string $title
250 * @paqram string $pageTitle
251 *
252 * @return void
253 * @access public
254 */
255 function setTitle($title, $pageTitle = NULL) {
256 if (!$pageTitle) {
257 $pageTitle = $title;
258 }
259 if (arg(0) == 'civicrm') {
260 //set drupal title
261 drupal_set_title($pageTitle);
262 }
263 }
264
265 /**
266 * Append an additional breadcrumb tag to the existing breadcrumb
267 *
268 * @param string $title
269 * @param string $url
270 *
271 * @return void
272 * @access public
273 */
274 function appendBreadCrumb($breadCrumbs) {
275 $breadCrumb = drupal_get_breadcrumb();
276
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,
283 FALSE, NULL, $_GET
284 );
285 if ($val) {
286 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
287 }
288 }
289 }
290 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
291 }
292 }
293 drupal_set_breadcrumb($breadCrumb);
294 }
295
296 /**
297 * Reset an additional breadcrumb tag to the existing breadcrumb
298 *
299 * @return void
300 * @access public
301 */
302 function resetBreadCrumb() {
303 $bc = array();
304 drupal_set_breadcrumb($bc);
305 }
306
307 /**
308 * Append a string to the head of the html file
309 *
310 * @param string $head the new string to be appended
311 *
312 * @return void
313 * @access public
314 */
315 function addHTMLHead($head) {
316 drupal_set_html_head($head);
317 }
318
319 /**
320 * Add a script file
321 *
322 * @param $url: string, absolute path to file
323 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
324 *
325 * Note: This function is not to be called directly
326 * @see CRM_Core_Region::render()
327 *
328 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
329 * @access public
330 */
331 public function addScriptUrl($url, $region) {
332 switch ($region) {
333 case 'html-header':
334 case 'page-footer':
335 $scope = substr($region, 5);
336 break;
337 default:
338 return FALSE;
339 }
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);
343 return TRUE;
344 }
345 return FALSE;
346 }
347
348 /**
349 * Add an inline script
350 *
351 * @param $code: string, javascript code
352 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
353 *
354 * Note: This function is not to be called directly
355 * @see CRM_Core_Region::render()
356 *
357 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
358 * @access public
359 */
360 public function addScript($code, $region) {
361 switch ($region) {
362 case 'html-header':
363 case 'page-footer':
364 $scope = substr($region, 5);
365 break;
366 default:
367 return FALSE;
368 }
369 drupal_add_js($code, 'inline', $scope);
370 return TRUE;
371 }
372
373 /**
374 * Add a css file
375 *
376 * @param $url: string, absolute path to file
377 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
378 *
379 * Note: This function is not to be called directly
380 * @see CRM_Core_Region::render()
381 *
382 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
383 * @access public
384 */
385 public function addStyleUrl($url, $region) {
386 if ($region != 'html-header' || !CRM_Utils_System_Drupal::formatResourceUrl($url)) {
387 return FALSE;
388 }
389 drupal_add_css($url);
390 return TRUE;
391 }
392
393 /**
394 * Add an inline style
395 *
396 * @param $code: string, css code
397 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
398 *
399 * Note: This function is not to be called directly
400 * @see CRM_Core_Region::render()
401 *
402 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
403 * @access public
404 */
405 public function addStyle($code, $region) {
406 return FALSE;
407 }
408
409 /**
410 * rewrite various system urls to https
411 *
412 * @param null
413 *
414 * @return void
415 * @access public
416 */
417 function mapConfigToSSL() {
418 global $base_url;
419 $base_url = str_replace('http://', 'https://', $base_url);
420 }
421
422 /**
423 * figure out the post url for the form
424 *
425 * @param mix $action the default action if one is pre-specified
426 *
427 * @return string the url to post the form
428 * @access public
429
430 */
431 function postURL($action) {
432 if (!empty($action)) {
433 return $action;
434 }
435
436 return $this->url($_GET['q']);
437 }
438
439 /**
440 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
441 *
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
446 * RSS feed.
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
450 *
451 * @return string an HTML string containing a link to the given path.
452 * @access public
453 *
454 */
455 function url($path = NULL, $query = NULL, $absolute = FALSE,
456 $fragment = NULL, $htmlize = TRUE,
457 $frontend = FALSE
458 ) {
459 $config = CRM_Core_Config::singleton();
460 $script = 'index.php';
461
462 $path = CRM_Utils_String::stripPathChars($path);
463
464 if (isset($fragment)) {
465 $fragment = '#' . $fragment;
466 }
467
468 if (!isset($config->useFrameworkRelativeBase)) {
469 $base = parse_url($config->userFrameworkBaseURL);
470 $config->useFrameworkRelativeBase = $base['path'];
471 }
472 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
473
474 $separator = $htmlize ? '&amp;' : '&';
475
476 if (!$config->cleanURL) {
477 if (isset($path)) {
478 if (isset($query)) {
479 return $base . $script . '?q=' . $path . $separator . $query . $fragment;
480 }
481 else {
482 return $base . $script . '?q=' . $path . $fragment;
483 }
484 }
485 else {
486 if (isset($query)) {
487 return $base . $script . '?' . $query . $fragment;
488 }
489 else {
490 return $base . $fragment;
491 }
492 }
493 }
494 else {
495 if (isset($path)) {
496 if (isset($query)) {
497 return $base . $path . '?' . $query . $fragment;
498 }
499 else {
500 return $base . $path . $fragment;
501 }
502 }
503 else {
504 if (isset($query)) {
505 return $base . $script . '?' . $query . $fragment;
506 }
507 else {
508 return $base . $fragment;
509 }
510 }
511 }
512 }
513
514 /**
515 * Authenticate the user against the drupal db
516 *
517 * @param string $name the user name
518 * @param string $password the password for the above user name
519 *
520 * @return mixed false if no auth
521 * array(
522 * contactID, ufID, unique string ) if success
523 * @access public
524 */
525 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
526 require_once 'DB.php';
527
528 $config = CRM_Core_Config::singleton();
529
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());
533 }
534
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);
540
541 $user = NULL;
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']);
546 if (!$contactID) {
547 return FALSE;
548 }
549 else{//success
550 if ($loadCMSBootstrap) {
551 $bootStrapParams = array();
552 if ($name && $password) {
553 $bootStrapParams = array(
554 'name' => $name,
555 'pass' => $password,
556 );
557 }
558 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
559 }
560 return array($contactID, $row['uid'], mt_rand());
561 }
562 }
563 return FALSE;
564 }
565
566 /*
567 * Load user into session
568 */
569 function loadUser($username) {
570 global $user;
571 $user = user_load(array('name' => $username));
572 if (empty($user->uid)) {
573 return FALSE;
574 }
575
576 $uid = $user->uid;
577 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
578
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);
583 return TRUE;
584 }
585
586 /**
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.
590 */
591 function userLoginFinalize($edit = array()){
592 user_authenticate_finalize(&$edit);
593 }
594
595 /**
596 * Set a message in the UF to display to a user
597 *
598 * @param string $message the message to set
599 *
600 * @access public
601 */
602 function setMessage($message) {
603 drupal_set_message($message);
604 }
605
606 function permissionDenied() {
607 drupal_access_denied();
608 }
609
610 function logout() {
611 module_load_include('inc', 'user', 'user.pages');
612 return user_logout();
613 }
614
615 function updateCategories() {
616 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
617 // CRM-3600
618 cache_clear_all();
619 menu_rebuild();
620 }
621
622 /**
623 * Get the locale set in the hosting CMS
624 *
625 * @return string with the locale or null for none
626 */
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
630 global $language;
631 switch (TRUE) {
632 case $language->language == 'zh-hans':
633 return 'zh_CN';
634
635 case $language->language == 'zh-hant':
636 return 'zh_TW';
637
638 case preg_match('/^.._..$/', $language->language):
639 return $language->language;
640
641 default:
642 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
643 }
644 }
645
646 function getVersion() {
647 return defined('VERSION') ? VERSION : 'Unknown';
648 }
649
650 /**
651 * load drupal bootstrap
652 *
653 * @param $name string optional username for login
654 * @param $pass string optional password for login
655 */
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));
661
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.';
666 exit();
667 }
668
669 chdir($cmsPath);
670 require_once 'includes/bootstrap.inc';
671 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
672
673 if (!function_exists('module_exists') ||
674 !module_exists('civicrm')
675 ) {
676 echo '<br />Sorry, could not able to load drupal bootstrap.';
677 exit();
678 }
679 // lets also fix the clean url setting
680 // CRM-6948
681 $config->cleanURL = (int) variable_get('clean_url', '0');
682
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
686 // CRM-8655
687 CRM_Utils_Hook::config($config);
688
689 if (!$loadUser) {
690 return TRUE;
691 }
692 //load user, we need to check drupal permissions.
693 if ($name) {
694 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
695 if (empty($user->uid)) {
696 echo '<br />Sorry, unrecognized username or password.';
697 exit();
698 }
699 }
700 elseif ($uid) {
701 $account = user_load(array('uid' => $uid));
702 if (empty($account->uid)) {
703 echo '<br />Sorry, unrecognized user id.';
704 exit();
705 }
706 else {
707 global $user;
708 $user = $account;
709 }
710 }
711 }
712
713 function cmsRootPath($scriptFilename = NULL) {
714 $cmsRoot = $valid = NULL;
715
716 if (!is_null($scriptFilename)) {
717 $path = $scriptFilename;
718 }
719 else {
720 $path = $_SERVER['SCRIPT_FILENAME'];
721 }
722 if (function_exists('drush_get_context')) {
723 // drush anyway takes care of multisite install etc
724 return drush_get_context('DRUSH_DRUPAL_ROOT');
725 }
726 // CRM-7582
727 $pathVars = explode('/',
728 str_replace('//', '/',
729 str_replace('\\', '/', $path)
730 )
731 );
732
733 //lets store first var,
734 //need to get back for windows.
735 $firstVar = array_shift($pathVars);
736
737 //lets remove sript name to reduce one iteration.
738 array_pop($pathVars);
739
740 //CRM-7429 --do check for upper most 'includes' dir,
741 //which would effectually work for multisite installation.
742 do {
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")
748 ) {
749 $valid = TRUE;
750 break;
751 }
752 //remove one directory level.
753 array_pop($pathVars);
754 } while (count($pathVars));
755
756 return ($valid) ? $cmsRoot : NULL;
757 }
758
759 /**
760 * check is user logged in.
761 *
762 * @return boolean true/false.
763 */
764 public function isUserLoggedIn() {
765 $isloggedIn = FALSE;
766 if (function_exists('user_is_logged_in')) {
767 $isloggedIn = user_is_logged_in();
768 }
769
770 return $isloggedIn;
771 }
772
773 /**
774 * Get currently logged in user uf id.
775 *
776 * @return int $userID logged in user uf id.
777 */
778 public function getLoggedInUfID() {
779 $ufID = NULL;
780 if (function_exists('user_is_logged_in') &&
781 user_is_logged_in() &&
782 function_exists('user_uid_optional_to_arg')
783 ) {
784 $ufID = user_uid_optional_to_arg(array());
785 }
786
787 return $ufID;
788 }
789
790 /**
791 * Format the url as per language Negotiation.
792 *
793 * @param string $url
794 *
795 * @return string $url, formatted url.
796 * @static
797 */
798 function languageNegotiationURL($url,
799 $addLanguagePart = TRUE,
800 $removeLanguagePart = FALSE
801 ) {
802 if (empty($url)) {
803 return $url;
804 }
805
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')
810 ) {
811 global $language;
812
813 //get the mode.
814 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE);
815
816 //url prefix / path.
817 if (isset($language->prefix) &&
818 $language->prefix &&
819 in_array($mode, array(
820 LANGUAGE_NEGOTIATION_PATH,
821 LANGUAGE_NEGOTIATION_PATH_DEFAULT,
822 ))
823 ) {
824
825 if ($addLanguagePart) {
826 $url .= $language->prefix . '/';
827 }
828 if ($removeLanguagePart) {
829 $url = str_replace("/{$language->prefix}/", '/', $url);
830 }
831 }
832 if (isset($language->domain) &&
833 $language->domain &&
834 $mode == LANGUAGE_NEGOTIATION_DOMAIN
835 ) {
836
837 if ($addLanguagePart) {
838 $url = CRM_Utils_File::addTrailingSlash($language->domain, '/');
839 }
840 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
841 $url = str_replace('\\', '/', $url);
842 $parseUrl = parse_url($url);
843
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);
852 }
853 }
854 }
855 }
856
857 return $url;
858 }
859
860 /**
861 * Find any users/roles/security-principals with the given permission
862 * and replace it with one or more permissions.
863 *
864 * @param $oldPerm string
865 * @param $newPerms array, strings
866 *
867 * @return void
868 */
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);
878 /*
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) );*/
884 }
885 }
886
887 /**
888 * Get a list of all installed modules, including enabled and disabled ones
889 *
890 * @return array CRM_Core_Module
891 */
892 function getModules() {
893 $result = array();
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);
897 }
898 return $result;
899 }
900
901 /**
902 * Get user login URL for hosting CMS (method declared in each CMS system class)
903 *
904 * @param string $destination - if present, add destination to querystring (works for Drupal only)
905 *
906 * @return string - loginURL for the current CMS
907 * @static
908 */
909 public function getLoginURL($destination = '') {
910 $config = CRM_Core_Config::singleton();
911 $loginURL = $config->userFrameworkBaseURL;
912 $loginURL .= 'user';
913 if (!empty($destination)) {
914 // append destination so user is returned to form they came from after login
915 $loginURL .= '?destination=' . urlencode($destination);
916 }
917 return $loginURL;
918 }
919
920 /**
921 * Wrapper for og_membership creation
922 *
923 * @param integer $ogID Organic Group ID
924 * @param integer $drupalID drupal User ID
925 */
926 function og_membership_create($ogID, $drupalID){
927 og_save_subscription( $ogID, $drupalID, array( 'is_active' => 1 ) );
928 }
929
930 /**
931 * Wrapper for og_membership deletion
932 *
933 * @param integer $ogID Organic Group ID
934 * @param integer $drupalID drupal User ID
935 */
936 function og_membership_delete($ogID, $drupalID) {
937 og_delete_subscription( $ogID, $drupalID );
938 }
939
940 /**
941 * Reset any system caches that may be required for proper CiviCRM
942 * integration.
943 */
944 function flush() {
945 drupal_flush_all_caches();
946 }
947 }
948