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