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