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