0ef2a08dbdbf70e4110ec450743fe28b4100d6d7
[civicrm-core.git] / CRM / Utils / System / Drupal6.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * Drupal specific stuff goes here
38 */
39 class CRM_Utils_System_Drupal6 extends CRM_Utils_System_DrupalBase {
40
41 /**
42 * If we are using a theming system, invoke theme, else just print the
43 * content
44 *
45 * @param string $content
46 * The content that will be themed.
47 * @param bool $print
48 * Are we displaying to the screen or bypassing theming?.
49 * @param bool $maintenance
50 * For maintenance mode.
51 *
52 * @return void
53 * prints content on stdout
54 */
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) {
58 if ($maintenance) {
59 drupal_set_breadcrumb('');
60 drupal_maintenance_theme();
61 }
62
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);
70 }
71 else {
72 $out = $content;
73 }
74
75 print $out;
76 }
77
78 /**
79 * Create a user in Drupal.
80 *
81 * @param array $params
82 * Associated array.
83 * @param string $mail
84 * Email id for cms user.
85 *
86 * @return uid if user exists, false otherwise
87 *
88 */
89 public 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 return $form_state['user']->uid;
123 }
124
125 /*
126 * Change user name in host CMS
127 *
128 * @param integer $ufID User ID in CMS
129 * @param string $ufName User name
130 */
131 /**
132 * @param int $ufID
133 * @param string $ufName
134 */
135 public function updateCMSName($ufID, $ufName) {
136 // CRM-5555
137 if (function_exists('user_load')) {
138 $user = user_load(array('uid' => $ufID));
139 if ($user->mail != $ufName) {
140 user_save($user, array('mail' => $ufName));
141 $user = user_load(array('uid' => $ufID));
142 }
143 }
144 }
145
146 /**
147 * Check if username and email exists in the drupal db
148 *
149 * @param array $params
150 * Array of name and mail values.
151 * @param array $errors
152 * Array of errors.
153 * @param string $emailName
154 * Field label for the 'email'.
155 *
156 * @return void
157 */
158 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
159 $config = CRM_Core_Config::singleton();
160
161 $dao = new CRM_Core_DAO();
162 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
163 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
164 _user_edit_validate(NULL, $params);
165 $errors = form_get_errors();
166 if ($errors) {
167 if (!empty($errors['name'])) {
168 $errors['cms_name'] = $errors['name'];
169 }
170 if (!empty($errors['mail'])) {
171 $errors[$emailName] = $errors['mail'];
172 }
173 // also unset drupal messages to avoid twice display of errors
174 unset($_SESSION['messages']);
175 }
176
177 // Do the name check manually.
178 $nameError = user_validate_name($params['name']);
179 if ($nameError) {
180 $errors['cms_name'] = $nameError;
181 }
182
183 $sql = "
184 SELECT name, mail
185 FROM {users}
186 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))
187 ";
188
189 $result = db_query($sql);
190 $row = db_fetch_array($result);
191 if (!$row) {
192 return;
193 }
194
195 $user = NULL;
196
197 if (!empty($row)) {
198 $dbName = CRM_Utils_Array::value('name', $row);
199 $dbEmail = CRM_Utils_Array::value('mail', $row);
200 if (strtolower($dbName) == strtolower($name)) {
201 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
202 array(1 => $name)
203 );
204 }
205 if (strtolower($dbEmail) == strtolower($email)) {
206 if (empty($email)) {
207 $errors[$emailName] = ts('You cannot create an email account for a contact with no email',
208 array(1 => $email)
209 );
210 }
211 else {
212 $errors[$emailName] = ts('This email %1 is already registered. Please select another email.',
213 array(1 => $email)
214 );
215 }
216 }
217 }
218 }
219
220 /**
221 * Get the drupal destination string. When this is passed in the
222 * URL the user will be directed to it after filling in the drupal form
223 *
224 * @param CRM_Core_Form $form
225 * Form object representing the 'current' form - to which the user will be returned.
226 * @return string
227 * destination value for URL
228 *
229 */
230 public function getLoginDestination(&$form) {
231 $args = NULL;
232
233 $id = $form->get('id');
234 if ($id) {
235 $args .= "&id=$id";
236 }
237 else {
238 $gid = $form->get('gid');
239 if ($gid) {
240 $args .= "&gid=$gid";
241 }
242 else {
243 // Setup Personal Campaign Page link uses pageId
244 $pageId = $form->get('pageId');
245 if ($pageId) {
246 $component = $form->get('component');
247 $args .= "&pageId=$pageId&component=$component&action=add";
248 }
249 }
250 }
251
252 $destination = NULL;
253 if ($args) {
254 // append destination so user is returned to form they came from after login
255 $destination = CRM_Utils_System::currentPath() . '?reset=1' . $args;
256 }
257 return $destination;
258 }
259
260 /**
261 * Sets the title of the page
262 *
263 * @param string $title
264 * @param null $pageTitle
265 *
266 * @paqram string $pageTitle
267 *
268 * @return void
269 */
270 public function setTitle($title, $pageTitle = NULL) {
271 if (!$pageTitle) {
272 $pageTitle = $title;
273 }
274 if (arg(0) == 'civicrm') {
275 //set drupal title
276 drupal_set_title($pageTitle);
277 }
278 }
279
280 /**
281 * Append an additional breadcrumb tag to the existing breadcrumb
282 *
283 * @param $breadCrumbs
284 *
285 * @internal param string $title
286 * @internal param string $url
287 *
288 * @return void
289 */
290 public function appendBreadCrumb($breadCrumbs) {
291 $breadCrumb = drupal_get_breadcrumb();
292
293 if (is_array($breadCrumbs)) {
294 foreach ($breadCrumbs as $crumbs) {
295 if (stripos($crumbs['url'], 'id%%')) {
296 $args = array('cid', 'mid');
297 foreach ($args as $a) {
298 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
299 FALSE, NULL, $_GET
300 );
301 if ($val) {
302 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
303 }
304 }
305 }
306 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
307 }
308 }
309 drupal_set_breadcrumb($breadCrumb);
310 }
311
312 /**
313 * Reset an additional breadcrumb tag to the existing breadcrumb
314 *
315 * @return void
316 */
317 public function resetBreadCrumb() {
318 $bc = array();
319 drupal_set_breadcrumb($bc);
320 }
321
322 /**
323 * Append a string to the head of the html file
324 *
325 * @param string $head
326 * The new string to be appended.
327 *
328 * @return void
329 */
330 public function addHTMLHead($head) {
331 drupal_set_html_head($head);
332 }
333
334 /**
335 * Add a script file
336 *
337 * @param $url: string, absolute path to file
338 * @param string $region
339 * location within the document: 'html-header', 'page-header', 'page-footer'.
340 *
341 * Note: This function is not to be called directly
342 * @see CRM_Core_Region::render()
343 *
344 * @return bool
345 * TRUE if we support this operation in this CMS, FALSE otherwise
346 */
347 public function addScriptUrl($url, $region) {
348 // CRM-15450 - D6 doesn't order internal/external links correctly so we can't use drupal_add_js
349 return FALSE;
350 }
351
352 /**
353 * Add an inline script
354 *
355 * @param $code: string, javascript code
356 * @param string $region
357 * location within the document: 'html-header', 'page-header', 'page-footer'.
358 *
359 * Note: This function is not to be called directly
360 * @see CRM_Core_Region::render()
361 *
362 * @return bool
363 * TRUE if we support this operation in this CMS, FALSE otherwise
364 */
365 public function addScript($code, $region) {
366 // CRM-15450 - ensure scripts are in correct order
367 return FALSE;
368 }
369
370 /**
371 * Add a css file
372 *
373 * @param $url: string, absolute path to file
374 * @param string $region
375 * location within the document: 'html-header', 'page-header', 'page-footer'.
376 *
377 * Note: This function is not to be called directly
378 * @see CRM_Core_Region::render()
379 *
380 * @return bool
381 * TRUE if we support this operation in this CMS, FALSE otherwise
382 */
383 public function addStyleUrl($url, $region) {
384 if ($region != 'html-header' || !$this->formatResourceUrl($url)) {
385 return FALSE;
386 }
387 drupal_add_css($url);
388 return TRUE;
389 }
390
391 /**
392 * Add an inline style
393 *
394 * @param $code: string, css code
395 * @param string $region
396 * location within the document: 'html-header', 'page-header', 'page-footer'.
397 *
398 * Note: This function is not to be called directly
399 * @see CRM_Core_Region::render()
400 *
401 * @return bool
402 * TRUE if we support this operation in this CMS, FALSE otherwise
403 */
404 public function addStyle($code, $region) {
405 return FALSE;
406 }
407
408 /**
409 * Rewrite various system urls to https
410 *
411 * @param null
412 *
413 * @return void
414 */
415 public function mapConfigToSSL() {
416 global $base_url;
417 $base_url = str_replace('http://', 'https://', $base_url);
418 }
419
420 /**
421 * Figure out the post url for the form
422 *
423 * @param mix $action
424 * The default action if one is pre-specified.
425 *
426 * @return string
427 * the url to post the form
428 */
429 public function postURL($action) {
430 if (!empty($action)) {
431 return $action;
432 }
433
434 return $this->url($_GET['q']);
435 }
436
437 /**
438 * Authenticate the user against the drupal db
439 *
440 * @param string $name
441 * The user name.
442 * @param string $password
443 * The password for the above user name.
444 * @param bool $loadCMSBootstrap
445 * Load cms bootstrap?.
446 * @param NULL|string $realPath filename of script
447 *
448 * @return mixed false if no auth
449 * array(
450 * contactID, ufID, unique string ) if success
451 */
452 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
453 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
454 // if ever now.
455 // probably if bootstrap is loaded this call
456 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
457 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
458 // safe in the unknown situation where authenticate might be called & it is important that
459 // false is returned
460 require_once 'DB.php';
461
462 $config = CRM_Core_Config::singleton();
463
464 $dbDrupal = DB::connect($config->userFrameworkDSN);
465 if (DB::isError($dbDrupal)) {
466 CRM_Core_Error::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
467 }
468
469 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
470 $dbpassword = md5($password);
471 $name = $dbDrupal->escapeSimple($strtolower($name));
472 $sql = 'SELECT u.* FROM ' . $config->userFrameworkUsersTableName . " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
473 $query = $dbDrupal->query($sql);
474
475 $user = NULL;
476 // need to change this to make sure we matched only one row
477 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC)) {
478 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
479 $contactID = CRM_Core_BAO_UFMatch::getContactId($row['uid']);
480 if (!$contactID) {
481 return FALSE;
482 }
483 else { //success
484 if ($loadCMSBootstrap) {
485 $bootStrapParams = array();
486 if ($name && $password) {
487 $bootStrapParams = array(
488 'name' => $name,
489 'pass' => $password,
490 );
491 }
492 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
493 }
494 return array($contactID, $row['uid'], mt_rand());
495 }
496 }
497 return FALSE;
498 }
499
500 /**
501 * Load user into session
502 */
503 public function loadUser($username) {
504 global $user;
505 $user = user_load(array('name' => $username));
506 if (empty($user->uid)) {
507 return FALSE;
508 }
509
510 $uid = $user->uid;
511 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
512
513 // lets store contact id and user id in session
514 $session = CRM_Core_Session::singleton();
515 $session->set('ufID', $uid);
516 $session->set('userID', $contact_id);
517 return TRUE;
518 }
519
520 /**
521 * Perform any post login activities required by the UF -
522 * e.g. for drupal : records a watchdog message about the new session,
523 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
524 *
525 * @param array params
526 *
527 * FIXME: Document values accepted/required by $params
528 */
529 public function userLoginFinalize($params = array()) {
530 user_authenticate_finalize($params);
531 }
532
533 /**
534 * Determine the native ID of the CMS user
535 *
536 * @param string $username
537 * @return int|NULL
538 */
539 public function getUfId($username) {
540 $user = user_load(array('name' => $username));
541 if (empty($user->uid)) {
542 return NULL;
543 }
544 return $user->uid;
545 }
546
547 /**
548 * Set a message in the UF to display to a user
549 *
550 * @param string $message
551 * The message to set.
552 *
553 */
554 public function setMessage($message) {
555 drupal_set_message($message);
556 }
557
558 /**
559 * @return mixed
560 */
561 public function logout() {
562 module_load_include('inc', 'user', 'user.pages');
563 return user_logout();
564 }
565
566 public function updateCategories() {
567 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
568 // CRM-3600
569 cache_clear_all();
570 menu_rebuild();
571 }
572
573 /**
574 * Get the locale set in the hosting CMS
575 *
576 * @return string
577 * with the locale or null for none
578 */
579 public function getUFLocale() {
580 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
581 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
582 // sometimes for CLI based on order called, this might not be set and/or empty
583 global $language;
584
585 if (empty($language)) {
586 return NULL;
587 }
588
589 if ($language->language == 'zh-hans') {
590 return 'zh_CN';
591 }
592
593 if ($language->language == 'zh-hant') {
594 return 'zh_TW';
595 }
596
597 if (preg_match('/^.._..$/', $language->language)) {
598 return $language->language;
599 }
600
601 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
602 }
603
604 /**
605 * @return string
606 */
607 public function getVersion() {
608 return defined('VERSION') ? VERSION : 'Unknown';
609 }
610
611 /**
612 * Load drupal bootstrap
613 *
614 * @param array $params
615 * Either uid, or name & pass.
616 * @param bool $loadUser
617 * Boolean Require CMS user load.
618 * @param bool $throwError
619 * If true, print error on failure and exit.
620 * @param bool|string $realPath path to script
621 *
622 * @return bool
623 */
624 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
625 //take the cms root path.
626 $cmsPath = $this->cmsRootPath($realPath);
627
628 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
629 if ($throwError) {
630 echo '<br />Sorry, could not locate bootstrap.inc\n';
631 exit();
632 }
633 return FALSE;
634 }
635 // load drupal bootstrap
636 chdir($cmsPath);
637 define('DRUPAL_ROOT', $cmsPath);
638
639 // For drupal multi-site CRM-11313
640 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
641 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
642 if (!empty($matches[1])) {
643 $_SERVER['HTTP_HOST'] = $matches[1];
644 }
645 }
646 require_once 'includes/bootstrap.inc';
647 // @ to suppress notices eg 'DRUPALFOO already defined'.
648 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
649
650 // explicitly setting error reporting, since we cannot handle drupal related notices
651 error_reporting(1);
652 if (!function_exists('module_exists') || !module_exists('civicrm')) {
653 if ($throwError) {
654 echo '<br />Sorry, could not load drupal bootstrap.';
655 exit();
656 }
657 return FALSE;
658 }
659
660 // seems like we've bootstrapped drupal
661 $config = CRM_Core_Config::singleton();
662
663 // lets also fix the clean url setting
664 // CRM-6948
665 $config->cleanURL = (int) variable_get('clean_url', '0');
666
667 // we need to call the config hook again, since we now know
668 // all the modules that are listening on it, does not apply
669 // to J! and WP as yet
670 // CRM-8655
671 CRM_Utils_Hook::config($config);
672
673 if (!$loadUser) {
674 return TRUE;
675 }
676 global $user;
677 // If $uid is passed in, authentication has been done already.
678 $uid = CRM_Utils_Array::value('uid', $params);
679 if (!$uid) {
680 //load user, we need to check drupal permissions.
681 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
682 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
683
684 if ($name) {
685 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
686 if (!$user->uid) {
687 if ($throwError) {
688 echo '<br />Sorry, unrecognized username or password.';
689 exit();
690 }
691 return FALSE;
692 }
693 else {
694 return TRUE;
695 }
696 }
697 }
698
699 if ($uid) {
700 $account = user_load($uid);
701 if ($account && $account->uid) {
702 $user = $account;
703 return TRUE;
704 }
705 }
706
707 if ($throwError) {
708 echo '<br />Sorry, can not load CMS user account.';
709 exit();
710 }
711
712 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
713 // which means that define(CIVICRM_CLEANURL) was correctly set.
714 // So we correct it
715 $config = CRM_Core_Config::singleton();
716 $config->cleanURL = (int) variable_get('clean_url', '0');
717
718 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
719 CRM_Utils_Hook::config($config);
720
721 return FALSE;
722 }
723
724 /**
725 *
726 */
727 public function cmsRootPath($scriptFilename = NULL) {
728 $cmsRoot = $valid = NULL;
729
730 if (!is_null($scriptFilename)) {
731 $path = $scriptFilename;
732 }
733 else {
734 $path = $_SERVER['SCRIPT_FILENAME'];
735 }
736
737 if (function_exists('drush_get_context')) {
738 // drush anyway takes care of multisite install etc
739 return drush_get_context('DRUSH_DRUPAL_ROOT');
740 }
741 // CRM-7582
742 $pathVars = explode('/',
743 str_replace('//', '/',
744 str_replace('\\', '/', $path)
745 )
746 );
747
748 //lets store first var,
749 //need to get back for windows.
750 $firstVar = array_shift($pathVars);
751
752 //lets remove sript name to reduce one iteration.
753 array_pop($pathVars);
754
755 //CRM-7429 --do check for upper most 'includes' dir,
756 //which would effectually work for multisite installation.
757 do {
758 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
759 $cmsIncludePath = "$cmsRoot/includes";
760 // Stop if we found bootstrap.
761 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
762 $valid = TRUE;
763 break;
764 }
765 //remove one directory level.
766 array_pop($pathVars);
767 } while (count($pathVars));
768
769 return ($valid) ? $cmsRoot : NULL;
770 }
771
772 /**
773 * Check is user logged in.
774 *
775 * @return boolean
776 */
777 public function isUserLoggedIn() {
778 $isloggedIn = FALSE;
779 if (function_exists('user_is_logged_in')) {
780 $isloggedIn = user_is_logged_in();
781 }
782
783 return $isloggedIn;
784 }
785
786 /**
787 * Get currently logged in user uf id.
788 *
789 * @return int
790 * $userID logged in user uf id.
791 */
792 public function getLoggedInUfID() {
793 $ufID = NULL;
794 if (function_exists('user_is_logged_in') &&
795 user_is_logged_in() &&
796 function_exists('user_uid_optional_to_arg')
797 ) {
798 $ufID = user_uid_optional_to_arg(array());
799 }
800
801 return $ufID;
802 }
803
804 /**
805 * Format the url as per language Negotiation.
806 *
807 * @param string $url
808 *
809 * @param bool $addLanguagePart
810 * @param bool $removeLanguagePart
811 *
812 * @return string
813 * , formatted url.
814 * @static
815 */
816 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
817 if (empty($url)) {
818 return $url;
819 }
820
821 //upto d6 only, already we have code in place for d7
822 $config = CRM_Core_Config::singleton();
823 if (function_exists('variable_get') &&
824 module_exists('locale')
825 ) {
826 global $language;
827
828 //get the mode.
829 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE);
830
831 //url prefix / path.
832 if (isset($language->prefix) &&
833 $language->prefix &&
834 in_array($mode, array(
835 LANGUAGE_NEGOTIATION_PATH,
836 LANGUAGE_NEGOTIATION_PATH_DEFAULT,
837 ))
838 ) {
839
840 if ($addLanguagePart) {
841 $url .= $language->prefix . '/';
842 }
843 if ($removeLanguagePart) {
844 $url = str_replace("/{$language->prefix}/", '/', $url);
845 }
846 }
847 if (isset($language->domain) &&
848 $language->domain &&
849 $mode == LANGUAGE_NEGOTIATION_DOMAIN
850 ) {
851
852 if ($addLanguagePart) {
853 $url = CRM_Utils_File::addTrailingSlash($language->domain, '/');
854 }
855 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
856 $url = str_replace('\\', '/', $url);
857 $parseUrl = parse_url($url);
858
859 //kinda hackish but not sure how to do it right
860 //hope http_build_url() will help at some point.
861 if (is_array($parseUrl) && !empty($parseUrl)) {
862 $urlParts = explode('/', $url);
863 $hostKey = array_search($parseUrl['host'], $urlParts);
864 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
865 $urlParts[$hostKey] = $ufUrlParts['host'];
866 $url = implode('/', $urlParts);
867 }
868 }
869 }
870 }
871
872 return $url;
873 }
874
875 /**
876 * Find any users/roles/security-principals with the given permission
877 * and replace it with one or more permissions.
878 *
879 * @param string $oldPerm
880 * @param array $newPerms
881 * Array, strings.
882 *
883 * @return void
884 */
885 public function replacePermission($oldPerm, $newPerms) {
886 $roles = user_roles(FALSE, $oldPerm);
887 foreach ($roles as $rid => $roleName) {
888 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
889 $perms = drupal_map_assoc(explode(', ', $permList));
890 unset($perms[$oldPerm]);
891 $perms = $perms + drupal_map_assoc($newPerms);
892 $permList = implode(', ', $perms);
893 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
894 /*
895 if ( ! empty( $roles ) ) {
896 $rids = implode(',', array_keys($roles));
897 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
898 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
899 $oldPerm, implode(', ', $newPerms) );*/
900 }
901 }
902
903 /**
904 * Get a list of all installed modules, including enabled and disabled ones
905 *
906 * @return array
907 * CRM_Core_Module
908 */
909 public function getModules() {
910 $result = array();
911 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
912 while ($row = db_fetch_object($q)) {
913 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
914 }
915 return $result;
916 }
917
918 /**
919 * Get user login URL for hosting CMS (method declared in each CMS system class)
920 *
921 * @param string $destination
922 * If present, add destination to querystring (works for Drupal only).
923 *
924 * @return string
925 * loginURL for the current CMS
926 * @static
927 */
928 public function getLoginURL($destination = '') {
929 $config = CRM_Core_Config::singleton();
930 $loginURL = $config->userFrameworkBaseURL;
931 $loginURL .= 'user';
932 if (!empty($destination)) {
933 // append destination so user is returned to form they came from after login
934 $loginURL .= '?destination=' . urlencode($destination);
935 }
936 return $loginURL;
937 }
938
939 /**
940 * Wrapper for og_membership creation
941 *
942 * @param int $ogID
943 * Organic Group ID.
944 * @param int $drupalID
945 * Drupal User ID.
946 */
947 public function og_membership_create($ogID, $drupalID) {
948 og_save_subscription($ogID, $drupalID, array('is_active' => 1));
949 }
950
951 /**
952 * Wrapper for og_membership deletion
953 *
954 * @param int $ogID
955 * Organic Group ID.
956 * @param int $drupalID
957 * Drupal User ID.
958 */
959 public function og_membership_delete($ogID, $drupalID) {
960 og_delete_subscription($ogID, $drupalID);
961 }
962
963 /**
964 * Over-ridable function to get timezone as a string eg.
965 * @return string
966 * Timezone e.g. 'America/Los_Angeles'
967 */
968 public function getTimeZoneString() {
969 global $user;
970 if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
971 $timezone = $user->timezone;
972 }
973 else {
974 $timezone = variable_get('date_default_timezone', NULL);
975 }
976 if (!$timezone) {
977 $timezone = parent::getTimeZoneString();
978 }
979 return $timezone;
980 }
981
982
983 /**
984 * Reset any system caches that may be required for proper CiviCRM
985 * integration.
986 */
987 public function flush() {
988 drupal_flush_all_caches();
989 }
990 }