Merge pull request #1222 from lcdservices/CRM-13099
[civicrm-core.git] / CRM / Utils / System / Drupal.php
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 */
39 class CRM_Utils_System_Drupal extends CRM_Utils_System_DrupalBase {
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;
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 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
566
567
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 = "
597 SELECT u.*
598 FROM {$config->userFrameworkUsersTableName} u
599 WHERE LOWER(u.name) = '$name'
600 AND 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 * Perform an post login activities required by the UF -
653 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp, calls hook_user op 'login' and generates a new session.
654 * @param array $edit: The array of form values submitted by the user.
655 *
656 function userLoginFinalize($edit = array()){
657 user_login_finalize(&$edit);
658 }
659 */
660
661 /**
662 * Determine the native ID of the CMS user
663 *
664 * @param $username
665 * @return int|NULL
666 */
667 function getUfId($username) {
668 $user = user_load_by_name($username);
669 if (empty($user->uid)) {
670 return NULL;
671 }
672 return $user->uid;
673 }
674
675 /**
676 * Set a message in the UF to display to a user
677 *
678 * @param string $message the message to set
679 *
680 * @access public
681 */
682 function setMessage($message) {
683 drupal_set_message($message);
684 }
685
686 function permissionDenied() {
687 drupal_access_denied();
688 }
689
690 function logout() {
691 module_load_include('inc', 'user', 'user.pages');
692 return user_logout();
693 }
694
695 function updateCategories() {
696 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
697 // CRM-3600
698 cache_clear_all();
699 menu_rebuild();
700 }
701
702 /**
703 * Get the default location for CiviCRM blocks
704 *
705 * @return string
706 */
707 function getDefaultBlockLocation() {
708 return 'sidebar_first';
709 }
710
711 /**
712 * Get the locale set in the hosting CMS
713 *
714 * @return string with the locale or null for none
715 */
716 function getUFLocale() {
717 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
718 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
719 // sometimes for CLI based on order called, this might not be set and/or empty
720 global $language;
721
722 if (empty($language)) {
723 return NULL;
724 }
725
726 if ($language->language == 'zh-hans') {
727 return 'zh_CN';
728 }
729
730 if ($language->language == 'zh-hant') {
731 return 'zh_TW';
732 }
733
734 if (preg_match('/^.._..$/', $language->language)) {
735 return $language->language;
736 }
737
738 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
739 }
740
741 function getVersion() {
742 return defined('VERSION') ? VERSION : 'Unknown';
743 }
744
745 /**
746 * load drupal bootstrap
747 *
748 * @param $params array with uid or name and password
749 * @param $loadUser boolean load cms user?
750 * @param $throwError throw error on failure?
751 */
752
753 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
754 //take the cms root path.
755 $cmsPath = $this->cmsRootPath($realPath);
756
757 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
758 if ($throwError) {
759 echo '<br />Sorry, could not locate bootstrap.inc\n';
760 exit();
761 }
762 return FALSE;
763 }
764 // load drupal bootstrap
765 chdir($cmsPath);
766 define('DRUPAL_ROOT', $cmsPath);
767
768 // For drupal multi-site CRM-11313
769 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
770 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
771 if (!empty($matches[1])) {
772 $_SERVER['HTTP_HOST'] = $matches[1];
773 }
774 }
775 require_once 'includes/bootstrap.inc';
776 drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
777
778 // explicitly setting error reporting, since we cannot handle drupal related notices
779 error_reporting(1);
780 if (!function_exists('module_exists') || !module_exists('civicrm')) {
781 if ($throwError) {
782 echo '<br />Sorry, could not load drupal bootstrap.';
783 exit();
784 }
785 return FALSE;
786 }
787
788 // seems like we've bootstrapped drupal
789 $config = CRM_Core_Config::singleton();
790
791 // lets also fix the clean url setting
792 // CRM-6948
793 $config->cleanURL = (int) variable_get('clean_url', '0');
794
795 // we need to call the config hook again, since we now know
796 // all the modules that are listening on it, does not apply
797 // to J! and WP as yet
798 // CRM-8655
799 CRM_Utils_Hook::config($config);
800
801 if (!$loadUser) {
802 return TRUE;
803 }
804
805 $uid = CRM_Utils_Array::value('uid', $params);
806 if (!$uid) {
807 //load user, we need to check drupal permissions.
808 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
809 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
810
811 if ($name) {
812 $uid = user_authenticate($name, $pass);
813 if (!$uid) {
814 if ($throwError) {
815 echo '<br />Sorry, unrecognized username or password.';
816 exit();
817 }
818 return FALSE;
819 }
820 }
821 }
822
823 if ($uid) {
824 $account = user_load($uid);
825 if ($account && $account->uid) {
826 global $user;
827 $user = $account;
828 return TRUE;
829 }
830 }
831
832 if ($throwError) {
833 echo '<br />Sorry, can not load CMS user account.';
834 exit();
835 }
836
837 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
838 // which means that define(CIVICRM_CLEANURL) was correctly set.
839 // So we correct it
840 $config = CRM_Core_Config::singleton();
841 $config->cleanURL = (int)variable_get('clean_url', '0');
842
843 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
844 CRM_Utils_Hook::config($config);
845
846 return FALSE;
847 }
848
849 function cmsRootPath($scriptFilename = NULL) {
850
851 $cmsRoot = $valid = NULL;
852
853 if (!is_null($scriptFilename)) {
854 $path = $scriptFilename;
855 }
856 else {
857 $path = $_SERVER['SCRIPT_FILENAME'];
858 }
859
860 if (function_exists('drush_get_context')) {
861 // drush anyway takes care of multisite install etc
862 return drush_get_context('DRUSH_DRUPAL_ROOT');
863 }
864 // CRM-7582
865 $pathVars = explode('/',
866 str_replace('//', '/',
867 str_replace('\\', '/', $path)
868 )
869 );
870
871 //lets store first var,
872 //need to get back for windows.
873 $firstVar = array_shift($pathVars);
874
875 //lets remove sript name to reduce one iteration.
876 array_pop($pathVars);
877
878 //CRM-7429 --do check for upper most 'includes' dir,
879 //which would effectually work for multisite installation.
880 do {
881 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
882 $cmsIncludePath = "$cmsRoot/includes";
883 //stop as we found bootstrap.
884 if (@opendir($cmsIncludePath) &&
885 file_exists("$cmsIncludePath/bootstrap.inc")
886 ) {
887 $valid = TRUE;
888 break;
889 }
890 //remove one directory level.
891 array_pop($pathVars);
892 } while (count($pathVars));
893
894 return ($valid) ? $cmsRoot : NULL;
895 }
896
897 /**
898 * check is user logged in.
899 *
900 * @return boolean true/false.
901 */
902 public function isUserLoggedIn() {
903 $isloggedIn = FALSE;
904 if (function_exists('user_is_logged_in')) {
905 $isloggedIn = user_is_logged_in();
906 }
907
908 return $isloggedIn;
909 }
910
911 /**
912 * Get currently logged in user uf id.
913 *
914 * @return int $userID logged in user uf id.
915 */
916 public function getLoggedInUfID() {
917 $ufID = NULL;
918 if (function_exists('user_is_logged_in') &&
919 user_is_logged_in() &&
920 function_exists('user_uid_optional_to_arg')
921 ) {
922 $ufID = user_uid_optional_to_arg(array());
923 }
924
925 return $ufID;
926 }
927
928 /**
929 * Format the url as per language Negotiation.
930 *
931 * @param string $url
932 *
933 * @return string $url, formatted url.
934 * @static
935 */
936 function languageNegotiationURL(
937 $url,
938 $addLanguagePart = TRUE,
939 $removeLanguagePart = FALSE
940 ) {
941 if (empty($url)) {
942 return $url;
943 }
944
945 //CRM-7803 -from d7 onward.
946 $config = CRM_Core_Config::singleton();
947 if (function_exists('variable_get') &&
948 module_exists('locale') &&
949 function_exists('language_negotiation_get')
950 ) {
951 global $language;
952
953 //does user configuration allow language
954 //support from the URL (Path prefix or domain)
955 if (language_negotiation_get('language') == 'locale-url') {
956 $urlType = variable_get('locale_language_negotiation_url_part');
957
958 //url prefix
959 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
960 if (isset($language->prefix) && $language->prefix) {
961 if ($addLanguagePart) {
962 $url .= $language->prefix . '/';
963 }
964 if ($removeLanguagePart) {
965 $url = str_replace("/{$language->prefix}/", '/', $url);
966 }
967 }
968 }
969 //domain
970 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
971 if (isset($language->domain) && $language->domain) {
972 if ($addLanguagePart) {
973 $url = CRM_Utils_File::addTrailingSlash($language->domain, '/');
974 }
975 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
976 $url = str_replace('\\', '/', $url);
977 $parseUrl = parse_url($url);
978
979 //kinda hackish but not sure how to do it right
980 //hope http_build_url() will help at some point.
981 if (is_array($parseUrl) && !empty($parseUrl)) {
982 $urlParts = explode('/', $url);
983 $hostKey = array_search($parseUrl['host'], $urlParts);
984 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
985 $urlParts[$hostKey] = $ufUrlParts['host'];
986 $url = implode('/', $urlParts);
987 }
988 }
989 }
990 }
991 }
992 }
993
994 return $url;
995 }
996
997 /**
998 * Find any users/roles/security-principals with the given permission
999 * and replace it with one or more permissions.
1000 *
1001 * @param $oldPerm string
1002 * @param $newPerms array, strings
1003 *
1004 * @return void
1005 */
1006 function replacePermission($oldPerm, $newPerms) {
1007 $roles = user_roles(FALSE, $oldPerm);
1008 if (!empty($roles)) {
1009 foreach (array_keys($roles) as $rid) {
1010 user_role_revoke_permissions($rid, array($oldPerm));
1011 user_role_grant_permissions($rid, $newPerms);
1012 }
1013 }
1014 }
1015
1016 /**
1017 * Get a list of all installed modules, including enabled and disabled ones
1018 *
1019 * @return array CRM_Core_Module
1020 */
1021 function getModules() {
1022 $result = array();
1023 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
1024 foreach ($q as $row) {
1025 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
1026 }
1027 return $result;
1028 }
1029
1030 /**
1031 * Wrapper for og_membership creation
1032 */
1033 function og_membership_create($ogID, $drupalID){
1034 if (function_exists('og_entity_query_alter')) {
1035 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
1036 // TODO: Find a more solid way to make this test
1037 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
1038 og_group('node', $ogID, array('entity' => user_load($drupalID)));
1039 }
1040 else {
1041 // Works for the OG 7.x-1.x branch
1042 og_group($ogID, array('entity' => user_load($drupalID)));
1043 }
1044 }
1045
1046 /**
1047 * Wrapper for og_membership deletion
1048 */
1049 function og_membership_delete($ogID, $drupalID) {
1050 if (function_exists('og_entity_query_alter')) {
1051 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
1052 // TODO: Find a more solid way to make this test
1053 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
1054 og_ungroup('node', $ogID, 'user', user_load($drupalID));
1055 } else {
1056 // Works for the OG 7.x-1.x branch
1057 og_ungroup($ogID, 'user', user_load($drupalID));
1058 }
1059 }
1060
1061 /**
1062 * Reset any system caches that may be required for proper CiviCRM
1063 * integration.
1064 */
1065 function flush() {
1066 drupal_flush_all_caches();
1067 }
1068 }