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