Merge pull request #1964 from dlobo/CRM-13746
[civicrm-core.git] / CRM / Utils / System / Drupal.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
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 */
9977c6f5 39class CRM_Utils_System_Drupal extends CRM_Utils_System_DrupalBase {
6a488035
TO
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) {
a5ecff8d 62 $form_state['input']['pass'] = array('pass1'=>$params['cms_pass'],'pass2'=>$params['cms_pass']);
6a488035
TO
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;
805b0f6e 71 $form_state['complete form'] = FALSE;
6a488035
TO
72 $form_state['method'] = 'post';
73 $form_state['build_info']['args'] = array();
41d551ad 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;
6a488035
TO
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;
805b0f6e 88 $form['#array_parents'] = array();
89 $form['#tree'] = FALSE;
6a488035
TO
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 }
a5ecff8d 97 return $form_state['user']->uid;
6a488035
TO
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'] = self::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'] = self::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 * Check if a resource url is within the drupal directory and format appropriately
411 *
412 * @param url (reference)
413 *
414 * @return bool: TRUE for internal paths, FALSE for external
415 */
416 static function formatResourceUrl(&$url) {
417 $internal = FALSE;
418 $base = CRM_Core_Config::singleton()->resourceBase;
419 global $base_url;
420 // Handle absolute urls
421 if (strpos($url, $base_url) === 0) {
422 $internal = TRUE;
423 $url = trim(str_replace($base_url, '', $url), '/');
424 }
425 // Handle relative urls
426 elseif (strpos($url, $base) === 0) {
427 $internal = TRUE;
428 $url = substr(drupal_get_path('module', 'civicrm'), 0, -6) . trim(substr($url, strlen($base)), '/');
429 }
430 // Strip query string
431 $q = strpos($url, '?');
432 if ($q && $internal) {
433 $url = substr($url, 0, $q);
434 }
435 return $internal;
436 }
437
438 /**
439 * rewrite various system urls to https
440 *
441 * @param null
442 *
443 * @return void
444 * @access public
445 */
446 function mapConfigToSSL() {
447 global $base_url;
448 $base_url = str_replace('http://', 'https://', $base_url);
449 }
450
451 /**
452 * figure out the post url for the form
453 *
454 * @param mix $action the default action if one is pre-specified
455 *
456 * @return string the url to post the form
457 * @access public
458 */
459 function postURL($action) {
460 if (!empty($action)) {
461 return $action;
462 }
463
464 return $this->url($_GET['q']);
465 }
466
467 /**
468 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
469 *
470 * @param $path string The path being linked to, such as "civicrm/add"
471 * @param $query string A query string to append to the link.
472 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
473 * Useful for links that will be displayed outside the site, such as in an
474 * RSS feed.
475 * @param $fragment string A fragment identifier (named anchor) to append to the link.
476 * @param $htmlize boolean whether to convert to html eqivalant
477 * @param $frontend boolean a gross joomla hack
478 *
479 * @return string an HTML string containing a link to the given path.
480 * @access public
481 *
482 */
483 function url($path = NULL, $query = NULL, $absolute = FALSE,
484 $fragment = NULL, $htmlize = TRUE,
485 $frontend = FALSE, $forceBackend = FALSE
486 ) {
487 $config = CRM_Core_Config::singleton();
488 $script = 'index.php';
489
490 $path = CRM_Utils_String::stripPathChars($path);
491
492 if (isset($fragment)) {
493 $fragment = '#' . $fragment;
494 }
495
496 if (!isset($config->useFrameworkRelativeBase)) {
497 $base = parse_url($config->userFrameworkBaseURL);
498 $config->useFrameworkRelativeBase = $base['path'];
499 }
500 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
501
502 $separator = $htmlize ? '&amp;' : '&';
503
504 if (!$config->cleanURL) {
505 if (isset($path)) {
506 if (isset($query)) {
507 return $base . $script . '?q=' . $path . $separator . $query . $fragment;
508 }
509 else {
510 return $base . $script . '?q=' . $path . $fragment;
511 }
512 }
513 else {
514 if (isset($query)) {
515 return $base . $script . '?' . $query . $fragment;
516 }
517 else {
518 return $base . $fragment;
519 }
520 }
521 }
522 else {
523 if (isset($path)) {
524 if (isset($query)) {
525 return $base . $path . '?' . $query . $fragment;
526 }
527 else {
528 return $base . $path . $fragment;
529 }
530 }
531 else {
532 if (isset($query)) {
533 return $base . $script . '?' . $query . $fragment;
534 }
535 else {
536 return $base . $fragment;
537 }
538 }
539 }
540 }
541
542 /**
543 * Authenticate the user against the drupal db
544 *
545 * @param string $name the user name
546 * @param string $password the password for the above user name
a5ecff8d
CB
547 * @param boolean $loadCMSBootstrap load cms bootstrap?
548 * @param NULL|string $realPath filename of script
6a488035
TO
549 *
550 * @return mixed false if no auth
551 * array(
552 * contactID, ufID, unique string ) if success
553 * @access public
554 */
555 static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
556 require_once 'DB.php';
557
558 $config = CRM_Core_Config::singleton();
559
560 $dbDrupal = DB::connect($config->userFrameworkDSN);
561 if (DB::isError($dbDrupal)) {
562 CRM_Core_Error::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
563 }
564
565 $account = $userUid = $userMail = NULL;
566 if ($loadCMSBootstrap) {
567 $bootStrapParams = array();
568 if ($name && $password) {
569 $bootStrapParams = array(
570 'name' => $name,
571 'pass' => $password,
572 );
573 }
574 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
575
576 global $user;
577 if ($user) {
578 $userUid = $user->uid;
579 $userMail = $user->mail;
580 }
581 }
582 else {
583 // CRM-8638
584 // SOAP cannot load drupal bootstrap and hence we do it the old way
585 // Contact CiviSMTP folks if we run into issues with this :)
586 $cmsPath = $config->userSystem->cmsRootPath($realPath);
587
588 require_once ("$cmsPath/includes/bootstrap.inc");
589 require_once ("$cmsPath/includes/password.inc");
590
591 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
592 $name = $dbDrupal->escapeSimple($strtolower($name));
593 $sql = "
594SELECT u.*
595FROM {$config->userFrameworkUsersTableName} u
596WHERE LOWER(u.name) = '$name'
597AND u.status = 1
598";
599
600 $query = $dbDrupal->query($sql);
601 $row = $query->fetchRow(DB_FETCHMODE_ASSOC);
602
603 if ($row) {
604 $fakeDrupalAccount = drupal_anonymous_user();
605 $fakeDrupalAccount->name = $name;
606 $fakeDrupalAccount->pass = $row['pass'];
607 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
608 if ($passwordCheck) {
609 $userUid = $row['uid'];
610 $userMail = $row['mail'];
611 }
612 }
613 }
614
615 if ($userUid && $userMail) {
616 CRM_Core_BAO_UFMatch::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
617 $contactID = CRM_Core_BAO_UFMatch::getContactId($userUid);
618 if (!$contactID) {
619 return FALSE;
620 }
621 return array($contactID, $userUid, mt_rand());
622 }
623 return FALSE;
624 }
625
626 /*
627 * Load user into session
628 */
629 function loadUser($username) {
630 global $user;
631
632 $user = user_load_by_name($username);
633
634 if (empty($user->uid)) {
635 return FALSE;
636 }
637
638 $uid = $user->uid;
639 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
640
641 // lets store contact id and user id in session
642 $session = CRM_Core_Session::singleton();
643 $session->set('ufID', $uid);
644 $session->set('userID', $contact_id);
645 return TRUE;
646 }
647
82d9c21e 648 /**
53980972 649 * Perform any post login activities required by the UF -
650 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
651 * calls hook_user op 'login' and generates a new session.
e43cc689 652 *
95d68223
TO
653 * @param array params
654 *
655 * FIXME: Document values accepted/required by $params
53980972 656 */
657 function userLoginFinalize($params = array()){
658 user_login_finalize($params);
82d9c21e 659 }
660
46b6363c
TO
661 /**
662 * Determine the native ID of the CMS user
663 *
664 * @param $username
665 * @return int|NULL
666 */
667 function getUfId($username) {
668 $user = user_load_by_name($username);
669 if (empty($user->uid)) {
670 return NULL;
671 }
672 return $user->uid;
673 }
674
6a488035
TO
675 /**
676 * Set a message in the UF to display to a user
677 *
678 * @param string $message the message to set
679 *
680 * @access public
681 */
682 function setMessage($message) {
683 drupal_set_message($message);
684 }
685
686 function permissionDenied() {
687 drupal_access_denied();
688 }
689
690 function logout() {
691 module_load_include('inc', 'user', 'user.pages');
692 return user_logout();
693 }
694
695 function updateCategories() {
696 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
697 // CRM-3600
698 cache_clear_all();
699 menu_rebuild();
700 }
701
702 /**
703 * Get the default location for CiviCRM blocks
704 *
705 * @return string
706 */
707 function getDefaultBlockLocation() {
708 return 'sidebar_first';
709 }
710
711 /**
712 * Get the locale set in the hosting CMS
713 *
714 * @return string with the locale or null for none
715 */
716 function getUFLocale() {
717 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
718 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
1c9f455c 719 // sometimes for CLI based on order called, this might not be set and/or empty
6a488035 720 global $language;
6a488035 721
1c9f455c
DL
722 if (empty($language)) {
723 return NULL;
724 }
6a488035 725
1c9f455c
DL
726 if ($language->language == 'zh-hans') {
727 return 'zh_CN';
728 }
6a488035 729
1c9f455c
DL
730 if ($language->language == 'zh-hant') {
731 return 'zh_TW';
6a488035 732 }
1c9f455c
DL
733
734 if (preg_match('/^.._..$/', $language->language)) {
735 return $language->language;
736 }
737
738 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
6a488035
TO
739 }
740
741 function getVersion() {
742 return defined('VERSION') ? VERSION : 'Unknown';
743 }
744
745 /**
746 * load drupal bootstrap
747 *
a5ecff8d
CB
748 * @param array $params Either uid, or name & pass.
749 * @param boolean $loadUser boolean Require CMS user load.
750 * @param boolean $throwError If true, print error on failure and exit.
751 * @param boolean|string $realPath path to script
6a488035 752 */
0af0e4c9 753 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
6a488035
TO
754 //take the cms root path.
755 $cmsPath = $this->cmsRootPath($realPath);
756
757 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
758 if ($throwError) {
759 echo '<br />Sorry, could not locate bootstrap.inc\n';
760 exit();
761 }
762 return FALSE;
763 }
764 // load drupal bootstrap
765 chdir($cmsPath);
766 define('DRUPAL_ROOT', $cmsPath);
767
768 // For drupal multi-site CRM-11313
769 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
770 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
771 if (!empty($matches[1])) {
772 $_SERVER['HTTP_HOST'] = $matches[1];
773 }
774 }
775 require_once 'includes/bootstrap.inc';
38507482
CB
776 // @ to suppress notices eg 'DRUPALFOO already defined'.
777 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
6a488035
TO
778
779 // explicitly setting error reporting, since we cannot handle drupal related notices
780 error_reporting(1);
0af0e4c9 781 if (!function_exists('module_exists') || !module_exists('civicrm')) {
6a488035
TO
782 if ($throwError) {
783 echo '<br />Sorry, could not load drupal bootstrap.';
784 exit();
785 }
786 return FALSE;
787 }
788
789 // seems like we've bootstrapped drupal
790 $config = CRM_Core_Config::singleton();
791
6a488035
TO
792 // lets also fix the clean url setting
793 // CRM-6948
794 $config->cleanURL = (int) variable_get('clean_url', '0');
795
796 // we need to call the config hook again, since we now know
797 // all the modules that are listening on it, does not apply
798 // to J! and WP as yet
799 // CRM-8655
800 CRM_Utils_Hook::config($config);
801
802 if (!$loadUser) {
803 return TRUE;
804 }
805
806 $uid = CRM_Utils_Array::value('uid', $params);
807 if (!$uid) {
808 //load user, we need to check drupal permissions.
809 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
810 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
811
812 if ($name) {
813 $uid = user_authenticate($name, $pass);
814 if (!$uid) {
815 if ($throwError) {
816 echo '<br />Sorry, unrecognized username or password.';
817 exit();
818 }
819 return FALSE;
820 }
821 }
822 }
823
824 if ($uid) {
825 $account = user_load($uid);
826 if ($account && $account->uid) {
827 global $user;
828 $user = $account;
829 return TRUE;
830 }
831 }
832
833 if ($throwError) {
834 echo '<br />Sorry, can not load CMS user account.';
835 exit();
836 }
837
0af0e4c9
DL
838 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
839 // which means that define(CIVICRM_CLEANURL) was correctly set.
6a488035
TO
840 // So we correct it
841 $config = CRM_Core_Config::singleton();
842 $config->cleanURL = (int)variable_get('clean_url', '0');
843
844 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
845 CRM_Utils_Hook::config($config);
846
847 return FALSE;
848 }
849
a5ecff8d
CB
850 /**
851 *
852 */
6a488035 853 function cmsRootPath($scriptFilename = NULL) {
6a488035
TO
854 $cmsRoot = $valid = NULL;
855
856 if (!is_null($scriptFilename)) {
857 $path = $scriptFilename;
858 }
859 else {
860 $path = $_SERVER['SCRIPT_FILENAME'];
861 }
862
863 if (function_exists('drush_get_context')) {
864 // drush anyway takes care of multisite install etc
865 return drush_get_context('DRUSH_DRUPAL_ROOT');
866 }
867 // CRM-7582
868 $pathVars = explode('/',
869 str_replace('//', '/',
870 str_replace('\\', '/', $path)
871 )
872 );
873
874 //lets store first var,
875 //need to get back for windows.
876 $firstVar = array_shift($pathVars);
877
878 //lets remove sript name to reduce one iteration.
879 array_pop($pathVars);
880
881 //CRM-7429 --do check for upper most 'includes' dir,
882 //which would effectually work for multisite installation.
883 do {
884 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
885 $cmsIncludePath = "$cmsRoot/includes";
886 //stop as we found bootstrap.
887 if (@opendir($cmsIncludePath) &&
888 file_exists("$cmsIncludePath/bootstrap.inc")
889 ) {
890 $valid = TRUE;
891 break;
892 }
893 //remove one directory level.
894 array_pop($pathVars);
895 } while (count($pathVars));
896
897 return ($valid) ? $cmsRoot : NULL;
898 }
899
900 /**
901 * check is user logged in.
902 *
903 * @return boolean true/false.
904 */
905 public function isUserLoggedIn() {
906 $isloggedIn = FALSE;
907 if (function_exists('user_is_logged_in')) {
908 $isloggedIn = user_is_logged_in();
909 }
910
911 return $isloggedIn;
912 }
913
914 /**
915 * Get currently logged in user uf id.
916 *
917 * @return int $userID logged in user uf id.
918 */
919 public function getLoggedInUfID() {
920 $ufID = NULL;
921 if (function_exists('user_is_logged_in') &&
922 user_is_logged_in() &&
923 function_exists('user_uid_optional_to_arg')
924 ) {
925 $ufID = user_uid_optional_to_arg(array());
926 }
927
928 return $ufID;
929 }
930
931 /**
932 * Format the url as per language Negotiation.
933 *
934 * @param string $url
935 *
936 * @return string $url, formatted url.
937 * @static
938 */
a5ecff8d 939 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
6a488035
TO
940 if (empty($url)) {
941 return $url;
942 }
943
944 //CRM-7803 -from d7 onward.
945 $config = CRM_Core_Config::singleton();
946 if (function_exists('variable_get') &&
947 module_exists('locale') &&
948 function_exists('language_negotiation_get')
949 ) {
950 global $language;
951
952 //does user configuration allow language
953 //support from the URL (Path prefix or domain)
954 if (language_negotiation_get('language') == 'locale-url') {
955 $urlType = variable_get('locale_language_negotiation_url_part');
956
957 //url prefix
958 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
959 if (isset($language->prefix) && $language->prefix) {
960 if ($addLanguagePart) {
3fe61451 961 $url .= $language->prefix . '/';
6a488035
TO
962 }
963 if ($removeLanguagePart) {
964 $url = str_replace("/{$language->prefix}/", '/', $url);
965 }
966 }
967 }
968 //domain
969 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
970 if (isset($language->domain) && $language->domain) {
971 if ($addLanguagePart) {
3fe61451 972 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $language->domain . base_path();
6a488035
TO
973 }
974 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
975 $url = str_replace('\\', '/', $url);
976 $parseUrl = parse_url($url);
977
978 //kinda hackish but not sure how to do it right
979 //hope http_build_url() will help at some point.
980 if (is_array($parseUrl) && !empty($parseUrl)) {
981 $urlParts = explode('/', $url);
982 $hostKey = array_search($parseUrl['host'], $urlParts);
983 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
984 $urlParts[$hostKey] = $ufUrlParts['host'];
985 $url = implode('/', $urlParts);
986 }
987 }
988 }
989 }
990 }
991 }
992
993 return $url;
994 }
995
996 /**
997 * Find any users/roles/security-principals with the given permission
998 * and replace it with one or more permissions.
999 *
1000 * @param $oldPerm string
1001 * @param $newPerms array, strings
1002 *
1003 * @return void
1004 */
1005 function replacePermission($oldPerm, $newPerms) {
1006 $roles = user_roles(FALSE, $oldPerm);
1007 if (!empty($roles)) {
1008 foreach (array_keys($roles) as $rid) {
1009 user_role_revoke_permissions($rid, array($oldPerm));
1010 user_role_grant_permissions($rid, $newPerms);
1011 }
1012 }
1013 }
1014
1015 /**
1016 * Get a list of all installed modules, including enabled and disabled ones
1017 *
1018 * @return array CRM_Core_Module
1019 */
1020 function getModules() {
1021 $result = array();
1022 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
1023 foreach ($q as $row) {
1024 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
1025 }
1026 return $result;
1027 }
1028
1029 /**
1030 * Wrapper for og_membership creation
a5ecff8d
CB
1031 *
1032 * @param integer $ogID Organic Group ID
1033 * @param integer $drupalID drupal User ID
6a488035
TO
1034 */
1035 function og_membership_create($ogID, $drupalID){
1036 if (function_exists('og_entity_query_alter')) {
a5ecff8d
CB
1037 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
1038 //
1039 // @TODO Find more solid way to check - try system_get_info('module', 'og').
1040 //
1041 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
6a488035
TO
1042 og_group('node', $ogID, array('entity' => user_load($drupalID)));
1043 }
1044 else {
1045 // Works for the OG 7.x-1.x branch
1046 og_group($ogID, array('entity' => user_load($drupalID)));
1047 }
1048 }
1049
1050 /**
1051 * Wrapper for og_membership deletion
a5ecff8d
CB
1052 *
1053 * @param integer $ogID Organic Group ID
1054 * @param integer $drupalID drupal User ID
6a488035
TO
1055 */
1056 function og_membership_delete($ogID, $drupalID) {
1057 if (function_exists('og_entity_query_alter')) {
1058 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
1059 // TODO: Find a more solid way to make this test
1060 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
1061 og_ungroup('node', $ogID, 'user', user_load($drupalID));
1062 } else {
1063 // Works for the OG 7.x-1.x branch
1064 og_ungroup($ogID, 'user', user_load($drupalID));
1065 }
1066 }
d8a4acc0 1067
5a604d61
E
1068 /**
1069 * Get timezone from Drupal
1070 * @return boolean|string
1071 */
1072 function getTimeZoneOffset(){
1073 global $user;
1074 if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
1075 $timezone = $user->timezone;
1076 } else {
1077 $timezone = variable_get('date_default_timezone', null);
1078 }
1079 $tzObj = new DateTimeZone($timezone);
1080 $dateTime = new DateTime("now", $tzObj);
1081 $tz = $tzObj->getOffset($dateTime);
1082
1083 if(empty($tz)){
1084 return false;
1085 }
1086
1087 $timeZoneOffset = sprintf("%02d:%02d", $tz / 3600, ($tz/60)%60 );
1088
1089 if($timeZoneOffset > 0){
1090 $timeZoneOffset = '+' . $timeZoneOffset;
1091 }
1092 return $timeZoneOffset;
1093 }
d8a4acc0
C
1094 /**
1095 * Reset any system caches that may be required for proper CiviCRM
1096 * integration.
1097 */
1098 function flush() {
1099 drupal_flush_all_caches();
1100 }
6a488035 1101}