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