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