Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-02-05-17-16-30
[civicrm-core.git] / CRM / Utils / System / Drupal.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * Drupal specific stuff goes here
38 */
39 class CRM_Utils_System_Drupal extends CRM_Utils_System_DrupalBase {
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) {
53 $form_state = form_state_defaults();
54
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) {
63 $form_state['input']['pass'] = array('pass1'=>$params['cms_pass'],'pass2'=>$params['cms_pass']);
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;
72 $form_state['complete form'] = FALSE;
73 $form_state['method'] = 'post';
74 $form_state['build_info']['args'] = array();
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;
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;
89 $form['#array_parents'] = array();
90 $form['#tree'] = FALSE;
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 }
98 return $form_state['user']->uid;
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
139 if (!empty($params['name'])) {
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
154 if (!empty($params['mail'])) {
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
335 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
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
384 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
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
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
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
445 * @param boolean $loadCMSBootstrap load cms bootstrap?
446 * @param NULL|string $realPath filename of script
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 = "
492 SELECT u.*
493 FROM {$config->userFrameworkUsersTableName} u
494 WHERE LOWER(u.name) = '$name'
495 AND 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
546 /**
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.
550 *
551 * @param array params
552 *
553 * FIXME: Document values accepted/required by $params
554 */
555 function userLoginFinalize($params = array()){
556 user_login_finalize($params);
557 }
558
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
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
584 function permissionDenied() {
585 drupal_access_denied();
586 }
587
588 function logout() {
589 module_load_include('inc', 'user', 'user.pages');
590 return user_logout();
591 }
592
593 function updateCategories() {
594 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
595 // CRM-3600
596 cache_clear_all();
597 menu_rebuild();
598 }
599
600 /**
601 * Get the default location for CiviCRM blocks
602 *
603 * @return string
604 */
605 function getDefaultBlockLocation() {
606 return 'sidebar_first';
607 }
608
609 /**
610 * Get the locale set in the hosting CMS
611 *
612 * @return string with the locale or null for none
613 */
614 function getUFLocale() {
615 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
616 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
617 // sometimes for CLI based on order called, this might not be set and/or empty
618 global $language;
619
620 if (empty($language)) {
621 return NULL;
622 }
623
624 if ($language->language == 'zh-hans') {
625 return 'zh_CN';
626 }
627
628 if ($language->language == 'zh-hant') {
629 return 'zh_TW';
630 }
631
632 if (preg_match('/^.._..$/', $language->language)) {
633 return $language->language;
634 }
635
636 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
637 }
638
639 function getVersion() {
640 return defined('VERSION') ? VERSION : 'Unknown';
641 }
642
643 /**
644 * load drupal bootstrap
645 *
646 * @param array $params Either uid, or name & pass.
647 * @param boolean $loadUser boolean Require CMS user load.
648 * @param boolean $throwError If true, print error on failure and exit.
649 * @param boolean|string $realPath path to script
650 */
651 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
652 //take the cms root path.
653 $cmsPath = $this->cmsRootPath($realPath);
654
655 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
656 if ($throwError) {
657 echo '<br />Sorry, could not locate bootstrap.inc\n';
658 exit();
659 }
660 return FALSE;
661 }
662 // load drupal bootstrap
663 chdir($cmsPath);
664 define('DRUPAL_ROOT', $cmsPath);
665
666 // For drupal multi-site CRM-11313
667 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
668 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
669 if (!empty($matches[1])) {
670 $_SERVER['HTTP_HOST'] = $matches[1];
671 }
672 }
673 require_once 'includes/bootstrap.inc';
674 // @ to suppress notices eg 'DRUPALFOO already defined'.
675 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
676
677 // explicitly setting error reporting, since we cannot handle drupal related notices
678 error_reporting(1);
679 if (!function_exists('module_exists') || !module_exists('civicrm')) {
680 if ($throwError) {
681 echo '<br />Sorry, could not load drupal bootstrap.';
682 exit();
683 }
684 return FALSE;
685 }
686
687 // seems like we've bootstrapped drupal
688 $config = CRM_Core_Config::singleton();
689
690 // lets also fix the clean url setting
691 // CRM-6948
692 $config->cleanURL = (int) variable_get('clean_url', '0');
693
694 // we need to call the config hook again, since we now know
695 // all the modules that are listening on it, does not apply
696 // to J! and WP as yet
697 // CRM-8655
698 CRM_Utils_Hook::config($config);
699
700 if (!$loadUser) {
701 return TRUE;
702 }
703
704 $uid = CRM_Utils_Array::value('uid', $params);
705 if (!$uid) {
706 //load user, we need to check drupal permissions.
707 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
708 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
709
710 if ($name) {
711 $uid = user_authenticate($name, $pass);
712 if (!$uid) {
713 if ($throwError) {
714 echo '<br />Sorry, unrecognized username or password.';
715 exit();
716 }
717 return FALSE;
718 }
719 }
720 }
721
722 if ($uid) {
723 $account = user_load($uid);
724 if ($account && $account->uid) {
725 global $user;
726 $user = $account;
727 return TRUE;
728 }
729 }
730
731 if ($throwError) {
732 echo '<br />Sorry, can not load CMS user account.';
733 exit();
734 }
735
736 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
737 // which means that define(CIVICRM_CLEANURL) was correctly set.
738 // So we correct it
739 $config = CRM_Core_Config::singleton();
740 $config->cleanURL = (int)variable_get('clean_url', '0');
741
742 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
743 CRM_Utils_Hook::config($config);
744
745 return FALSE;
746 }
747
748 /**
749 *
750 */
751 function cmsRootPath($scriptFilename = NULL) {
752 $cmsRoot = $valid = NULL;
753
754 if (!is_null($scriptFilename)) {
755 $path = $scriptFilename;
756 }
757 else {
758 $path = $_SERVER['SCRIPT_FILENAME'];
759 }
760
761 if (function_exists('drush_get_context')) {
762 // drush anyway takes care of multisite install etc
763 return drush_get_context('DRUSH_DRUPAL_ROOT');
764 }
765 // CRM-7582
766 $pathVars = explode('/',
767 str_replace('//', '/',
768 str_replace('\\', '/', $path)
769 )
770 );
771
772 //lets store first var,
773 //need to get back for windows.
774 $firstVar = array_shift($pathVars);
775
776 //lets remove sript name to reduce one iteration.
777 array_pop($pathVars);
778
779 //CRM-7429 --do check for upper most 'includes' dir,
780 //which would effectually work for multisite installation.
781 do {
782 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
783 $cmsIncludePath = "$cmsRoot/includes";
784 //stop as we found bootstrap.
785 if (@opendir($cmsIncludePath) &&
786 file_exists("$cmsIncludePath/bootstrap.inc")
787 ) {
788 $valid = TRUE;
789 break;
790 }
791 //remove one directory level.
792 array_pop($pathVars);
793 } while (count($pathVars));
794
795 return ($valid) ? $cmsRoot : NULL;
796 }
797
798 /**
799 * check is user logged in.
800 *
801 * @return boolean true/false.
802 */
803 public function isUserLoggedIn() {
804 $isloggedIn = FALSE;
805 if (function_exists('user_is_logged_in')) {
806 $isloggedIn = user_is_logged_in();
807 }
808
809 return $isloggedIn;
810 }
811
812 /**
813 * Get currently logged in user uf id.
814 *
815 * @return int $userID logged in user uf id.
816 */
817 public function getLoggedInUfID() {
818 $ufID = NULL;
819 if (function_exists('user_is_logged_in') &&
820 user_is_logged_in() &&
821 function_exists('user_uid_optional_to_arg')
822 ) {
823 $ufID = user_uid_optional_to_arg(array());
824 }
825
826 return $ufID;
827 }
828
829 /**
830 * Format the url as per language Negotiation.
831 *
832 * @param string $url
833 *
834 * @return string $url, formatted url.
835 * @static
836 */
837 function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
838 if (empty($url)) {
839 return $url;
840 }
841
842 //CRM-7803 -from d7 onward.
843 $config = CRM_Core_Config::singleton();
844 if (function_exists('variable_get') &&
845 module_exists('locale') &&
846 function_exists('language_negotiation_get')
847 ) {
848 global $language;
849
850 //does user configuration allow language
851 //support from the URL (Path prefix or domain)
852 if (language_negotiation_get('language') == 'locale-url') {
853 $urlType = variable_get('locale_language_negotiation_url_part');
854
855 //url prefix
856 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
857 if (isset($language->prefix) && $language->prefix) {
858 if ($addLanguagePart) {
859 $url .= $language->prefix . '/';
860 }
861 if ($removeLanguagePart) {
862 $url = str_replace("/{$language->prefix}/", '/', $url);
863 }
864 }
865 }
866 //domain
867 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
868 if (isset($language->domain) && $language->domain) {
869 if ($addLanguagePart) {
870 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $language->domain . base_path();
871 }
872 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
873 $url = str_replace('\\', '/', $url);
874 $parseUrl = parse_url($url);
875
876 //kinda hackish but not sure how to do it right
877 //hope http_build_url() will help at some point.
878 if (is_array($parseUrl) && !empty($parseUrl)) {
879 $urlParts = explode('/', $url);
880 $hostKey = array_search($parseUrl['host'], $urlParts);
881 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
882 $urlParts[$hostKey] = $ufUrlParts['host'];
883 $url = implode('/', $urlParts);
884 }
885 }
886 }
887 }
888 }
889 }
890
891 return $url;
892 }
893
894 /**
895 * Find any users/roles/security-principals with the given permission
896 * and replace it with one or more permissions.
897 *
898 * @param $oldPerm string
899 * @param $newPerms array, strings
900 *
901 * @return void
902 */
903 function replacePermission($oldPerm, $newPerms) {
904 $roles = user_roles(FALSE, $oldPerm);
905 if (!empty($roles)) {
906 foreach (array_keys($roles) as $rid) {
907 user_role_revoke_permissions($rid, array($oldPerm));
908 user_role_grant_permissions($rid, $newPerms);
909 }
910 }
911 }
912
913 /**
914 * Get a list of all installed modules, including enabled and disabled ones
915 *
916 * @return array CRM_Core_Module
917 */
918 function getModules() {
919 $result = array();
920 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
921 foreach ($q as $row) {
922 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
923 }
924 return $result;
925 }
926
927 /**
928 * Wrapper for og_membership creation
929 *
930 * @param integer $ogID Organic Group ID
931 * @param integer $drupalID drupal User ID
932 */
933 function og_membership_create($ogID, $drupalID){
934 if (function_exists('og_entity_query_alter')) {
935 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
936 //
937 // @TODO Find more solid way to check - try system_get_info('module', 'og').
938 //
939 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
940 og_group('node', $ogID, array('entity' => user_load($drupalID)));
941 }
942 else {
943 // Works for the OG 7.x-1.x branch
944 og_group($ogID, array('entity' => user_load($drupalID)));
945 }
946 }
947
948 /**
949 * Wrapper for og_membership deletion
950 *
951 * @param integer $ogID Organic Group ID
952 * @param integer $drupalID drupal User ID
953 */
954 function og_membership_delete($ogID, $drupalID) {
955 if (function_exists('og_entity_query_alter')) {
956 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
957 // TODO: Find a more solid way to make this test
958 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
959 og_ungroup('node', $ogID, 'user', user_load($drupalID));
960 } else {
961 // Works for the OG 7.x-1.x branch
962 og_ungroup($ogID, 'user', user_load($drupalID));
963 }
964 }
965
966 /**
967 * Get timezone from Drupal
968 * @return boolean|string
969 */
970 function getTimeZoneOffset(){
971 global $user;
972 if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
973 $timezone = $user->timezone;
974 } else {
975 $timezone = variable_get('date_default_timezone', null);
976 }
977 $tzObj = new DateTimeZone($timezone);
978 $dateTime = new DateTime("now", $tzObj);
979 $tz = $tzObj->getOffset($dateTime);
980
981 if(empty($tz)){
982 return false;
983 }
984
985 $timeZoneOffset = sprintf("%02d:%02d", $tz / 3600, ($tz/60)%60 );
986
987 if($timeZoneOffset > 0){
988 $timeZoneOffset = '+' . $timeZoneOffset;
989 }
990 return $timeZoneOffset;
991 }
992 /**
993 * Reset any system caches that may be required for proper CiviCRM
994 * integration.
995 */
996 function flush() {
997 drupal_flush_all_caches();
998 }
999 }