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