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