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