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