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