INFRA-132 - CRM/Utils - Convert single-line @param to multi-line
[civicrm-core.git] / CRM / Utils / System / Drupal.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 * Create a user in Drupal.
43 *
44 * @param array $params
45 * Associated array.
46 * @param string $mail
47 * Email id for cms user.
48 *
49 * @return uid if user exists, false otherwise
50 *
51 *
52 */
53 public function createUser(&$params, $mail) {
54 $form_state = form_state_defaults();
55
56 $form_state['input'] = array(
57 'name' => $params['cms_name'],
58 'mail' => $params[$mail],
59 'op' => 'Create new account',
60 );
61
62 $admin = user_access('administer users');
63 if (!variable_get('user_email_verification', TRUE) || $admin) {
64 $form_state['input']['pass'] = array('pass1'=>$params['cms_pass'],'pass2'=>$params['cms_pass']);
65 }
66
67 if(!empty($params['notify'])){
68 $form_state['input']['notify'] = $params['notify'];
69 }
70
71 $form_state['rebuild'] = FALSE;
72 $form_state['programmed'] = TRUE;
73 $form_state['complete form'] = FALSE;
74 $form_state['method'] = 'post';
75 $form_state['build_info']['args'] = array();
76 /*
77 * if we want to submit this form more than once in a process (e.g. create more than one user)
78 * we must force it to validate each time for this form. Otherwise it will not validate
79 * subsequent submissions and the manner in which the password is passed in will be invalid
80 */
81 $form_state['must_validate'] = TRUE;
82 $config = CRM_Core_Config::singleton();
83
84 // we also need to redirect b
85 $config->inCiviCRM = TRUE;
86
87 $form = drupal_retrieve_form('user_register_form', $form_state);
88 $form_state['process_input'] = 1;
89 $form_state['submitted'] = 1;
90 $form['#array_parents'] = array();
91 $form['#tree'] = FALSE;
92 drupal_process_form('user_register_form', $form, $form_state);
93
94 $config->inCiviCRM = FALSE;
95
96 if (form_get_errors()) {
97 return FALSE;
98 }
99 return $form_state['user']->uid;
100 }
101
102 /*
103 * Change user name in host CMS
104 *
105 * @param integer $ufID User ID in CMS
106 * @param string $ufName User name
107 */
108 /**
109 * @param int $ufID
110 * @param string $ufName
111 */
112 public function updateCMSName($ufID, $ufName) {
113 // CRM-5555
114 if (function_exists('user_load')) {
115 $user = user_load($ufID);
116 if ($user->mail != $ufName) {
117 user_save($user, array('mail' => $ufName));
118 $user = user_load($ufID);
119 }
120 }
121 }
122
123 /**
124 * Check if username and email exists in the drupal db
125 *
126 * @param array $params
127 * Array of name and mail values.
128 * @param array $errors
129 * Array of errors.
130 * @param string $emailName
131 * Field label for the 'email'.
132 *
133 * @return void
134 */
135 public 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 * 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 CRM_Core_Form $form
186 * Form object representing the 'current' form - to which the user will be returned.
187 * @return string $destination destination value for URL
188 *
189 */
190 /**
191 * @param CRM_Core_Form $form
192 *
193 * @return null|string
194 */
195 public function getLoginDestination(&$form) {
196 $args = NULL;
197
198 $id = $form->get('id');
199 if ($id) {
200 $args .= "&id=$id";
201 }
202 else {
203 $gid = $form->get('gid');
204 if ($gid) {
205 $args .= "&gid=$gid";
206 }
207 else {
208 // Setup Personal Campaign Page link uses pageId
209 $pageId = $form->get('pageId');
210 if ($pageId) {
211 $component = $form->get('component');
212 $args .= "&pageId=$pageId&component=$component&action=add";
213 }
214 }
215 }
216
217 $destination = NULL;
218 if ($args) {
219 // append destination so user is returned to form they came from after login
220 $destination = CRM_Utils_System::currentPath() . '?reset=1' . $args;
221 }
222 return $destination;
223 }
224
225 /**
226 * Get user login URL for hosting CMS (method declared in each CMS system class)
227 *
228 * @param string $destination
229 * If present, add destination to querystring (works for Drupal only).
230 *
231 * @return string - loginURL for the current CMS
232 * @static
233 */
234 public function getLoginURL($destination = '') {
235 $query = $destination ? array('destination' => $destination) : array();
236 return url('user', array('query' => $query));
237 }
238
239
240 /**
241 * Sets the title of the page
242 *
243 * @param string $title
244 * @param null $pageTitle
245 *
246 * @paqram string $pageTitle
247 *
248 * @return void
249 */
250 public function setTitle($title, $pageTitle = NULL) {
251 if (arg(0) == 'civicrm') {
252 if (!$pageTitle) {
253 $pageTitle = $title;
254 }
255
256 drupal_set_title($pageTitle, PASS_THROUGH);
257 }
258 }
259
260 /**
261 * Append an additional breadcrumb tag to the existing breadcrumb
262 *
263 * @param array $breadCrumbs
264 * @internal param string $title
265 * @internal param string $url
266 *
267 * @return void
268 */
269 public function appendBreadCrumb($breadCrumbs) {
270 $breadCrumb = drupal_get_breadcrumb();
271
272 if (is_array($breadCrumbs)) {
273 foreach ($breadCrumbs as $crumbs) {
274 if (stripos($crumbs['url'], 'id%%')) {
275 $args = array('cid', 'mid');
276 foreach ($args as $a) {
277 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
278 FALSE, NULL, $_GET
279 );
280 if ($val) {
281 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
282 }
283 }
284 }
285 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
286 }
287 }
288 drupal_set_breadcrumb($breadCrumb);
289 }
290
291 /**
292 * Reset an additional breadcrumb tag to the existing breadcrumb
293 *
294 * @return void
295 */
296 public function resetBreadCrumb() {
297 $bc = array();
298 drupal_set_breadcrumb($bc);
299 }
300
301 /**
302 * Append a string to the head of the html file
303 *
304 * @param string $header
305 * The new string to be appended.
306 *
307 * @return void
308 */
309 public function addHTMLHead($header) {
310 static $count = 0;
311 if (!empty($header)) {
312 $key = 'civi_' . ++$count;
313 $data = array(
314 '#type' => 'markup',
315 '#markup' => $header,
316 );
317 drupal_add_html_head($data, $key);
318 }
319 }
320
321 /**
322 * Add a script file
323 *
324 * @param $url: string, absolute path to file
325 * @param $region
326 * String, location within the document: 'html-header', 'page-header', 'page-footer'.
327 *
328 * Note: This function is not to be called directly
329 * @see CRM_Core_Region::render()
330 *
331 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
332 */
333 public function addScriptUrl($url, $region) {
334 $params = array('group' => JS_LIBRARY, 'weight' => 10);
335 switch ($region) {
336 case 'html-header':
337 case 'page-footer':
338 $params['scope'] = substr($region, 5);
339 break;
340 default:
341 return FALSE;
342 }
343 // If the path is within the drupal directory we can use the more efficient 'file' setting
344 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
345 drupal_add_js($url, $params);
346 return TRUE;
347 }
348
349 /**
350 * Add an inline script
351 *
352 * @param $code: string, javascript code
353 * @param $region
354 * String, location within the document: 'html-header', 'page-header', 'page-footer'.
355 *
356 * Note: This function is not to be called directly
357 * @see CRM_Core_Region::render()
358 *
359 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
360 */
361 public function addScript($code, $region) {
362 $params = array('type' => 'inline', 'group' => JS_LIBRARY, 'weight' => 10);
363 switch ($region) {
364 case 'html-header':
365 case 'page-footer':
366 $params['scope'] = substr($region, 5);
367 break;
368 default:
369 return FALSE;
370 }
371 drupal_add_js($code, $params);
372 return TRUE;
373 }
374
375 /**
376 * Add a css file
377 *
378 * @param $url: string, absolute path to file
379 * @param $region
380 * String, location within the document: 'html-header', 'page-header', 'page-footer'.
381 *
382 * Note: This function is not to be called directly
383 * @see CRM_Core_Region::render()
384 *
385 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
386 */
387 public function addStyleUrl($url, $region) {
388 if ($region != 'html-header') {
389 return FALSE;
390 }
391 $params = array();
392 // If the path is within the drupal directory we can use the more efficient 'file' setting
393 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
394 drupal_add_css($url, $params);
395 return TRUE;
396 }
397
398 /**
399 * Add an inline style
400 *
401 * @param $code: string, css code
402 * @param $region
403 * String, location within the document: 'html-header', 'page-header', 'page-footer'.
404 *
405 * Note: This function is not to be called directly
406 * @see CRM_Core_Region::render()
407 *
408 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
409 */
410 public function addStyle($code, $region) {
411 if ($region != 'html-header') {
412 return FALSE;
413 }
414 $params = array('type' => 'inline');
415 drupal_add_css($code, $params);
416 return TRUE;
417 }
418
419 /**
420 * Rewrite various system urls to https
421 *
422 * @param null
423 *
424 * @return void
425 */
426 public function mapConfigToSSL() {
427 global $base_url;
428 $base_url = str_replace('http://', 'https://', $base_url);
429 }
430
431 /**
432 * Figure out the post url for the form
433 *
434 * @param mix $action
435 * The default action if one is pre-specified.
436 *
437 * @return string the url to post the form
438 */
439 public function postURL($action) {
440 if (!empty($action)) {
441 return $action;
442 }
443
444 return $this->url($_GET['q']);
445 }
446
447
448 /**
449 * Authenticate the user against the drupal db
450 *
451 * @param string $name
452 * The user name.
453 * @param string $password
454 * The password for the above user name.
455 * @param bool $loadCMSBootstrap
456 * 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 */
463 public static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
464 require_once 'DB.php';
465
466 $config = CRM_Core_Config::singleton();
467
468 $dbDrupal = DB::connect($config->userFrameworkDSN);
469 if (DB::isError($dbDrupal)) {
470 CRM_Core_Error::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
471 }
472
473 $account = $userUid = $userMail = NULL;
474 if ($loadCMSBootstrap) {
475 $bootStrapParams = array();
476 if ($name && $password) {
477 $bootStrapParams = array(
478 'name' => $name,
479 'pass' => $password,
480 );
481 }
482 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
483
484 global $user;
485 if ($user) {
486 $userUid = $user->uid;
487 $userMail = $user->mail;
488 }
489 }
490 else {
491 // CRM-8638
492 // SOAP cannot load drupal bootstrap and hence we do it the old way
493 // Contact CiviSMTP folks if we run into issues with this :)
494 $cmsPath = $config->userSystem->cmsRootPath($realPath);
495
496 require_once ("$cmsPath/includes/bootstrap.inc");
497 require_once ("$cmsPath/includes/password.inc");
498
499 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
500 $name = $dbDrupal->escapeSimple($strtolower($name));
501 $sql = "
502 SELECT u.*
503 FROM {$config->userFrameworkUsersTableName} u
504 WHERE LOWER(u.name) = '$name'
505 AND u.status = 1
506 ";
507
508 $query = $dbDrupal->query($sql);
509 $row = $query->fetchRow(DB_FETCHMODE_ASSOC);
510
511 if ($row) {
512 $fakeDrupalAccount = drupal_anonymous_user();
513 $fakeDrupalAccount->name = $name;
514 $fakeDrupalAccount->pass = $row['pass'];
515 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
516 if ($passwordCheck) {
517 $userUid = $row['uid'];
518 $userMail = $row['mail'];
519 }
520 }
521 }
522
523 if ($userUid && $userMail) {
524 CRM_Core_BAO_UFMatch::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
525 $contactID = CRM_Core_BAO_UFMatch::getContactId($userUid);
526 if (!$contactID) {
527 return FALSE;
528 }
529 return array($contactID, $userUid, mt_rand());
530 }
531 return FALSE;
532 }
533
534 /*
535 * Load user into session
536 */
537 /**
538 * @param string $username
539 *
540 * @return bool
541 */
542 public function loadUser($username) {
543 global $user;
544
545 $user = user_load_by_name($username);
546
547 if (empty($user->uid)) {
548 return FALSE;
549 }
550
551 $uid = $user->uid;
552 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
553
554 // lets store contact id and user id in session
555 $session = CRM_Core_Session::singleton();
556 $session->set('ufID', $uid);
557 $session->set('userID', $contact_id);
558 return TRUE;
559 }
560
561 /**
562 * Perform any post login activities required by the UF -
563 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
564 * calls hook_user op 'login' and generates a new session.
565 *
566 * @param array params
567 *
568 * FIXME: Document values accepted/required by $params
569 */
570 public function userLoginFinalize($params = array()){
571 user_login_finalize($params);
572 }
573
574 /**
575 * Determine the native ID of the CMS user
576 *
577 * @param string $username
578 * @return int|NULL
579 */
580 public function getUfId($username) {
581 $user = user_load_by_name($username);
582 if (empty($user->uid)) {
583 return NULL;
584 }
585 return $user->uid;
586 }
587
588 /**
589 * Set a message in the UF to display to a user
590 *
591 * @param string $message
592 * The message to set.
593 *
594 */
595 public function setMessage($message) {
596 drupal_set_message($message);
597 }
598
599 /**
600 * @return mixed
601 */
602 public function logout() {
603 module_load_include('inc', 'user', 'user.pages');
604 return user_logout();
605 }
606
607 public function updateCategories() {
608 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
609 // CRM-3600
610 cache_clear_all();
611 menu_rebuild();
612 }
613
614 /**
615 * Get the default location for CiviCRM blocks
616 *
617 * @return string
618 */
619 public function getDefaultBlockLocation() {
620 return 'sidebar_first';
621 }
622
623 /**
624 * Get the locale set in the hosting CMS
625 *
626 * @return string with the locale or null for none
627 */
628 public function getUFLocale() {
629 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
630 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
631 // sometimes for CLI based on order called, this might not be set and/or empty
632 global $language;
633
634 if (empty($language)) {
635 return NULL;
636 }
637
638 if ($language->language == 'zh-hans') {
639 return 'zh_CN';
640 }
641
642 if ($language->language == 'zh-hant') {
643 return 'zh_TW';
644 }
645
646 if (preg_match('/^.._..$/', $language->language)) {
647 return $language->language;
648 }
649
650 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
651 }
652
653 /**
654 * @return string
655 */
656 public function getVersion() {
657 return defined('VERSION') ? VERSION : 'Unknown';
658 }
659
660 /**
661 * Load drupal bootstrap
662 *
663 * @param array $params
664 * Either uid, or name & pass.
665 * @param bool $loadUser
666 * Boolean Require CMS user load.
667 * @param bool $throwError
668 * If true, print error on failure and exit.
669 * @param bool|string $realPath path to script
670 *
671 * @return bool
672 */
673 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
674 //take the cms root path.
675 $cmsPath = $this->cmsRootPath($realPath);
676
677 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
678 if ($throwError) {
679 echo '<br />Sorry, could not locate bootstrap.inc\n';
680 exit();
681 }
682 return FALSE;
683 }
684 // load drupal bootstrap
685 chdir($cmsPath);
686 define('DRUPAL_ROOT', $cmsPath);
687
688 // For drupal multi-site CRM-11313
689 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
690 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
691 if (!empty($matches[1])) {
692 $_SERVER['HTTP_HOST'] = $matches[1];
693 }
694 }
695 require_once 'includes/bootstrap.inc';
696 // @ to suppress notices eg 'DRUPALFOO already defined'.
697 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
698
699 // explicitly setting error reporting, since we cannot handle drupal related notices
700 error_reporting(1);
701 if (!function_exists('module_exists') || !module_exists('civicrm')) {
702 if ($throwError) {
703 echo '<br />Sorry, could not load drupal bootstrap.';
704 exit();
705 }
706 return FALSE;
707 }
708
709 // seems like we've bootstrapped drupal
710 $config = CRM_Core_Config::singleton();
711
712 // lets also fix the clean url setting
713 // CRM-6948
714 $config->cleanURL = (int) variable_get('clean_url', '0');
715
716 // we need to call the config hook again, since we now know
717 // all the modules that are listening on it, does not apply
718 // to J! and WP as yet
719 // CRM-8655
720 CRM_Utils_Hook::config($config);
721
722 if (!$loadUser) {
723 return TRUE;
724 }
725
726 $uid = CRM_Utils_Array::value('uid', $params);
727 if (!$uid) {
728 //load user, we need to check drupal permissions.
729 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
730 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
731
732 if ($name) {
733 $uid = user_authenticate($name, $pass);
734 if (!$uid) {
735 if ($throwError) {
736 echo '<br />Sorry, unrecognized username or password.';
737 exit();
738 }
739 return FALSE;
740 }
741 }
742 }
743
744 if ($uid) {
745 $account = user_load($uid);
746 if ($account && $account->uid) {
747 global $user;
748 $user = $account;
749 return TRUE;
750 }
751 }
752
753 if ($throwError) {
754 echo '<br />Sorry, can not load CMS user account.';
755 exit();
756 }
757
758 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
759 // which means that define(CIVICRM_CLEANURL) was correctly set.
760 // So we correct it
761 $config = CRM_Core_Config::singleton();
762 $config->cleanURL = (int)variable_get('clean_url', '0');
763
764 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
765 CRM_Utils_Hook::config($config);
766
767 return FALSE;
768 }
769
770 /**
771 *
772 */
773 public function cmsRootPath($scriptFilename = NULL) {
774 $cmsRoot = $valid = NULL;
775
776 if (!is_null($scriptFilename)) {
777 $path = $scriptFilename;
778 }
779 else {
780 $path = $_SERVER['SCRIPT_FILENAME'];
781 }
782
783 if (function_exists('drush_get_context')) {
784 // drush anyway takes care of multisite install etc
785 return drush_get_context('DRUSH_DRUPAL_ROOT');
786 }
787 // CRM-7582
788 $pathVars = explode('/',
789 str_replace('//', '/',
790 str_replace('\\', '/', $path)
791 )
792 );
793
794 //lets store first var,
795 //need to get back for windows.
796 $firstVar = array_shift($pathVars);
797
798 //lets remove sript name to reduce one iteration.
799 array_pop($pathVars);
800
801 // CRM-7429 -- do check for uppermost 'includes' dir, which would
802 // work for multisite installation.
803 do {
804 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
805 $cmsIncludePath = "$cmsRoot/includes";
806 // Stop if we find bootstrap.
807 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
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 public 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
927 * String.
928 * @param $newPerms
929 * Array, strings.
930 *
931 * @return void
932 */
933 public function replacePermission($oldPerm, $newPerms) {
934 $roles = user_roles(FALSE, $oldPerm);
935 if (!empty($roles)) {
936 foreach (array_keys($roles) as $rid) {
937 user_role_revoke_permissions($rid, array($oldPerm));
938 user_role_grant_permissions($rid, $newPerms);
939 }
940 }
941 }
942
943 /**
944 * Get a list of all installed modules, including enabled and disabled ones
945 *
946 * @return array CRM_Core_Module
947 */
948 public function getModules() {
949 $result = array();
950 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
951 foreach ($q as $row) {
952 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
953 }
954 return $result;
955 }
956
957 /**
958 * Wrapper for og_membership creation
959 *
960 * @param int $ogID
961 * Organic Group ID.
962 * @param int $drupalID
963 * Drupal User ID.
964 */
965 public function og_membership_create($ogID, $drupalID){
966 if (function_exists('og_entity_query_alter')) {
967 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
968 //
969 // @TODO Find more solid way to check - try system_get_info('module', 'og').
970 //
971 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
972 og_group('node', $ogID, array('entity' => user_load($drupalID)));
973 }
974 else {
975 // Works for the OG 7.x-1.x branch
976 og_group($ogID, array('entity' => user_load($drupalID)));
977 }
978 }
979
980 /**
981 * Wrapper for og_membership deletion
982 *
983 * @param int $ogID
984 * Organic Group ID.
985 * @param int $drupalID
986 * Drupal User ID.
987 */
988 public function og_membership_delete($ogID, $drupalID) {
989 if (function_exists('og_entity_query_alter')) {
990 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
991 // TODO: Find a more solid way to make this test
992 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
993 og_ungroup('node', $ogID, 'user', user_load($drupalID));
994 } else {
995 // Works for the OG 7.x-1.x branch
996 og_ungroup($ogID, 'user', user_load($drupalID));
997 }
998 }
999
1000 /**
1001 * Over-ridable function to get timezone as a string eg.
1002 * @return string Timezone e.g. 'America/Los_Angeles'
1003 */
1004 public function getTimeZoneString() {
1005 global $user;
1006 if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
1007 $timezone = $user->timezone;
1008 } else {
1009 $timezone = variable_get('date_default_timezone', null);
1010 }
1011 if (!$timezone) {
1012 $timezone = parent::getTimeZoneString();
1013 }
1014 return $timezone;
1015 }
1016 /**
1017 * Reset any system caches that may be required for proper CiviCRM
1018 * integration.
1019 */
1020 public function flush() {
1021 drupal_flush_all_caches();
1022 }
1023 }