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