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