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