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