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