Merge pull request #1 from manishmore/master
[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 // CRM-15450 - D6 doesn't order internal/external links correctly so we can't use drupal_add_js
346 return FALSE;
347 }
348
349 /**
350 * Add an inline script
351 *
352 * @param $code: string, javascript code
353 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
354 *
355 * Note: This function is not to be called directly
356 * @see CRM_Core_Region::render()
357 *
358 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
359 * @access public
360 */
361 public function addScript($code, $region) {
362 // CRM-15450 - ensure scripts are in correct order
363 return FALSE;
364 }
365
366 /**
367 * Add a css file
368 *
369 * @param $url: string, absolute path to file
370 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
371 *
372 * Note: This function is not to be called directly
373 * @see CRM_Core_Region::render()
374 *
375 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
376 * @access public
377 */
378 public function addStyleUrl($url, $region) {
379 if ($region != 'html-header' || !$this->formatResourceUrl($url)) {
380 return FALSE;
381 }
382 drupal_add_css($url);
383 return TRUE;
384 }
385
386 /**
387 * Add an inline style
388 *
389 * @param $code: string, css code
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 addStyle($code, $region) {
399 return FALSE;
400 }
401
402 /**
403 * rewrite various system urls to https
404 *
405 * @param null
406 *
407 * @return void
408 * @access public
409 */
410 function mapConfigToSSL() {
411 global $base_url;
412 $base_url = str_replace('http://', 'https://', $base_url);
413 }
414
415 /**
416 * figure out the post url for the form
417 *
418 * @param mix $action the default action if one is pre-specified
419 *
420 * @return string the url to post the form
421 * @access public
422 */
423 function postURL($action) {
424 if (!empty($action)) {
425 return $action;
426 }
427
428 return $this->url($_GET['q']);
429 }
430
431 /**
432 * Authenticate the user against the drupal db
433 *
434 * @param string $name the user name
435 * @param string $password the password for the above user name
436 * @param boolean $loadCMSBootstrap load cms bootstrap?
437 * @param NULL|string $realPath filename of script
438 *
439 * @return mixed false if no auth
440 * array(
441 * contactID, ufID, unique string ) if success
442 * @access public
443 */
444 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
445 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
446 // if ever now.
447 // probably if bootstrap is loaded this call
448 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
449 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
450 // safe in the unknown situation where authenticate might be called & it is important that
451 // false is returned
452 require_once 'DB.php';
453
454 $config = CRM_Core_Config::singleton();
455
456 $dbDrupal = DB::connect($config->userFrameworkDSN);
457 if (DB::isError($dbDrupal)) {
458 CRM_Core_Error::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
459 }
460
461 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
462 $dbpassword = md5($password);
463 $name = $dbDrupal->escapeSimple($strtolower($name));
464 $sql = 'SELECT u.* FROM ' . $config->userFrameworkUsersTableName . " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
465 $query = $dbDrupal->query($sql);
466
467 $user = NULL;
468 // need to change this to make sure we matched only one row
469 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC)) {
470 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
471 $contactID = CRM_Core_BAO_UFMatch::getContactId($row['uid']);
472 if (!$contactID) {
473 return FALSE;
474 }
475 else{//success
476 if ($loadCMSBootstrap) {
477 $bootStrapParams = array();
478 if ($name && $password) {
479 $bootStrapParams = array(
480 'name' => $name,
481 'pass' => $password,
482 );
483 }
484 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
485 }
486 return array($contactID, $row['uid'], mt_rand());
487 }
488 }
489 return FALSE;
490 }
491
492 /**
493 * Load user into session
494 */
495 function loadUser($username) {
496 global $user;
497 $user = user_load(array('name' => $username));
498 if (empty($user->uid)) {
499 return FALSE;
500 }
501
502 $uid = $user->uid;
503 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
504
505 // lets store contact id and user id in session
506 $session = CRM_Core_Session::singleton();
507 $session->set('ufID', $uid);
508 $session->set('userID', $contact_id);
509 return TRUE;
510 }
511
512 /**
513 * Perform any post login activities required by the UF -
514 * e.g. for drupal : records a watchdog message about the new session,
515 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
516 *
517 * @param array params
518 *
519 * FIXME: Document values accepted/required by $params
520 */
521 function userLoginFinalize($params = array()) {
522 user_authenticate_finalize($params);
523 }
524
525 /**
526 * Determine the native ID of the CMS user
527 *
528 * @param $username
529 * @return int|NULL
530 */
531 function getUfId($username) {
532 $user = user_load(array('name' => $username));
533 if (empty($user->uid)) {
534 return NULL;
535 }
536 return $user->uid;
537 }
538
539 /**
540 * Set a message in the UF to display to a user
541 *
542 * @param string $message the message to set
543 *
544 * @access public
545 */
546 function setMessage($message) {
547 drupal_set_message($message);
548 }
549
550 /**
551 * @return mixed
552 */
553 function logout() {
554 module_load_include('inc', 'user', 'user.pages');
555 return user_logout();
556 }
557
558 function updateCategories() {
559 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
560 // CRM-3600
561 cache_clear_all();
562 menu_rebuild();
563 }
564
565 /**
566 * Get the locale set in the hosting CMS
567 *
568 * @return string with the locale or null for none
569 */
570 function getUFLocale() {
571 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
572 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
573 // sometimes for CLI based on order called, this might not be set and/or empty
574 global $language;
575
576 if (empty($language)) {
577 return NULL;
578 }
579
580 if ($language->language == 'zh-hans') {
581 return 'zh_CN';
582 }
583
584 if ($language->language == 'zh-hant') {
585 return 'zh_TW';
586 }
587
588 if (preg_match('/^.._..$/', $language->language)) {
589 return $language->language;
590 }
591
592 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
593 }
594
595 /**
596 * @return string
597 */
598 function getVersion() {
599 return defined('VERSION') ? VERSION : 'Unknown';
600 }
601
602 /**
603 * load drupal bootstrap
604 *
605 * @param array $params Either uid, or name & pass.
606 * @param boolean $loadUser boolean Require CMS user load.
607 * @param boolean $throwError If true, print error on failure and exit.
608 * @param boolean|string $realPath path to script
609 *
610 * @return bool
611 */
612 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
613 //take the cms root path.
614 $cmsPath = $this->cmsRootPath($realPath);
615
616 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
617 if ($throwError) {
618 echo '<br />Sorry, could not locate bootstrap.inc\n';
619 exit();
620 }
621 return FALSE;
622 }
623 // load drupal bootstrap
624 chdir($cmsPath);
625 define('DRUPAL_ROOT', $cmsPath);
626
627 // For drupal multi-site CRM-11313
628 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
629 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
630 if (!empty($matches[1])) {
631 $_SERVER['HTTP_HOST'] = $matches[1];
632 }
633 }
634 require_once 'includes/bootstrap.inc';
635 // @ to suppress notices eg 'DRUPALFOO already defined'.
636 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
637
638 // explicitly setting error reporting, since we cannot handle drupal related notices
639 error_reporting(1);
640 if (!function_exists('module_exists') || !module_exists('civicrm')) {
641 if ($throwError) {
642 echo '<br />Sorry, could not load drupal bootstrap.';
643 exit();
644 }
645 return FALSE;
646 }
647
648 // seems like we've bootstrapped drupal
649 $config = CRM_Core_Config::singleton();
650
651 // lets also fix the clean url setting
652 // CRM-6948
653 $config->cleanURL = (int) variable_get('clean_url', '0');
654
655 // we need to call the config hook again, since we now know
656 // all the modules that are listening on it, does not apply
657 // to J! and WP as yet
658 // CRM-8655
659 CRM_Utils_Hook::config($config);
660
661 if (!$loadUser) {
662 return TRUE;
663 }
664 global $user;
665 // If $uid is passed in, authentication has been done already.
666 $uid = CRM_Utils_Array::value('uid', $params);
667 if (!$uid) {
668 //load user, we need to check drupal permissions.
669 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
670 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
671
672 if ($name) {
673 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
674 if (!$user->uid) {
675 if ($throwError) {
676 echo '<br />Sorry, unrecognized username or password.';
677 exit();
678 }
679 return FALSE;
680 }
681 else {
682 return TRUE;
683 }
684 }
685 }
686
687 if ($uid) {
688 $account = user_load($uid);
689 if ($account && $account->uid) {
690 $user = $account;
691 return TRUE;
692 }
693 }
694
695 if ($throwError) {
696 echo '<br />Sorry, can not load CMS user account.';
697 exit();
698 }
699
700 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
701 // which means that define(CIVICRM_CLEANURL) was correctly set.
702 // So we correct it
703 $config = CRM_Core_Config::singleton();
704 $config->cleanURL = (int)variable_get('clean_url', '0');
705
706 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
707 CRM_Utils_Hook::config($config);
708
709 return FALSE;
710 }
711
712 /**
713 *
714 */
715 function cmsRootPath($scriptFilename = NULL) {
716 $cmsRoot = $valid = NULL;
717
718 if (!is_null($scriptFilename)) {
719 $path = $scriptFilename;
720 }
721 else {
722 $path = $_SERVER['SCRIPT_FILENAME'];
723 }
724
725 if (function_exists('drush_get_context')) {
726 // drush anyway takes care of multisite install etc
727 return drush_get_context('DRUSH_DRUPAL_ROOT');
728 }
729 // CRM-7582
730 $pathVars = explode('/',
731 str_replace('//', '/',
732 str_replace('\\', '/', $path)
733 )
734 );
735
736 //lets store first var,
737 //need to get back for windows.
738 $firstVar = array_shift($pathVars);
739
740 //lets remove sript name to reduce one iteration.
741 array_pop($pathVars);
742
743 //CRM-7429 --do check for upper most 'includes' dir,
744 //which would effectually work for multisite installation.
745 do {
746 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
747 $cmsIncludePath = "$cmsRoot/includes";
748 //stop as we found bootstrap.
749 if (@opendir($cmsIncludePath) &&
750 file_exists("$cmsIncludePath/bootstrap.inc")
751 ) {
752 $valid = TRUE;
753 break;
754 }
755 //remove one directory level.
756 array_pop($pathVars);
757 } while (count($pathVars));
758
759 return ($valid) ? $cmsRoot : NULL;
760 }
761
762 /**
763 * check is user logged in.
764 *
765 * @return boolean true/false.
766 */
767 public function isUserLoggedIn() {
768 $isloggedIn = FALSE;
769 if (function_exists('user_is_logged_in')) {
770 $isloggedIn = user_is_logged_in();
771 }
772
773 return $isloggedIn;
774 }
775
776 /**
777 * Get currently logged in user uf id.
778 *
779 * @return int $userID logged in user uf id.
780 */
781 public function getLoggedInUfID() {
782 $ufID = NULL;
783 if (function_exists('user_is_logged_in') &&
784 user_is_logged_in() &&
785 function_exists('user_uid_optional_to_arg')
786 ) {
787 $ufID = user_uid_optional_to_arg(array());
788 }
789
790 return $ufID;
791 }
792
793 /**
794 * Format the url as per language Negotiation.
795 *
796 * @param string $url
797 *
798 * @param bool $addLanguagePart
799 * @param bool $removeLanguagePart
800 *
801 * @return string $url, formatted url.
802 * @static
803 */
804 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
805 if (empty($url)) {
806 return $url;
807 }
808
809 //upto d6 only, already we have code in place for d7
810 $config = CRM_Core_Config::singleton();
811 if (function_exists('variable_get') &&
812 module_exists('locale')
813 ) {
814 global $language;
815
816 //get the mode.
817 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE);
818
819 //url prefix / path.
820 if (isset($language->prefix) &&
821 $language->prefix &&
822 in_array($mode, array(
823 LANGUAGE_NEGOTIATION_PATH,
824 LANGUAGE_NEGOTIATION_PATH_DEFAULT,
825 ))
826 ) {
827
828 if ($addLanguagePart) {
829 $url .= $language->prefix . '/';
830 }
831 if ($removeLanguagePart) {
832 $url = str_replace("/{$language->prefix}/", '/', $url);
833 }
834 }
835 if (isset($language->domain) &&
836 $language->domain &&
837 $mode == LANGUAGE_NEGOTIATION_DOMAIN
838 ) {
839
840 if ($addLanguagePart) {
841 $url = CRM_Utils_File::addTrailingSlash($language->domain, '/');
842 }
843 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
844 $url = str_replace('\\', '/', $url);
845 $parseUrl = parse_url($url);
846
847 //kinda hackish but not sure how to do it right
848 //hope http_build_url() will help at some point.
849 if (is_array($parseUrl) && !empty($parseUrl)) {
850 $urlParts = explode('/', $url);
851 $hostKey = array_search($parseUrl['host'], $urlParts);
852 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
853 $urlParts[$hostKey] = $ufUrlParts['host'];
854 $url = implode('/', $urlParts);
855 }
856 }
857 }
858 }
859
860 return $url;
861 }
862
863 /**
864 * Find any users/roles/security-principals with the given permission
865 * and replace it with one or more permissions.
866 *
867 * @param $oldPerm string
868 * @param $newPerms array, strings
869 *
870 * @return void
871 */
872 function replacePermission($oldPerm, $newPerms) {
873 $roles = user_roles(FALSE, $oldPerm);
874 foreach ($roles as $rid => $roleName) {
875 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
876 $perms = drupal_map_assoc(explode(', ', $permList));
877 unset($perms[$oldPerm]);
878 $perms = $perms + drupal_map_assoc($newPerms);
879 $permList = implode(', ', $perms);
880 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
881 /*
882 if ( ! empty( $roles ) ) {
883 $rids = implode(',', array_keys($roles));
884 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
885 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
886 $oldPerm, implode(', ', $newPerms) );*/
887 }
888 }
889
890 /**
891 * Get a list of all installed modules, including enabled and disabled ones
892 *
893 * @return array CRM_Core_Module
894 */
895 function getModules() {
896 $result = array();
897 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
898 while ($row = db_fetch_object($q)) {
899 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
900 }
901 return $result;
902 }
903
904 /**
905 * Get user login URL for hosting CMS (method declared in each CMS system class)
906 *
907 * @param string $destination - if present, add destination to querystring (works for Drupal only)
908 *
909 * @return string - loginURL for the current CMS
910 * @static
911 */
912 public function getLoginURL($destination = '') {
913 $config = CRM_Core_Config::singleton();
914 $loginURL = $config->userFrameworkBaseURL;
915 $loginURL .= 'user';
916 if (!empty($destination)) {
917 // append destination so user is returned to form they came from after login
918 $loginURL .= '?destination=' . urlencode($destination);
919 }
920 return $loginURL;
921 }
922
923 /**
924 * Wrapper for og_membership creation
925 *
926 * @param integer $ogID Organic Group ID
927 * @param integer $drupalID drupal User ID
928 */
929 function og_membership_create($ogID, $drupalID){
930 og_save_subscription( $ogID, $drupalID, array( 'is_active' => 1 ) );
931 }
932
933 /**
934 * Wrapper for og_membership deletion
935 *
936 * @param integer $ogID Organic Group ID
937 * @param integer $drupalID drupal User ID
938 */
939 function og_membership_delete($ogID, $drupalID) {
940 og_delete_subscription( $ogID, $drupalID );
941 }
942
943 /**
944 * Over-ridable function to get timezone as a string eg.
945 * @return string Timezone e.g. 'America/Los_Angeles'
946 */
947 function getTimeZoneString() {
948 global $user;
949 if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
950 $timezone = $user->timezone;
951 } else {
952 $timezone = variable_get('date_default_timezone', null);
953 }
954 if (!$timezone) {
955 $timezone = parent::getTimeZoneString();
956 }
957 return $timezone;
958 }
959
960
961 /**
962 * Reset any system caches that may be required for proper CiviCRM
963 * integration.
964 */
965 function flush() {
966 drupal_flush_all_caches();
967 }
968 }