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