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