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