Comment block fixes
[civicrm-core.git] / CRM / Utils / System / Drupal6.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
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 /**
42 * if we are using a theming system, invoke theme, else just print the
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 /**
76 * Function to create a user in Drupal.
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 */
127 function updateCMSName($ufID, $ufName) {
128 // CRM-5555
129 if (function_exists('user_load')) {
130 $user = user_load(array('uid' => $ufID));
131 if ($user->mail != $ufName) {
132 user_save($user, array('mail' => $ufName));
133 $user = user_load(array('uid' => $ufID));
134 }
135 }
136 }
137
138 /**
139 * Check if username and email exists in the drupal db
140 *
141 * @params $params array array of name and mail values
142 * @params $errors array array of errors
143 * @params $emailName string field label for the 'email'
144 *
f4aaa82a
EM
145 * @param $params
146 * @param $errors
147 * @param string $emailName
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 /**
6a488035
TO
214 * Function to get the drupal destination string. When this is passed in the
215 * URL the user will be directed to it after filling in the drupal form
216 *
217 * @param object $form Form object representing the 'current' form - to which the user will be returned
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 /**
252 * sets the title of the page
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) {
341 switch ($region) {
342 case 'html-header':
343 case 'page-footer':
344 $scope = substr($region, 5);
345 break;
346 default:
347 return FALSE;
348 }
349 // If the path is within the drupal directory we can add in the normal way
42e1a97c 350 if ($this->formatResourceUrl($url)) {
6a488035 351 drupal_add_js($url, 'module', $scope);
a03524aa 352 return TRUE;
6a488035 353 }
a03524aa 354 return FALSE;
6a488035
TO
355 }
356
357 /**
358 * Add an inline script
359 *
360 * @param $code: string, javascript code
361 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
362 *
363 * Note: This function is not to be called directly
364 * @see CRM_Core_Region::render()
365 *
366 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
367 * @access public
368 */
369 public function addScript($code, $region) {
370 switch ($region) {
371 case 'html-header':
372 case 'page-footer':
373 $scope = substr($region, 5);
374 break;
375 default:
376 return FALSE;
377 }
378 drupal_add_js($code, 'inline', $scope);
379 return TRUE;
380 }
381
382 /**
383 * Add a css file
384 *
385 * @param $url: string, absolute path to file
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 addStyleUrl($url, $region) {
42e1a97c 395 if ($region != 'html-header' || !$this->formatResourceUrl($url)) {
6a488035
TO
396 return FALSE;
397 }
398 drupal_add_css($url);
399 return TRUE;
400 }
401
402 /**
403 * Add an inline style
404 *
405 * @param $code: string, css code
406 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
407 *
408 * Note: This function is not to be called directly
409 * @see CRM_Core_Region::render()
410 *
411 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
412 * @access public
413 */
414 public function addStyle($code, $region) {
415 return FALSE;
416 }
417
418 /**
419 * rewrite various system urls to https
420 *
421 * @param null
422 *
423 * @return void
424 * @access public
425 */
426 function mapConfigToSSL() {
427 global $base_url;
428 $base_url = str_replace('http://', 'https://', $base_url);
429 }
430
431 /**
432 * figure out the post url for the form
433 *
434 * @param mix $action the default action if one is pre-specified
435 *
436 * @return string the url to post the form
437 * @access public
6a488035
TO
438 */
439 function postURL($action) {
440 if (!empty($action)) {
441 return $action;
442 }
443
444 return $this->url($_GET['q']);
445 }
446
6a488035
TO
447 /**
448 * Authenticate the user against the drupal db
449 *
450 * @param string $name the user name
451 * @param string $password the password for the above user name
a5ecff8d
CB
452 * @param boolean $loadCMSBootstrap load cms bootstrap?
453 * @param NULL|string $realPath filename of script
6a488035
TO
454 *
455 * @return mixed false if no auth
456 * array(
457 * contactID, ufID, unique string ) if success
458 * @access public
459 */
460 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
bc2f844f
E
461 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
462 // if ever now.
463 // probably if bootstrap is loaded this call
464 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
465 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
466 // safe in the unknown situation where authenticate might be called & it is important that
467 // false is returned
6a488035
TO
468 require_once 'DB.php';
469
470 $config = CRM_Core_Config::singleton();
471
472 $dbDrupal = DB::connect($config->userFrameworkDSN);
473 if (DB::isError($dbDrupal)) {
474 CRM_Core_Error::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
475 }
476
477 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
478 $dbpassword = md5($password);
479 $name = $dbDrupal->escapeSimple($strtolower($name));
b67a6d82 480 $sql = 'SELECT u.* FROM ' . $config->userFrameworkUsersTableName . " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
6a488035
TO
481 $query = $dbDrupal->query($sql);
482
483 $user = NULL;
484 // need to change this to make sure we matched only one row
485 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC)) {
486 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
487 $contactID = CRM_Core_BAO_UFMatch::getContactId($row['uid']);
488 if (!$contactID) {
489 return FALSE;
490 }
491 else{//success
492 if ($loadCMSBootstrap) {
493 $bootStrapParams = array();
494 if ($name && $password) {
495 $bootStrapParams = array(
496 'name' => $name,
497 'pass' => $password,
498 );
499 }
500 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
501 }
a5ecff8d
CB
502 return array($contactID, $row['uid'], mt_rand());
503 }
6a488035
TO
504 }
505 return FALSE;
506 }
507
f4aaa82a 508 /**
6a488035
TO
509 * Load user into session
510 */
511 function loadUser($username) {
512 global $user;
513 $user = user_load(array('name' => $username));
514 if (empty($user->uid)) {
515 return FALSE;
516 }
517
518 $uid = $user->uid;
519 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
520
521 // lets store contact id and user id in session
522 $session = CRM_Core_Session::singleton();
523 $session->set('ufID', $uid);
524 $session->set('userID', $contact_id);
525 return TRUE;
526 }
527
82d9c21e 528 /**
53980972 529 * Perform any post login activities required by the UF -
530 * e.g. for drupal : records a watchdog message about the new session,
531 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
e43cc689 532 *
95d68223
TO
533 * @param array params
534 *
535 * FIXME: Document values accepted/required by $params
53980972 536 */
537 function userLoginFinalize($params = array()) {
538 user_authenticate_finalize($params);
82d9c21e 539 }
540
46b6363c
TO
541 /**
542 * Determine the native ID of the CMS user
543 *
544 * @param $username
545 * @return int|NULL
546 */
547 function getUfId($username) {
548 $user = user_load(array('name' => $username));
549 if (empty($user->uid)) {
550 return NULL;
551 }
552 return $user->uid;
553 }
554
6a488035
TO
555 /**
556 * Set a message in the UF to display to a user
557 *
558 * @param string $message the message to set
559 *
560 * @access public
561 */
562 function setMessage($message) {
563 drupal_set_message($message);
564 }
565
6a488035
TO
566 function logout() {
567 module_load_include('inc', 'user', 'user.pages');
568 return user_logout();
569 }
570
571 function updateCategories() {
572 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
573 // CRM-3600
574 cache_clear_all();
575 menu_rebuild();
576 }
577
578 /**
579 * Get the locale set in the hosting CMS
580 *
581 * @return string with the locale or null for none
582 */
583 function getUFLocale() {
584 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
585 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
cbb2e021 586 // sometimes for CLI based on order called, this might not be set and/or empty
6a488035 587 global $language;
6a488035 588
cbb2e021
CB
589 if (empty($language)) {
590 return NULL;
591 }
6a488035 592
cbb2e021
CB
593 if ($language->language == 'zh-hans') {
594 return 'zh_CN';
595 }
6a488035 596
cbb2e021
CB
597 if ($language->language == 'zh-hant') {
598 return 'zh_TW';
6a488035 599 }
cbb2e021
CB
600
601 if (preg_match('/^.._..$/', $language->language)) {
602 return $language->language;
603 }
604
605 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
6a488035
TO
606 }
607
608 function getVersion() {
609 return defined('VERSION') ? VERSION : 'Unknown';
610 }
611
612 /**
613 * load drupal bootstrap
614 *
a5ecff8d
CB
615 * @param array $params Either uid, or name & pass.
616 * @param boolean $loadUser boolean Require CMS user load.
617 * @param boolean $throwError If true, print error on failure and exit.
618 * @param boolean|string $realPath path to script
f4aaa82a
EM
619 *
620 * @return bool
6a488035 621 */
a5ecff8d 622 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
6a488035
TO
623 //take the cms root path.
624 $cmsPath = $this->cmsRootPath($realPath);
4459cd26 625
6a488035 626 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
4459cd26
CB
627 if ($throwError) {
628 echo '<br />Sorry, could not locate bootstrap.inc\n';
629 exit();
630 }
631 return FALSE;
6a488035 632 }
4459cd26 633 // load drupal bootstrap
6a488035 634 chdir($cmsPath);
4459cd26
CB
635 define('DRUPAL_ROOT', $cmsPath);
636
637 // For drupal multi-site CRM-11313
638 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
639 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
640 if (!empty($matches[1])) {
641 $_SERVER['HTTP_HOST'] = $matches[1];
642 }
643 }
6a488035 644 require_once 'includes/bootstrap.inc';
38507482 645 // @ to suppress notices eg 'DRUPALFOO already defined'.
6a488035
TO
646 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
647
4459cd26
CB
648 // explicitly setting error reporting, since we cannot handle drupal related notices
649 error_reporting(1);
a5ecff8d 650 if (!function_exists('module_exists') || !module_exists('civicrm')) {
4459cd26
CB
651 if ($throwError) {
652 echo '<br />Sorry, could not load drupal bootstrap.';
653 exit();
654 }
655 return FALSE;
6a488035 656 }
a5ecff8d 657
4459cd26
CB
658 // seems like we've bootstrapped drupal
659 $config = CRM_Core_Config::singleton();
660
6a488035
TO
661 // lets also fix the clean url setting
662 // CRM-6948
663 $config->cleanURL = (int) variable_get('clean_url', '0');
664
665 // we need to call the config hook again, since we now know
666 // all the modules that are listening on it, does not apply
667 // to J! and WP as yet
668 // CRM-8655
669 CRM_Utils_Hook::config($config);
670
671 if (!$loadUser) {
672 return TRUE;
673 }
95915c38 674 global $user;
4459cd26
CB
675 // If $uid is passed in, authentication has been done already.
676 $uid = CRM_Utils_Array::value('uid', $params);
677 if (!$uid) {
678 //load user, we need to check drupal permissions.
679 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
680 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
681
682 if ($name) {
95915c38
E
683 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
684 if (!$user->uid) {
4459cd26
CB
685 if ($throwError) {
686 echo '<br />Sorry, unrecognized username or password.';
687 exit();
688 }
689 return FALSE;
690 }
95915c38
E
691 else {
692 return TRUE;
693 }
6a488035
TO
694 }
695 }
4459cd26
CB
696
697 if ($uid) {
698 $account = user_load($uid);
699 if ($account && $account->uid) {
6a488035 700 $user = $account;
4459cd26 701 return TRUE;
6a488035
TO
702 }
703 }
4459cd26
CB
704
705 if ($throwError) {
706 echo '<br />Sorry, can not load CMS user account.';
707 exit();
708 }
709
710 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
711 // which means that define(CIVICRM_CLEANURL) was correctly set.
712 // So we correct it
713 $config = CRM_Core_Config::singleton();
714 $config->cleanURL = (int)variable_get('clean_url', '0');
715
716 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
717 CRM_Utils_Hook::config($config);
718
719 return FALSE;
6a488035
TO
720 }
721
a5ecff8d
CB
722 /**
723 *
724 */
6a488035
TO
725 function cmsRootPath($scriptFilename = NULL) {
726 $cmsRoot = $valid = NULL;
727
728 if (!is_null($scriptFilename)) {
729 $path = $scriptFilename;
730 }
731 else {
732 $path = $_SERVER['SCRIPT_FILENAME'];
733 }
a5ecff8d 734
6a488035
TO
735 if (function_exists('drush_get_context')) {
736 // drush anyway takes care of multisite install etc
737 return drush_get_context('DRUSH_DRUPAL_ROOT');
738 }
739 // CRM-7582
740 $pathVars = explode('/',
741 str_replace('//', '/',
742 str_replace('\\', '/', $path)
743 )
744 );
745
746 //lets store first var,
747 //need to get back for windows.
748 $firstVar = array_shift($pathVars);
749
750 //lets remove sript name to reduce one iteration.
751 array_pop($pathVars);
752
753 //CRM-7429 --do check for upper most 'includes' dir,
754 //which would effectually work for multisite installation.
755 do {
756 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
757 $cmsIncludePath = "$cmsRoot/includes";
758 //stop as we found bootstrap.
759 if (@opendir($cmsIncludePath) &&
760 file_exists("$cmsIncludePath/bootstrap.inc")
761 ) {
762 $valid = TRUE;
763 break;
764 }
765 //remove one directory level.
766 array_pop($pathVars);
767 } while (count($pathVars));
768
769 return ($valid) ? $cmsRoot : NULL;
770 }
771
772 /**
773 * check is user logged in.
774 *
775 * @return boolean true/false.
776 */
777 public function isUserLoggedIn() {
778 $isloggedIn = FALSE;
779 if (function_exists('user_is_logged_in')) {
780 $isloggedIn = user_is_logged_in();
781 }
782
783 return $isloggedIn;
784 }
785
786 /**
787 * Get currently logged in user uf id.
788 *
789 * @return int $userID logged in user uf id.
790 */
791 public function getLoggedInUfID() {
792 $ufID = NULL;
793 if (function_exists('user_is_logged_in') &&
794 user_is_logged_in() &&
795 function_exists('user_uid_optional_to_arg')
796 ) {
797 $ufID = user_uid_optional_to_arg(array());
798 }
799
800 return $ufID;
801 }
802
803 /**
804 * Format the url as per language Negotiation.
805 *
806 * @param string $url
807 *
f4aaa82a
EM
808 * @param bool $addLanguagePart
809 * @param bool $removeLanguagePart
810 *
6a488035
TO
811 * @return string $url, formatted url.
812 * @static
813 */
a5ecff8d 814 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
6a488035
TO
815 if (empty($url)) {
816 return $url;
817 }
818
819 //upto d6 only, already we have code in place for d7
820 $config = CRM_Core_Config::singleton();
821 if (function_exists('variable_get') &&
822 module_exists('locale')
823 ) {
824 global $language;
825
826 //get the mode.
827 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE);
828
829 //url prefix / path.
830 if (isset($language->prefix) &&
831 $language->prefix &&
832 in_array($mode, array(
833 LANGUAGE_NEGOTIATION_PATH,
834 LANGUAGE_NEGOTIATION_PATH_DEFAULT,
835 ))
836 ) {
837
838 if ($addLanguagePart) {
839 $url .= $language->prefix . '/';
840 }
841 if ($removeLanguagePart) {
842 $url = str_replace("/{$language->prefix}/", '/', $url);
843 }
844 }
845 if (isset($language->domain) &&
846 $language->domain &&
847 $mode == LANGUAGE_NEGOTIATION_DOMAIN
848 ) {
849
850 if ($addLanguagePart) {
851 $url = CRM_Utils_File::addTrailingSlash($language->domain, '/');
852 }
853 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
854 $url = str_replace('\\', '/', $url);
855 $parseUrl = parse_url($url);
856
857 //kinda hackish but not sure how to do it right
858 //hope http_build_url() will help at some point.
859 if (is_array($parseUrl) && !empty($parseUrl)) {
860 $urlParts = explode('/', $url);
861 $hostKey = array_search($parseUrl['host'], $urlParts);
862 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
863 $urlParts[$hostKey] = $ufUrlParts['host'];
864 $url = implode('/', $urlParts);
865 }
866 }
867 }
868 }
869
870 return $url;
871 }
872
873 /**
874 * Find any users/roles/security-principals with the given permission
875 * and replace it with one or more permissions.
876 *
877 * @param $oldPerm string
878 * @param $newPerms array, strings
879 *
880 * @return void
881 */
882 function replacePermission($oldPerm, $newPerms) {
883 $roles = user_roles(FALSE, $oldPerm);
884 foreach ($roles as $rid => $roleName) {
885 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
886 $perms = drupal_map_assoc(explode(', ', $permList));
887 unset($perms[$oldPerm]);
888 $perms = $perms + drupal_map_assoc($newPerms);
889 $permList = implode(', ', $perms);
890 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
891 /*
892 if ( ! empty( $roles ) ) {
893 $rids = implode(',', array_keys($roles));
894 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
895 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
896 $oldPerm, implode(', ', $newPerms) );*/
897 }
898 }
899
900 /**
901 * Get a list of all installed modules, including enabled and disabled ones
902 *
903 * @return array CRM_Core_Module
904 */
905 function getModules() {
906 $result = array();
907 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
908 while ($row = db_fetch_object($q)) {
909 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
910 }
911 return $result;
912 }
913
914 /**
915 * Get user login URL for hosting CMS (method declared in each CMS system class)
916 *
917 * @param string $destination - if present, add destination to querystring (works for Drupal only)
918 *
919 * @return string - loginURL for the current CMS
920 * @static
921 */
922 public function getLoginURL($destination = '') {
923 $config = CRM_Core_Config::singleton();
924 $loginURL = $config->userFrameworkBaseURL;
925 $loginURL .= 'user';
926 if (!empty($destination)) {
927 // append destination so user is returned to form they came from after login
928 $loginURL .= '?destination=' . urlencode($destination);
929 }
930 return $loginURL;
931 }
932
d761c4d8 933 /**
6a488035 934 * Wrapper for og_membership creation
d761c4d8 935 *
936 * @param integer $ogID Organic Group ID
937 * @param integer $drupalID drupal User ID
6a488035
TO
938 */
939 function og_membership_create($ogID, $drupalID){
d761c4d8 940 og_save_subscription( $ogID, $drupalID, array( 'is_active' => 1 ) );
6a488035
TO
941 }
942
943 /**
944 * Wrapper for og_membership deletion
d761c4d8 945 *
946 * @param integer $ogID Organic Group ID
947 * @param integer $drupalID drupal User ID
6a488035
TO
948 */
949 function og_membership_delete($ogID, $drupalID) {
d761c4d8 950 og_delete_subscription( $ogID, $drupalID );
6a488035
TO
951 }
952
5a604d61 953 /**
48ec57ab
TO
954 * Over-ridable function to get timezone as a string eg.
955 * @return string Timezone e.g. 'America/Los_Angeles'
5a604d61 956 */
48ec57ab 957 function getTimeZoneString() {
5a604d61
E
958 global $user;
959 if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
960 $timezone = $user->timezone;
961 } else {
962 $timezone = variable_get('date_default_timezone', null);
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 */
975 function flush() {
976 drupal_flush_all_caches();
977 }
6a488035 978}