INFRA-132 - Docblock formatting fixes
[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
104 * User ID in CMS
105 * @param string $ufName
106 * User name
107 */
108 public function updateCMSName($ufID, $ufName) {
109 // CRM-5555
110 if (function_exists('user_load')) {
111 $user = user_load($ufID);
112 if ($user->mail != $ufName) {
113 user_save($user, array('mail' => $ufName));
114 $user = user_load($ufID);
115 }
116 }
117 }
118
119 /**
120 * Check if username and email exists in the drupal db
121 *
122 * @param array $params
123 * Array of name and mail values.
124 * @param array $errors
125 * Array of errors.
126 * @param string $emailName
127 * Field label for the 'email'.
128 *
129 * @return void
130 */
131 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
132 $config = CRM_Core_Config::singleton();
133
134 $dao = new CRM_Core_DAO();
135 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
136 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
137 $errors = form_get_errors();
138 if ($errors) {
139 // unset drupal messages to avoid twice display of errors
140 unset($_SESSION['messages']);
141 }
142
143 if (!empty($params['name'])) {
144 if ($nameError = user_validate_name($params['name'])) {
145 $errors['cms_name'] = $nameError;
146 }
147 else {
148 $uid = db_query(
149 "SELECT uid FROM {users} WHERE name = :name",
150 array(':name' => $params['name'])
151 )->fetchField();
152 if ((bool) $uid) {
153 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
154 }
155 }
156 }
157
158 if (!empty($params['mail'])) {
159 if ($emailError = user_validate_mail($params['mail'])) {
160 $errors[$emailName] = $emailError;
161 }
162 else {
163 $uid = db_query(
164 "SELECT uid FROM {users} WHERE mail = :mail",
165 array(':mail' => $params['mail'])
166 )->fetchField();
167 if ((bool) $uid) {
168 $resetUrl = $config->userFrameworkBaseURL . 'user/password';
169 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
170 array(1 => $params['mail'], 2 => $resetUrl)
171 );
172 }
173 }
174 }
175 }
176
177 /**
178 * Get the drupal destination string. When this is passed in the
179 * URL the user will be directed to it after filling in the drupal form
180 *
181 * @param CRM_Core_Form $form
182 * Form object representing the 'current' form - to which the user will be returned.
183 * @return null|string
184 * destination value for URL
185 */
186 public function getLoginDestination(&$form) {
187 $args = NULL;
188
189 $id = $form->get('id');
190 if ($id) {
191 $args .= "&id=$id";
192 }
193 else {
194 $gid = $form->get('gid');
195 if ($gid) {
196 $args .= "&gid=$gid";
197 }
198 else {
199 // Setup Personal Campaign Page link uses pageId
200 $pageId = $form->get('pageId');
201 if ($pageId) {
202 $component = $form->get('component');
203 $args .= "&pageId=$pageId&component=$component&action=add";
204 }
205 }
206 }
207
208 $destination = NULL;
209 if ($args) {
210 // append destination so user is returned to form they came from after login
211 $destination = CRM_Utils_System::currentPath() . '?reset=1' . $args;
212 }
213 return $destination;
214 }
215
216 /**
217 * Get user login URL for hosting CMS (method declared in each CMS system class)
218 *
219 * @param string $destination
220 * If present, add destination to querystring (works for Drupal only).
221 *
222 * @return string
223 * loginURL for the current CMS
224 * @static
225 */
226 public function getLoginURL($destination = '') {
227 $query = $destination ? array('destination' => $destination) : array();
228 return url('user', array('query' => $query));
229 }
230
231
232 /**
233 * Sets the title of the page
234 *
235 * @param string $title
236 * @param null $pageTitle
237 *
238 * @paqram string $pageTitle
239 *
240 * @return void
241 */
242 public function setTitle($title, $pageTitle = NULL) {
243 if (arg(0) == 'civicrm') {
244 if (!$pageTitle) {
245 $pageTitle = $title;
246 }
247
248 drupal_set_title($pageTitle, PASS_THROUGH);
249 }
250 }
251
252 /**
253 * Append an additional breadcrumb tag to the existing breadcrumb
254 *
255 * @param array $breadCrumbs
256 * @internal param string $title
257 * @internal param string $url
258 *
259 * @return void
260 */
261 public function appendBreadCrumb($breadCrumbs) {
262 $breadCrumb = drupal_get_breadcrumb();
263
264 if (is_array($breadCrumbs)) {
265 foreach ($breadCrumbs as $crumbs) {
266 if (stripos($crumbs['url'], 'id%%')) {
267 $args = array('cid', 'mid');
268 foreach ($args as $a) {
269 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
270 FALSE, NULL, $_GET
271 );
272 if ($val) {
273 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
274 }
275 }
276 }
277 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
278 }
279 }
280 drupal_set_breadcrumb($breadCrumb);
281 }
282
283 /**
284 * Reset an additional breadcrumb tag to the existing breadcrumb
285 *
286 * @return void
287 */
288 public function resetBreadCrumb() {
289 $bc = array();
290 drupal_set_breadcrumb($bc);
291 }
292
293 /**
294 * Append a string to the head of the html file
295 *
296 * @param string $header
297 * The new string to be appended.
298 *
299 * @return void
300 */
301 public function addHTMLHead($header) {
302 static $count = 0;
303 if (!empty($header)) {
304 $key = 'civi_' . ++$count;
305 $data = array(
306 '#type' => 'markup',
307 '#markup' => $header,
308 );
309 drupal_add_html_head($data, $key);
310 }
311 }
312
313 /**
314 * Add a script file
315 *
316 * @param $url : string, absolute path to file
317 * @param string $region
318 * location within the document: 'html-header', 'page-header', 'page-footer'.
319 *
320 * Note: This function is not to be called directly
321 * @see CRM_Core_Region::render()
322 *
323 * @return bool
324 * TRUE if we support this operation in this CMS, FALSE otherwise
325 */
326 public function addScriptUrl($url, $region) {
327 $params = array('group' => JS_LIBRARY, 'weight' => 10);
328 switch ($region) {
329 case 'html-header':
330 case 'page-footer':
331 $params['scope'] = substr($region, 5);
332 break;
333
334 default:
335 return FALSE;
336 }
337 // If the path is within the drupal directory we can use the more efficient 'file' setting
338 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
339 drupal_add_js($url, $params);
340 return TRUE;
341 }
342
343 /**
344 * Add an inline script
345 *
346 * @param $code : string, javascript code
347 * @param string $region
348 * location within the document: 'html-header', 'page-header', 'page-footer'.
349 *
350 * Note: This function is not to be called directly
351 * @see CRM_Core_Region::render()
352 *
353 * @return bool
354 * TRUE if we support this operation in this CMS, FALSE otherwise
355 */
356 public function addScript($code, $region) {
357 $params = array('type' => 'inline', 'group' => JS_LIBRARY, 'weight' => 10);
358 switch ($region) {
359 case 'html-header':
360 case 'page-footer':
361 $params['scope'] = substr($region, 5);
362 break;
363
364 default:
365 return FALSE;
366 }
367 drupal_add_js($code, $params);
368 return TRUE;
369 }
370
371 /**
372 * Add a css file
373 *
374 * @param $url : string, absolute path to file
375 * @param string $region
376 * location within the document: 'html-header', 'page-header', 'page-footer'.
377 *
378 * Note: This function is not to be called directly
379 * @see CRM_Core_Region::render()
380 *
381 * @return bool
382 * TRUE if we support this operation in this CMS, FALSE otherwise
383 */
384 public function addStyleUrl($url, $region) {
385 if ($region != 'html-header') {
386 return FALSE;
387 }
388 $params = array();
389 // If the path is within the drupal directory we can use the more efficient 'file' setting
390 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
391 drupal_add_css($url, $params);
392 return TRUE;
393 }
394
395 /**
396 * Add an inline style
397 *
398 * @param $code : string, css code
399 * @param string $region
400 * location within the document: 'html-header', 'page-header', 'page-footer'.
401 *
402 * Note: This function is not to be called directly
403 * @see CRM_Core_Region::render()
404 *
405 * @return bool
406 * TRUE if we support this operation in this CMS, FALSE otherwise
407 */
408 public function addStyle($code, $region) {
409 if ($region != 'html-header') {
410 return FALSE;
411 }
412 $params = array('type' => 'inline');
413 drupal_add_css($code, $params);
414 return TRUE;
415 }
416
417 /**
418 * Rewrite various system urls to https
419 *
420 * @param null
421 *
422 * @return void
423 */
424 public function mapConfigToSSL() {
425 global $base_url;
426 $base_url = str_replace('http://', 'https://', $base_url);
427 }
428
429 /**
430 * Figure out the post url for the form
431 *
432 * @param mix $action
433 * The default action if one is pre-specified.
434 *
435 * @return string
436 * the url to post the form
437 */
438 public function postURL($action) {
439 if (!empty($action)) {
440 return $action;
441 }
442
443 return $this->url($_GET['q']);
444 }
445
446
447 /**
448 * Authenticate the user against the drupal db
449 *
450 * @param string $name
451 * The user name.
452 * @param string $password
453 * The password for the above user name.
454 * @param bool $loadCMSBootstrap
455 * Load cms bootstrap?.
456 * @param NULL|string $realPath filename of script
457 *
458 * @return mixed
459 * 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 * @param string $username
538 *
539 * @return bool
540 */
541 public function loadUser($username) {
542 global $user;
543
544 $user = user_load_by_name($username);
545
546 if (empty($user->uid)) {
547 return FALSE;
548 }
549
550 $uid = $user->uid;
551 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
552
553 // lets store contact id and user id in session
554 $session = CRM_Core_Session::singleton();
555 $session->set('ufID', $uid);
556 $session->set('userID', $contact_id);
557 return TRUE;
558 }
559
560 /**
561 * Perform any post login activities required by the UF -
562 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
563 * calls hook_user op 'login' and generates a new session.
564 *
565 * @param array params
566 *
567 * FIXME: Document values accepted/required by $params
568 */
569 public function userLoginFinalize($params = array()) {
570 user_login_finalize($params);
571 }
572
573 /**
574 * Determine the native ID of the CMS user
575 *
576 * @param string $username
577 * @return int|NULL
578 */
579 public function getUfId($username) {
580 $user = user_load_by_name($username);
581 if (empty($user->uid)) {
582 return NULL;
583 }
584 return $user->uid;
585 }
586
587 /**
588 * Set a message in the UF to display to a user
589 *
590 * @param string $message
591 * The message to set.
592 */
593 public function setMessage($message) {
594 drupal_set_message($message);
595 }
596
597 /**
598 * @return mixed
599 */
600 public function logout() {
601 module_load_include('inc', 'user', 'user.pages');
602 return user_logout();
603 }
604
605 public function updateCategories() {
606 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
607 // CRM-3600
608 cache_clear_all();
609 menu_rebuild();
610 }
611
612 /**
613 * Get the default location for CiviCRM blocks
614 *
615 * @return string
616 */
617 public function getDefaultBlockLocation() {
618 return 'sidebar_first';
619 }
620
621 /**
622 * Get the locale set in the hosting CMS
623 *
624 * @return string
625 * with the locale or null for none
626 */
627 public function getUFLocale() {
628 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
629 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
630 // sometimes for CLI based on order called, this might not be set and/or empty
631 global $language;
632
633 if (empty($language)) {
634 return NULL;
635 }
636
637 if ($language->language == 'zh-hans') {
638 return 'zh_CN';
639 }
640
641 if ($language->language == 'zh-hant') {
642 return 'zh_TW';
643 }
644
645 if (preg_match('/^.._..$/', $language->language)) {
646 return $language->language;
647 }
648
649 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
650 }
651
652 /**
653 * @return string
654 */
655 public function getVersion() {
656 return defined('VERSION') ? VERSION : 'Unknown';
657 }
658
659 /**
660 * Load drupal bootstrap
661 *
662 * @param array $params
663 * Either uid, or name & pass.
664 * @param bool $loadUser
665 * Boolean Require CMS user load.
666 * @param bool $throwError
667 * If true, print error on failure and exit.
668 * @param bool|string $realPath path to script
669 *
670 * @return bool
671 */
672 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
673 //take the cms root path.
674 $cmsPath = $this->cmsRootPath($realPath);
675
676 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
677 if ($throwError) {
678 echo '<br />Sorry, could not locate bootstrap.inc\n';
679 exit();
680 }
681 return FALSE;
682 }
683 // load drupal bootstrap
684 chdir($cmsPath);
685 define('DRUPAL_ROOT', $cmsPath);
686
687 // For drupal multi-site CRM-11313
688 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
689 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
690 if (!empty($matches[1])) {
691 $_SERVER['HTTP_HOST'] = $matches[1];
692 }
693 }
694 require_once 'includes/bootstrap.inc';
695 // @ to suppress notices eg 'DRUPALFOO already defined'.
696 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
697
698 // explicitly setting error reporting, since we cannot handle drupal related notices
699 error_reporting(1);
700 if (!function_exists('module_exists') || !module_exists('civicrm')) {
701 if ($throwError) {
702 echo '<br />Sorry, could not load drupal bootstrap.';
703 exit();
704 }
705 return FALSE;
706 }
707
708 // seems like we've bootstrapped drupal
709 $config = CRM_Core_Config::singleton();
710
711 // lets also fix the clean url setting
712 // CRM-6948
713 $config->cleanURL = (int) variable_get('clean_url', '0');
714
715 // we need to call the config hook again, since we now know
716 // all the modules that are listening on it, does not apply
717 // to J! and WP as yet
718 // CRM-8655
719 CRM_Utils_Hook::config($config);
720
721 if (!$loadUser) {
722 return TRUE;
723 }
724
725 $uid = CRM_Utils_Array::value('uid', $params);
726 if (!$uid) {
727 //load user, we need to check drupal permissions.
728 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
729 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
730
731 if ($name) {
732 $uid = user_authenticate($name, $pass);
733 if (!$uid) {
734 if ($throwError) {
735 echo '<br />Sorry, unrecognized username or password.';
736 exit();
737 }
738 return FALSE;
739 }
740 }
741 }
742
743 if ($uid) {
744 $account = user_load($uid);
745 if ($account && $account->uid) {
746 global $user;
747 $user = $account;
748 return TRUE;
749 }
750 }
751
752 if ($throwError) {
753 echo '<br />Sorry, can not load CMS user account.';
754 exit();
755 }
756
757 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
758 // which means that define(CIVICRM_CLEANURL) was correctly set.
759 // So we correct it
760 $config = CRM_Core_Config::singleton();
761 $config->cleanURL = (int) variable_get('clean_url', '0');
762
763 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
764 CRM_Utils_Hook::config($config);
765
766 return FALSE;
767 }
768
769 /**
770 */
771 public 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 uppermost 'includes' dir, which would
800 // work for multisite installation.
801 do {
802 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
803 $cmsIncludePath = "$cmsRoot/includes";
804 // Stop if we find bootstrap.
805 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
806 $valid = TRUE;
807 break;
808 }
809 //remove one directory level.
810 array_pop($pathVars);
811 } while (count($pathVars));
812
813 return ($valid) ? $cmsRoot : NULL;
814 }
815
816 /**
817 * Check is user logged in.
818 *
819 * @return boolean
820 */
821 public function isUserLoggedIn() {
822 $isloggedIn = FALSE;
823 if (function_exists('user_is_logged_in')) {
824 $isloggedIn = user_is_logged_in();
825 }
826
827 return $isloggedIn;
828 }
829
830 /**
831 * Get currently logged in user uf id.
832 *
833 * @return int
834 * $userID logged in user uf id.
835 */
836 public function getLoggedInUfID() {
837 $ufID = NULL;
838 if (function_exists('user_is_logged_in') &&
839 user_is_logged_in() &&
840 function_exists('user_uid_optional_to_arg')
841 ) {
842 $ufID = user_uid_optional_to_arg(array());
843 }
844
845 return $ufID;
846 }
847
848 /**
849 * Format the url as per language Negotiation.
850 *
851 * @param string $url
852 *
853 * @param bool $addLanguagePart
854 * @param bool $removeLanguagePart
855 *
856 * @return string
857 * , 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 string $oldPerm
927 * @param array $newPerms
928 * Array, strings.
929 *
930 * @return void
931 */
932 public function replacePermission($oldPerm, $newPerms) {
933 $roles = user_roles(FALSE, $oldPerm);
934 if (!empty($roles)) {
935 foreach (array_keys($roles) as $rid) {
936 user_role_revoke_permissions($rid, array($oldPerm));
937 user_role_grant_permissions($rid, $newPerms);
938 }
939 }
940 }
941
942 /**
943 * Get a list of all installed modules, including enabled and disabled ones
944 *
945 * @return array
946 * 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 }
995 else {
996 // Works for the OG 7.x-1.x branch
997 og_ungroup($ogID, 'user', user_load($drupalID));
998 }
999 }
1000
1001 /**
1002 * Over-ridable function to get timezone as a string eg.
1003 * @return string
1004 * Timezone e.g. 'America/Los_Angeles'
1005 */
1006 public function getTimeZoneString() {
1007 global $user;
1008 if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
1009 $timezone = $user->timezone;
1010 }
1011 else {
1012 $timezone = variable_get('date_default_timezone', NULL);
1013 }
1014 if (!$timezone) {
1015 $timezone = parent::getTimeZoneString();
1016 }
1017 return $timezone;
1018 }
1019
1020 /**
1021 * Reset any system caches that may be required for proper CiviCRM
1022 * integration.
1023 */
1024 public function flush() {
1025 drupal_flush_all_caches();
1026 }
1027 }