Merge pull request #17780 from totten/master-sync-into
[civicrm-core.git] / CRM / Utils / System / Drupal.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
19 * Drupal specific stuff goes here
20 */
9977c6f5 21class CRM_Utils_System_Drupal extends CRM_Utils_System_DrupalBase {
6a488035
TO
22
23 /**
17f443df 24 * @inheritDoc
6a488035 25 */
00be9182 26 public function createUser(&$params, $mail) {
88b91745 27 $form_state = form_state_defaults();
d0ffa3e4 28
be2fb01f 29 $form_state['input'] = [
6a488035
TO
30 'name' => $params['cms_name'],
31 'mail' => $params[$mail],
32 'op' => 'Create new account',
be2fb01f 33 ];
6a488035
TO
34
35 $admin = user_access('administer users');
36 if (!variable_get('user_email_verification', TRUE) || $admin) {
be2fb01f 37 $form_state['input']['pass'] = ['pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']];
6a488035
TO
38 }
39
9b873358 40 if (!empty($params['notify'])) {
6a488035
TO
41 $form_state['input']['notify'] = $params['notify'];
42 }
43
44 $form_state['rebuild'] = FALSE;
45 $form_state['programmed'] = TRUE;
805b0f6e 46 $form_state['complete form'] = FALSE;
6a488035 47 $form_state['method'] = 'post';
be2fb01f 48 $form_state['build_info']['args'] = [];
41d551ad 49 /*
e70a7fc0
TO
50 * if we want to submit this form more than once in a process (e.g. create more than one user)
51 * we must force it to validate each time for this form. Otherwise it will not validate
52 * subsequent submissions and the manner in which the password is passed in will be invalid
53 */
41d551ad 54 $form_state['must_validate'] = TRUE;
6a488035
TO
55 $config = CRM_Core_Config::singleton();
56
57 // we also need to redirect b
58 $config->inCiviCRM = TRUE;
59
60 $form = drupal_retrieve_form('user_register_form', $form_state);
61 $form_state['process_input'] = 1;
62 $form_state['submitted'] = 1;
be2fb01f 63 $form['#array_parents'] = [];
805b0f6e 64 $form['#tree'] = FALSE;
6a488035
TO
65 drupal_process_form('user_register_form', $form, $form_state);
66
67 $config->inCiviCRM = FALSE;
68
69 if (form_get_errors()) {
70 return FALSE;
71 }
a5ecff8d 72 return $form_state['user']->uid;
6a488035
TO
73 }
74
8f939417
RO
75 /**
76 * Appends a Drupal 7 Javascript file when the CRM Menubar Javascript file has
77 * been included. The file is added before the menu bar so we can properly listen
78 * for the menu bar ready event.
79 */
80 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent $event) {
ab77d9df 81 $menuBarFileIndex = array_search('js/crm.menubar.js', $event->list);
8f939417 82
ab77d9df
CW
83 if ($menuBarFileIndex !== FALSE) {
84 array_splice($event->list, $menuBarFileIndex, 0, ['js/crm.drupal7.js']);
8f939417 85 }
8f939417
RO
86 }
87
bb3a214a 88 /**
17f443df 89 * @inheritDoc
bb3a214a 90 */
00be9182 91 public function updateCMSName($ufID, $ufName) {
6a488035
TO
92 // CRM-5555
93 if (function_exists('user_load')) {
94 $user = user_load($ufID);
95 if ($user->mail != $ufName) {
be2fb01f 96 user_save($user, ['mail' => $ufName]);
6a488035
TO
97 $user = user_load($ufID);
98 }
99 }
100 }
101
102 /**
fe482240 103 * Check if username and email exists in the drupal db.
6a488035 104 *
77855840
TO
105 * @param array $params
106 * Array of name and mail values.
107 * @param array $errors
108 * Array of errors.
109 * @param string $emailName
110 * Field label for the 'email'.
6a488035 111 */
00be9182 112 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
6a488035
TO
113 $config = CRM_Core_Config::singleton();
114
353ffa53
TO
115 $dao = new CRM_Core_DAO();
116 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
117 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
6a488035
TO
118 $errors = form_get_errors();
119 if ($errors) {
120 // unset drupal messages to avoid twice display of errors
121 unset($_SESSION['messages']);
122 }
123
a7488080 124 if (!empty($params['name'])) {
6a488035
TO
125 if ($nameError = user_validate_name($params['name'])) {
126 $errors['cms_name'] = $nameError;
127 }
128 else {
129 $uid = db_query(
130 "SELECT uid FROM {users} WHERE name = :name",
be2fb01f 131 [':name' => $params['name']]
6a488035
TO
132 )->fetchField();
133 if ((bool) $uid) {
be2fb01f 134 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
6a488035
TO
135 }
136 }
137 }
138
a7488080 139 if (!empty($params['mail'])) {
6a488035
TO
140 if ($emailError = user_validate_mail($params['mail'])) {
141 $errors[$emailName] = $emailError;
142 }
143 else {
144 $uid = db_query(
145 "SELECT uid FROM {users} WHERE mail = :mail",
be2fb01f 146 [':mail' => $params['mail']]
6a488035
TO
147 )->fetchField();
148 if ((bool) $uid) {
aaba8ae5 149 $resetUrl = url('user/password');
db18d815 150 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
be2fb01f 151 [1 => $params['mail'], 2 => $resetUrl]
6a488035
TO
152 );
153 }
154 }
155 }
156 }
157
d424ffde 158 /**
17f443df 159 * @inheritDoc
6a488035
TO
160 */
161 public function getLoginURL($destination = '') {
be2fb01f 162 $query = $destination ? ['destination' => $destination] : NULL;
cd2e7151 163 return CRM_Utils_System::url('user', $query, TRUE);
6a488035
TO
164 }
165
6a488035 166 /**
17f443df 167 * @inheritDoc
6a488035 168 */
00be9182 169 public function setTitle($title, $pageTitle = NULL) {
6a488035
TO
170 if (arg(0) == 'civicrm') {
171 if (!$pageTitle) {
172 $pageTitle = $title;
173 }
174
175 drupal_set_title($pageTitle, PASS_THROUGH);
176 }
177 }
178
179 /**
17f443df 180 * @inheritDoc
6a488035 181 */
00be9182 182 public function appendBreadCrumb($breadCrumbs) {
6a488035
TO
183 $breadCrumb = drupal_get_breadcrumb();
184
185 if (is_array($breadCrumbs)) {
186 foreach ($breadCrumbs as $crumbs) {
187 if (stripos($crumbs['url'], 'id%%')) {
be2fb01f 188 $args = ['cid', 'mid'];
6a488035
TO
189 foreach ($args as $a) {
190 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
191 FALSE, NULL, $_GET
192 );
193 if ($val) {
194 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
195 }
196 }
197 }
198 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
199 }
200 }
201 drupal_set_breadcrumb($breadCrumb);
202 }
203
204 /**
17f443df 205 * @inheritDoc
6a488035 206 */
00be9182 207 public function resetBreadCrumb() {
be2fb01f 208 $bc = [];
6a488035
TO
209 drupal_set_breadcrumb($bc);
210 }
211
212 /**
17f443df 213 * @inheritDoc
6a488035 214 */
00be9182 215 public function addHTMLHead($header) {
6a488035
TO
216 static $count = 0;
217 if (!empty($header)) {
218 $key = 'civi_' . ++$count;
be2fb01f 219 $data = [
6a488035
TO
220 '#type' => 'markup',
221 '#markup' => $header,
be2fb01f 222 ];
6a488035
TO
223 drupal_add_html_head($data, $key);
224 }
225 }
226
227 /**
17f443df 228 * @inheritDoc
6a488035
TO
229 */
230 public function addScriptUrl($url, $region) {
be2fb01f 231 $params = ['group' => JS_LIBRARY, 'weight' => 10];
6a488035
TO
232 switch ($region) {
233 case 'html-header':
234 case 'page-footer':
235 $params['scope'] = substr($region, 5);
236 break;
e7292422 237
6a488035
TO
238 default:
239 return FALSE;
240 }
241 // If the path is within the drupal directory we can use the more efficient 'file' setting
42e1a97c 242 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
6a488035
TO
243 drupal_add_js($url, $params);
244 return TRUE;
245 }
246
247 /**
17f443df 248 * @inheritDoc
6a488035
TO
249 */
250 public function addScript($code, $region) {
be2fb01f 251 $params = ['type' => 'inline', 'group' => JS_LIBRARY, 'weight' => 10];
6a488035
TO
252 switch ($region) {
253 case 'html-header':
254 case 'page-footer':
255 $params['scope'] = substr($region, 5);
256 break;
e7292422 257
6a488035
TO
258 default:
259 return FALSE;
260 }
261 drupal_add_js($code, $params);
262 return TRUE;
263 }
264
265 /**
17f443df 266 * @inheritDoc
6a488035
TO
267 */
268 public function addStyleUrl($url, $region) {
269 if ($region != 'html-header') {
270 return FALSE;
271 }
be2fb01f 272 $params = [];
6a488035 273 // If the path is within the drupal directory we can use the more efficient 'file' setting
42e1a97c 274 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
6a488035
TO
275 drupal_add_css($url, $params);
276 return TRUE;
277 }
278
279 /**
17f443df 280 * @inheritDoc
6a488035
TO
281 */
282 public function addStyle($code, $region) {
283 if ($region != 'html-header') {
284 return FALSE;
285 }
be2fb01f 286 $params = ['type' => 'inline'];
6a488035
TO
287 drupal_add_css($code, $params);
288 return TRUE;
289 }
290
6a488035 291 /**
17f443df 292 * @inheritDoc
6a488035 293 */
00be9182 294 public function mapConfigToSSL() {
6a488035
TO
295 global $base_url;
296 $base_url = str_replace('http://', 'https://', $base_url);
297 }
298
f2ac86d1 299 /**
300 * Get the name of the users table.
301 *
302 * @return string
303 */
348754d5
TO
304 protected function getUsersTableName() {
305 $userFrameworkUsersTableName = Civi::settings()->get('userFrameworkUsersTableName');
306 if (empty($userFrameworkUsersTableName)) {
307 $userFrameworkUsersTableName = 'users';
308 }
309 return $userFrameworkUsersTableName;
310 }
311
6a488035 312 /**
17f443df 313 * @inheritDoc
6a488035 314 */
17f443df 315 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
6a488035
TO
316 require_once 'DB.php';
317
318 $config = CRM_Core_Config::singleton();
319
320 $dbDrupal = DB::connect($config->userFrameworkDSN);
321 if (DB::isError($dbDrupal)) {
309310bf 322 throw new CRM_Core_Exception("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
6a488035
TO
323 }
324
325 $account = $userUid = $userMail = NULL;
326 if ($loadCMSBootstrap) {
be2fb01f 327 $bootStrapParams = [];
6a488035 328 if ($name && $password) {
be2fb01f 329 $bootStrapParams = [
6a488035
TO
330 'name' => $name,
331 'pass' => $password,
be2fb01f 332 ];
6a488035
TO
333 }
334 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
335
336 global $user;
337 if ($user) {
338 $userUid = $user->uid;
339 $userMail = $user->mail;
340 }
341 }
342 else {
343 // CRM-8638
344 // SOAP cannot load drupal bootstrap and hence we do it the old way
345 // Contact CiviSMTP folks if we run into issues with this :)
346 $cmsPath = $config->userSystem->cmsRootPath($realPath);
347
e7292422
TO
348 require_once "$cmsPath/includes/bootstrap.inc";
349 require_once "$cmsPath/includes/password.inc";
6a488035
TO
350
351 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
353ffa53 352 $name = $dbDrupal->escapeSimple($strtolower($name));
348754d5 353 $userFrameworkUsersTableName = $this->getUsersTableName();
b27d1855 354
355 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
353ffa53 356 $sql = "
6a488035 357SELECT u.*
348754d5 358FROM {$userFrameworkUsersTableName} u
6a488035
TO
359WHERE LOWER(u.name) = '$name'
360AND u.status = 1
361";
362
363 $query = $dbDrupal->query($sql);
364 $row = $query->fetchRow(DB_FETCHMODE_ASSOC);
365
366 if ($row) {
367 $fakeDrupalAccount = drupal_anonymous_user();
368 $fakeDrupalAccount->name = $name;
369 $fakeDrupalAccount->pass = $row['pass'];
370 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
371 if ($passwordCheck) {
372 $userUid = $row['uid'];
373 $userMail = $row['mail'];
374 }
375 }
376 }
377
378 if ($userUid && $userMail) {
379 CRM_Core_BAO_UFMatch::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
380 $contactID = CRM_Core_BAO_UFMatch::getContactId($userUid);
381 if (!$contactID) {
382 return FALSE;
383 }
be2fb01f 384 return [$contactID, $userUid, mt_rand()];
6a488035
TO
385 }
386 return FALSE;
387 }
388
bb3a214a 389 /**
17f443df 390 * @inheritDoc
bb3a214a 391 */
00be9182 392 public function loadUser($username) {
6a488035
TO
393 global $user;
394
395 $user = user_load_by_name($username);
396
397 if (empty($user->uid)) {
398 return FALSE;
399 }
400
401 $uid = $user->uid;
402 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
403
404 // lets store contact id and user id in session
405 $session = CRM_Core_Session::singleton();
406 $session->set('ufID', $uid);
407 $session->set('userID', $contact_id);
408 return TRUE;
409 }
410
82d9c21e 411 /**
53980972 412 * Perform any post login activities required by the UF -
413 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
414 * calls hook_user op 'login' and generates a new session.
e43cc689 415 *
c301f76e 416 * @param array $params
95d68223
TO
417 *
418 * FIXME: Document values accepted/required by $params
53980972 419 */
be2fb01f 420 public function userLoginFinalize($params = []) {
53980972 421 user_login_finalize($params);
82d9c21e 422 }
423
46b6363c 424 /**
fe482240 425 * Determine the native ID of the CMS user.
46b6363c 426 *
100fef9d 427 * @param string $username
e97c66ff 428 * @return int|null
46b6363c 429 */
00be9182 430 public function getUfId($username) {
46b6363c
TO
431 $user = user_load_by_name($username);
432 if (empty($user->uid)) {
433 return NULL;
434 }
435 return $user->uid;
436 }
437
6a488035 438 /**
17f443df 439 * @inheritDoc
bb3a214a 440 */
00be9182 441 public function logout() {
6a488035
TO
442 module_load_include('inc', 'user', 'user.pages');
443 return user_logout();
444 }
445
6a488035 446 /**
fe482240 447 * Get the default location for CiviCRM blocks.
6a488035
TO
448 *
449 * @return string
450 */
00be9182 451 public function getDefaultBlockLocation() {
6a488035
TO
452 return 'sidebar_first';
453 }
454
6a488035 455 /**
fe482240 456 * Load drupal bootstrap.
6a488035 457 *
77855840
TO
458 * @param array $params
459 * Either uid, or name & pass.
460 * @param bool $loadUser
461 * Boolean Require CMS user load.
462 * @param bool $throwError
463 * If true, print error on failure and exit.
464 * @param bool|string $realPath path to script
f4aaa82a
EM
465 *
466 * @return bool
6a488035 467 */
be2fb01f 468 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
6a488035
TO
469 //take the cms root path.
470 $cmsPath = $this->cmsRootPath($realPath);
471
472 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
473 if ($throwError) {
de1a27d0 474 throw new Exception('Sorry, could not locate bootstrap.inc');
6a488035
TO
475 }
476 return FALSE;
477 }
478 // load drupal bootstrap
479 chdir($cmsPath);
480 define('DRUPAL_ROOT', $cmsPath);
481
482 // For drupal multi-site CRM-11313
483 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
484 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
485 if (!empty($matches[1])) {
486 $_SERVER['HTTP_HOST'] = $matches[1];
487 }
488 }
489 require_once 'includes/bootstrap.inc';
38507482
CB
490 // @ to suppress notices eg 'DRUPALFOO already defined'.
491 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
6a488035
TO
492
493 // explicitly setting error reporting, since we cannot handle drupal related notices
3ccadca3
ES
494 // @todo 1 = E_ERROR, but more to the point setting error reporting deep in code
495 // causes grief with debugging scripts
6a488035 496 error_reporting(1);
de1a27d0 497 if (!function_exists('module_exists')) {
6a488035 498 if ($throwError) {
de1a27d0
ES
499 throw new Exception('Sorry, could not load drupal bootstrap.');
500 }
501 return FALSE;
502 }
503 if (!module_exists('civicrm')) {
504 if ($throwError) {
505 throw new Exception('Sorry, drupal cannot find CiviCRM');
6a488035
TO
506 }
507 return FALSE;
508 }
509
510 // seems like we've bootstrapped drupal
511 $config = CRM_Core_Config::singleton();
512
6a488035
TO
513 // lets also fix the clean url setting
514 // CRM-6948
515 $config->cleanURL = (int) variable_get('clean_url', '0');
516
517 // we need to call the config hook again, since we now know
518 // all the modules that are listening on it, does not apply
519 // to J! and WP as yet
520 // CRM-8655
521 CRM_Utils_Hook::config($config);
522
523 if (!$loadUser) {
524 return TRUE;
525 }
526
9c1bc317 527 $uid = $params['uid'] ?? NULL;
6a488035
TO
528 if (!$uid) {
529 //load user, we need to check drupal permissions.
530 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
531 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
532
533 if ($name) {
534 $uid = user_authenticate($name, $pass);
535 if (!$uid) {
536 if ($throwError) {
de1a27d0 537 throw new Exception('Sorry, unrecognized username or password.');
6a488035
TO
538 }
539 return FALSE;
540 }
541 }
542 }
543
544 if ($uid) {
545 $account = user_load($uid);
546 if ($account && $account->uid) {
547 global $user;
548 $user = $account;
549 return TRUE;
550 }
551 }
552
553 if ($throwError) {
de1a27d0 554 throw new Exception('Sorry, can not load CMS user account.');
6a488035
TO
555 }
556
0af0e4c9
DL
557 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
558 // which means that define(CIVICRM_CLEANURL) was correctly set.
6a488035
TO
559 // So we correct it
560 $config = CRM_Core_Config::singleton();
e7292422 561 $config->cleanURL = (int) variable_get('clean_url', '0');
6a488035
TO
562
563 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
564 CRM_Utils_Hook::config($config);
565
566 return FALSE;
567 }
568
a5ecff8d 569 /**
ea3ddccf 570 * Get CMS root path.
571 *
572 * @param string $scriptFilename
573 *
574 * @return null|string
a5ecff8d 575 */
00be9182 576 public function cmsRootPath($scriptFilename = NULL) {
6a488035
TO
577 $cmsRoot = $valid = NULL;
578
579 if (!is_null($scriptFilename)) {
580 $path = $scriptFilename;
581 }
582 else {
583 $path = $_SERVER['SCRIPT_FILENAME'];
584 }
585
586 if (function_exists('drush_get_context')) {
587 // drush anyway takes care of multisite install etc
588 return drush_get_context('DRUSH_DRUPAL_ROOT');
589 }
d33e2f7d 590
591 global $civicrm_paths;
592 if (!empty($civicrm_paths['cms.root']['path'])) {
593 return $civicrm_paths['cms.root']['path'];
594 }
595
6a488035
TO
596 // CRM-7582
597 $pathVars = explode('/',
598 str_replace('//', '/',
599 str_replace('\\', '/', $path)
600 )
601 );
602
603 //lets store first var,
604 //need to get back for windows.
605 $firstVar = array_shift($pathVars);
606
e0e68bf4 607 // Remove the script name to remove an necessary iteration of the loop.
6a488035
TO
608 array_pop($pathVars);
609
948d11bf
CB
610 // CRM-7429 -- do check for uppermost 'includes' dir, which would
611 // work for multisite installation.
6a488035
TO
612 do {
613 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
614 $cmsIncludePath = "$cmsRoot/includes";
948d11bf 615 // Stop if we find bootstrap.
f81c7606 616 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
6a488035
TO
617 $valid = TRUE;
618 break;
619 }
620 //remove one directory level.
621 array_pop($pathVars);
622 } while (count($pathVars));
623
624 return ($valid) ? $cmsRoot : NULL;
625 }
626
627 /**
17f443df 628 * @inheritDoc
6a488035
TO
629 */
630 public function isUserLoggedIn() {
631 $isloggedIn = FALSE;
632 if (function_exists('user_is_logged_in')) {
633 $isloggedIn = user_is_logged_in();
634 }
635
636 return $isloggedIn;
637 }
638
639 /**
17f443df 640 * @inheritDoc
6a488035
TO
641 */
642 public function getLoggedInUfID() {
643 $ufID = NULL;
644 if (function_exists('user_is_logged_in') &&
645 user_is_logged_in() &&
646 function_exists('user_uid_optional_to_arg')
647 ) {
be2fb01f 648 $ufID = user_uid_optional_to_arg([]);
6a488035
TO
649 }
650
651 return $ufID;
652 }
653
654 /**
17f443df 655 * @inheritDoc
6a488035 656 */
00be9182 657 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
6a488035
TO
658 if (empty($url)) {
659 return $url;
660 }
661
662 //CRM-7803 -from d7 onward.
663 $config = CRM_Core_Config::singleton();
664 if (function_exists('variable_get') &&
665 module_exists('locale') &&
666 function_exists('language_negotiation_get')
667 ) {
668 global $language;
669
670 //does user configuration allow language
671 //support from the URL (Path prefix or domain)
672 if (language_negotiation_get('language') == 'locale-url') {
673 $urlType = variable_get('locale_language_negotiation_url_part');
674
675 //url prefix
676 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
677 if (isset($language->prefix) && $language->prefix) {
678 if ($addLanguagePart) {
3fe61451 679 $url .= $language->prefix . '/';
6a488035
TO
680 }
681 if ($removeLanguagePart) {
682 $url = str_replace("/{$language->prefix}/", '/', $url);
683 }
684 }
685 }
686 //domain
687 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
688 if (isset($language->domain) && $language->domain) {
689 if ($addLanguagePart) {
b276048c 690 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain);
ea54c1ae 691 // drupal function base_path() adds a "/" to the beginning and end of the returned path
34020e33 692 if (substr($cleanedUrl, -1) == '/') {
ea54c1ae
LS
693 $cleanedUrl = substr($cleanedUrl, 0, -1);
694 }
b276048c 695 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $cleanedUrl . base_path();
6a488035
TO
696 }
697 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
698 $url = str_replace('\\', '/', $url);
699 $parseUrl = parse_url($url);
700
701 //kinda hackish but not sure how to do it right
702 //hope http_build_url() will help at some point.
703 if (is_array($parseUrl) && !empty($parseUrl)) {
353ffa53
TO
704 $urlParts = explode('/', $url);
705 $hostKey = array_search($parseUrl['host'], $urlParts);
706 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
6a488035 707 $urlParts[$hostKey] = $ufUrlParts['host'];
353ffa53 708 $url = implode('/', $urlParts);
6a488035
TO
709 }
710 }
711 }
712 }
713 }
714 }
715
716 return $url;
717 }
718
719 /**
720 * Find any users/roles/security-principals with the given permission
721 * and replace it with one or more permissions.
722 *
5a4f6742
CW
723 * @param string $oldPerm
724 * @param array $newPerms
77855840 725 * Array, strings.
6a488035 726 */
00be9182 727 public function replacePermission($oldPerm, $newPerms) {
6a488035
TO
728 $roles = user_roles(FALSE, $oldPerm);
729 if (!empty($roles)) {
730 foreach (array_keys($roles) as $rid) {
be2fb01f 731 user_role_revoke_permissions($rid, [$oldPerm]);
6a488035
TO
732 user_role_grant_permissions($rid, $newPerms);
733 }
734 }
735 }
736
6a488035 737 /**
fe482240 738 * Wrapper for og_membership creation.
a5ecff8d 739 *
77855840
TO
740 * @param int $ogID
741 * Organic Group ID.
742 * @param int $drupalID
743 * Drupal User ID.
6a488035 744 */
9b873358 745 public function og_membership_create($ogID, $drupalID) {
6a488035 746 if (function_exists('og_entity_query_alter')) {
a5ecff8d
CB
747 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
748 //
749 // @TODO Find more solid way to check - try system_get_info('module', 'og').
750 //
751 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
be2fb01f 752 og_group('node', $ogID, ['entity' => user_load($drupalID)]);
6a488035
TO
753 }
754 else {
755 // Works for the OG 7.x-1.x branch
be2fb01f 756 og_group($ogID, ['entity' => user_load($drupalID)]);
6a488035
TO
757 }
758 }
759
760 /**
fe482240 761 * Wrapper for og_membership deletion.
a5ecff8d 762 *
77855840
TO
763 * @param int $ogID
764 * Organic Group ID.
765 * @param int $drupalID
766 * Drupal User ID.
6a488035 767 */
00be9182 768 public function og_membership_delete($ogID, $drupalID) {
6a488035
TO
769 if (function_exists('og_entity_query_alter')) {
770 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
771 // TODO: Find a more solid way to make this test
772 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
773 og_ungroup('node', $ogID, 'user', user_load($drupalID));
0db6c3e1
TO
774 }
775 else {
6a488035
TO
776 // Works for the OG 7.x-1.x branch
777 og_ungroup($ogID, 'user', user_load($drupalID));
778 }
779 }
d8a4acc0 780
5a604d61 781 /**
17f443df 782 * @inheritDoc
5a604d61 783 */
00be9182 784 public function getTimeZoneString() {
5a604d61 785 global $user;
e41775f6 786 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
787 if (variable_get('configurable_timezones', 1) && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
5a604d61 788 $timezone = $user->timezone;
0db6c3e1
TO
789 }
790 else {
e7292422 791 $timezone = variable_get('date_default_timezone', NULL);
5a604d61 792 }
48ec57ab
TO
793 if (!$timezone) {
794 $timezone = parent::getTimeZoneString();
5a604d61 795 }
48ec57ab 796 return $timezone;
5a604d61 797 }
353ffa53 798
d42a224c
CW
799 /**
800 * @inheritDoc
801 */
802 public function setHttpHeader($name, $value) {
803 drupal_add_http_header($name, $value);
804 }
805
03d5592a
CW
806 /**
807 * @inheritDoc
808 */
809 public function synchronizeUsers() {
810 $config = CRM_Core_Config::singleton();
811 if (PHP_SAPI != 'cli') {
812 set_time_limit(300);
813 }
03d5592a
CW
814 $id = 'uid';
815 $mail = 'mail';
816 $name = 'name';
817
818 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
819
03d5592a
CW
820 $user = new StdClass();
821 $uf = $config->userFramework;
822 $contactCount = 0;
823 $contactCreated = 0;
824 $contactMatching = 0;
2eb3dae2
CW
825 foreach ($result as $row) {
826 $user->$id = $row->$id;
827 $user->$mail = $row->$mail;
828 $user->$name = $row->$name;
03d5592a 829 $contactCount++;
2eb3dae2 830 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
03d5592a
CW
831 $contactCreated++;
832 }
833 else {
834 $contactMatching++;
835 }
03d5592a
CW
836 }
837
be2fb01f 838 return [
03d5592a
CW
839 'contactCount' => $contactCount,
840 'contactMatching' => $contactMatching,
841 'contactCreated' => $contactCreated,
be2fb01f 842 ];
03d5592a
CW
843 }
844
f2e906d7
JP
845 /**
846 * Commit the session before exiting.
847 * Similar to drupal_exit().
848 */
849 public function onCiviExit() {
eb3277f9
JP
850 if (function_exists('module_invoke_all')) {
851 if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
852 module_invoke_all('exit');
853 }
854 drupal_session_commit();
f2e906d7 855 }
f2e906d7
JP
856 }
857
6a488035 858}