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