Merge pull request #18008 from civicrm/5.28
[civicrm-core.git] / CRM / Utils / System / Backdrop.php
CommitLineData
84fce21c
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
84fce21c 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 |
84fce21c
TO
9 +--------------------------------------------------------------------+
10 */
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
84fce21c
TO
16 */
17
18/**
ddd5c06f 19 * Backdrop-specific logic that differs from Drupal.
84fce21c
TO
20 */
21class CRM_Utils_System_Backdrop extends CRM_Utils_System_DrupalBase {
22
23 /**
24 * @inheritDoc
25 */
26 public function createUser(&$params, $mail) {
27 $form_state = form_state_defaults();
28
be2fb01f 29 $form_state['input'] = [
84fce21c
TO
30 'name' => $params['cms_name'],
31 'mail' => $params[$mail],
32 'op' => 'Create new account',
be2fb01f 33 ];
84fce21c
TO
34
35 $admin = user_access('administer users');
ddd5c06f 36 if (!config_get('system.core', 'user_email_verification') || $admin) {
be2fb01f 37 $form_state['input']['pass'] = ['pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']];
84fce21c
TO
38 }
39
40 if (!empty($params['notify'])) {
41 $form_state['input']['notify'] = $params['notify'];
42 }
43
44 $form_state['rebuild'] = FALSE;
45 $form_state['programmed'] = TRUE;
46 $form_state['complete form'] = FALSE;
47 $form_state['method'] = 'post';
be2fb01f 48 $form_state['build_info']['args'] = [];
84fce21c
TO
49 /*
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 */
54 $form_state['must_validate'] = TRUE;
55 $config = CRM_Core_Config::singleton();
56
57 // we also need to redirect b
58 $config->inCiviCRM = TRUE;
59
84da17e3 60 $form = backdrop_retrieve_form('user_register_form', $form_state);
84fce21c
TO
61 $form_state['process_input'] = 1;
62 $form_state['submitted'] = 1;
be2fb01f 63 $form['#array_parents'] = [];
84fce21c 64 $form['#tree'] = FALSE;
84da17e3 65 backdrop_process_form('user_register_form', $form, $form_state);
84fce21c
TO
66
67 $config->inCiviCRM = FALSE;
68
69 if (form_get_errors()) {
70 return FALSE;
71 }
72 return $form_state['user']->uid;
73 }
74
75 /**
76 * @inheritDoc
77 */
ddd5c06f 78 public function updateCMSName($ufID, $email) {
84fce21c
TO
79 // CRM-5555
80 if (function_exists('user_load')) {
81 $user = user_load($ufID);
ddd5c06f
NH
82 if ($user->mail != $email) {
83 $user->mail = $email;
84 $user->save();
84fce21c
TO
85 }
86 }
87 }
88
89 /**
84da17e3 90 * Check if username and email exists in the Backdrop db.
84fce21c
TO
91 *
92 * @param array $params
93 * Array of name and mail values.
94 * @param array $errors
95 * Array of errors.
96 * @param string $emailName
97 * Field label for the 'email'.
98 */
99 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
84fce21c
TO
100 $errors = form_get_errors();
101 if ($errors) {
84da17e3 102 // unset Backdrop messages to avoid twice display of errors
84fce21c
TO
103 unset($_SESSION['messages']);
104 }
105
106 if (!empty($params['name'])) {
107 if ($nameError = user_validate_name($params['name'])) {
108 $errors['cms_name'] = $nameError;
109 }
110 else {
be2fb01f 111 $uid = db_query("SELECT uid FROM {users} WHERE name = :name", [':name' => $params['name']])->fetchField();
84fce21c 112 if ((bool) $uid) {
be2fb01f 113 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
84fce21c
TO
114 }
115 }
116 }
117
118 if (!empty($params['mail'])) {
ddd5c06f 119 if (!valid_email_address($params['mail'])) {
6dabf459 120 $errors[$emailName] = ts('The e-mail address %1 is not valid.', [1 => $params['mail']]);
84fce21c
TO
121 }
122 else {
be2fb01f 123 $uid = db_query("SELECT uid FROM {users} WHERE mail = :mail", [':mail' => $params['mail']])->fetchField();
84fce21c 124 if ((bool) $uid) {
ddd5c06f 125 $resetUrl = url('user/password');
84fce21c 126 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
be2fb01f 127 [1 => $params['mail'], 2 => $resetUrl]
84fce21c
TO
128 );
129 }
130 }
131 }
132 }
133
134 /**
135 * @inheritDoc
136 */
137 public function getLoginURL($destination = '') {
be2fb01f 138 $query = $destination ? ['destination' => $destination] : [];
8f76d5aa 139 return url('user/login', ['query' => $query, 'absolute' => TRUE]);
84fce21c
TO
140 }
141
142 /**
143 * @inheritDoc
144 */
145 public function setTitle($title, $pageTitle = NULL) {
146 if (arg(0) == 'civicrm') {
147 if (!$pageTitle) {
148 $pageTitle = $title;
149 }
150
84da17e3 151 backdrop_set_title($pageTitle, PASS_THROUGH);
84fce21c
TO
152 }
153 }
154
155 /**
156 * @inheritDoc
157 */
158 public function appendBreadCrumb($breadCrumbs) {
84da17e3 159 $breadCrumb = backdrop_get_breadcrumb();
84fce21c
TO
160
161 if (is_array($breadCrumbs)) {
162 foreach ($breadCrumbs as $crumbs) {
163 if (stripos($crumbs['url'], 'id%%')) {
be2fb01f 164 $args = ['cid', 'mid'];
84fce21c
TO
165 foreach ($args as $a) {
166 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
167 FALSE, NULL, $_GET
168 );
169 if ($val) {
170 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
171 }
172 }
173 }
174 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
175 }
176 }
84da17e3 177 backdrop_set_breadcrumb($breadCrumb);
84fce21c
TO
178 }
179
180 /**
181 * @inheritDoc
182 */
183 public function resetBreadCrumb() {
be2fb01f 184 $bc = [];
84da17e3 185 backdrop_set_breadcrumb($bc);
84fce21c
TO
186 }
187
188 /**
189 * @inheritDoc
190 */
191 public function addHTMLHead($header) {
192 static $count = 0;
193 if (!empty($header)) {
194 $key = 'civi_' . ++$count;
be2fb01f 195 $data = [
84fce21c
TO
196 '#type' => 'markup',
197 '#markup' => $header,
be2fb01f 198 ];
84da17e3 199 backdrop_add_html_head($data, $key);
84fce21c
TO
200 }
201 }
202
203 /**
204 * @inheritDoc
205 */
206 public function addScriptUrl($url, $region) {
be2fb01f 207 $params = ['group' => JS_LIBRARY, 'weight' => 10];
84fce21c
TO
208 switch ($region) {
209 case 'html-header':
210 case 'page-footer':
211 $params['scope'] = substr($region, 5);
212 break;
213
214 default:
215 return FALSE;
216 }
84da17e3 217 // If the path is within the Backdrop directory we can use the more efficient 'file' setting
84fce21c 218 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
84da17e3 219 backdrop_add_js($url, $params);
84fce21c
TO
220 return TRUE;
221 }
222
223 /**
224 * @inheritDoc
225 */
226 public function addScript($code, $region) {
be2fb01f 227 $params = ['type' => 'inline', 'group' => JS_LIBRARY, 'weight' => 10];
84fce21c
TO
228 switch ($region) {
229 case 'html-header':
230 case 'page-footer':
231 $params['scope'] = substr($region, 5);
232 break;
233
234 default:
235 return FALSE;
236 }
84da17e3 237 backdrop_add_js($code, $params);
84fce21c
TO
238 return TRUE;
239 }
240
241 /**
242 * @inheritDoc
243 */
244 public function addStyleUrl($url, $region) {
245 if ($region != 'html-header') {
246 return FALSE;
247 }
be2fb01f 248 $params = [];
84da17e3 249 // If the path is within the Backdrop directory we can use the more efficient 'file' setting
84fce21c 250 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
84da17e3 251 backdrop_add_css($url, $params);
84fce21c
TO
252 return TRUE;
253 }
254
255 /**
256 * @inheritDoc
257 */
258 public function addStyle($code, $region) {
259 if ($region != 'html-header') {
260 return FALSE;
261 }
be2fb01f 262 $params = ['type' => 'inline'];
84da17e3 263 backdrop_add_css($code, $params);
84fce21c
TO
264 return TRUE;
265 }
266
267 /**
268 * @inheritDoc
269 */
270 public function mapConfigToSSL() {
271 global $base_url;
272 $base_url = str_replace('http://', 'https://', $base_url);
273 }
274
8246bca4 275 /**
276 * Get the name of the table that stores the user details.
277 *
278 * @return string
279 */
84fce21c
TO
280 protected function getUsersTableName() {
281 $userFrameworkUsersTableName = Civi::settings()->get('userFrameworkUsersTableName');
282 if (empty($userFrameworkUsersTableName)) {
283 $userFrameworkUsersTableName = 'users';
284 }
285 return $userFrameworkUsersTableName;
286 }
287
288 /**
289 * @inheritDoc
290 */
291 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
84fce21c
TO
292 $config = CRM_Core_Config::singleton();
293
ddd5c06f
NH
294 $dbBackdrop = DB::connect($config->userFrameworkDSN);
295 if (DB::isError($dbBackdrop)) {
309310bf 296 throw new CRM_Core_Exception("Cannot connect to Backdrop database via $config->userFrameworkDSN, " . $dbBackdrop->getMessage());
84fce21c
TO
297 }
298
299 $account = $userUid = $userMail = NULL;
300 if ($loadCMSBootstrap) {
be2fb01f 301 $bootStrapParams = [];
84fce21c 302 if ($name && $password) {
be2fb01f 303 $bootStrapParams = [
84fce21c
TO
304 'name' => $name,
305 'pass' => $password,
be2fb01f 306 ];
84fce21c
TO
307 }
308 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
309
310 global $user;
311 if ($user) {
312 $userUid = $user->uid;
313 $userMail = $user->mail;
314 }
315 }
316 else {
317 // CRM-8638
84da17e3 318 // SOAP cannot load Backdrop bootstrap and hence we do it the old way
84fce21c 319 // Contact CiviSMTP folks if we run into issues with this :)
ddd5c06f 320 $cmsPath = $this->cmsRootPath();
1cee22f0 321 if (!defined('BACKDROP_ROOT')) {
322 define(BACKDROP_ROOT, $cmsPath);
323 }
5c6ebf4c
TO
324 require_once "$cmsPath/core/includes/bootstrap.inc";
325 require_once "$cmsPath/core/includes/password.inc";
84fce21c
TO
326
327 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
ddd5c06f 328 $name = $dbBackdrop->escapeSimple($strtolower($name));
84fce21c 329 $userFrameworkUsersTableName = $this->getUsersTableName();
b27d1855 330
331 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
84fce21c
TO
332 $sql = "
333SELECT u.*
334FROM {$userFrameworkUsersTableName} u
335WHERE LOWER(u.name) = '$name'
336AND u.status = 1
337";
338
ddd5c06f 339 $query = $dbBackdrop->query($sql);
84fce21c
TO
340 $row = $query->fetchRow(DB_FETCHMODE_ASSOC);
341
342 if ($row) {
ddd5c06f
NH
343 $fakeAccount = backdrop_anonymous_user();
344 $fakeAccount->name = $name;
345 $fakeAccount->pass = $row['pass'];
346 $passwordCheck = user_check_password($password, $fakeAccount);
84fce21c
TO
347 if ($passwordCheck) {
348 $userUid = $row['uid'];
349 $userMail = $row['mail'];
350 }
351 }
352 }
353
354 if ($userUid && $userMail) {
ddd5c06f 355 CRM_Core_BAO_UFMatch::synchronizeUFMatch($account, $userUid, $userMail, 'Backdrop');
84fce21c
TO
356 $contactID = CRM_Core_BAO_UFMatch::getContactId($userUid);
357 if (!$contactID) {
358 return FALSE;
359 }
be2fb01f 360 return [$contactID, $userUid, mt_rand()];
84fce21c
TO
361 }
362 return FALSE;
363 }
364
365 /**
366 * @inheritDoc
367 */
368 public function loadUser($username) {
369 global $user;
370
371 $user = user_load_by_name($username);
372
373 if (empty($user->uid)) {
374 return FALSE;
375 }
376
377 $uid = $user->uid;
378 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
379
380 // lets store contact id and user id in session
381 $session = CRM_Core_Session::singleton();
382 $session->set('ufID', $uid);
383 $session->set('userID', $contact_id);
384 return TRUE;
385 }
386
387 /**
388 * Perform any post login activities required by the UF -
ddd5c06f
NH
389 * For Backdrop this could mean recording a watchdog message about the new
390 * session, saving the login timestamp, calling hook_user_login(), etc.
84fce21c
TO
391 *
392 * @param array $params
ddd5c06f 393 * The array of form values submitted by the user.
84fce21c 394 */
be2fb01f 395 public function userLoginFinalize($params = []) {
84fce21c
TO
396 user_login_finalize($params);
397 }
398
cfb37063
HD
399 /**
400 * @inheritDoc
401 */
402 public function isUserRegistrationPermitted() {
403 if (config_get('system.core', 'user_register') == 'admin_only') {
404 return FALSE;
405 }
406 return TRUE;
407 }
408
63df6889
HD
409 /**
410 * @inheritDoc
411 */
1a6630be 412 public function isPasswordUserGenerated() {
63df6889
HD
413 if (config_get('system.core', 'user_email_verification') == TRUE) {
414 return FALSE;
415 }
416 return TRUE;
417 }
418
974c6b58
HD
419 /**
420 * @inheritDoc
421 */
422 public function getUFLocale() {
84da17e3 423 // return CiviCRM’s xx_YY locale that either matches Backdrop’s Chinese locale
424 // (for CRM-6281), Backdrop’s xx_YY or is retrieved based on Backdrop’s xx
974c6b58
HD
425 // sometimes for CLI based on order called, this might not be set and/or empty
426 global $language;
427
428 if (empty($language)) {
429 return NULL;
430 }
431
432 if ($language->langcode == 'zh-hans') {
433 return 'zh_CN';
434 }
435
436 if ($language->langcode == 'zh-hant') {
437 return 'zh_TW';
438 }
439
440 if (preg_match('/^.._..$/', $language->langcode)) {
441 return $language->langcode;
442 }
443
444 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->langcode, 0, 2));
445 }
446
447 /**
448 * @inheritDoc
449 */
450 public function setUFLocale($civicrm_language) {
451 global $language;
452
453 $langcode = substr($civicrm_language, 0, 2);
454 $languages = language_list(FALSE, TRUE);
455
456 if (isset($languages[$langcode])) {
457 $language = $languages[$langcode];
458
459 // Config must be re-initialized to reset the base URL
460 // otherwise links will have the wrong language prefix/domain.
461 $config = CRM_Core_Config::singleton();
462 $config->free();
463
464 return TRUE;
465 }
466
467 return FALSE;
468 }
469
84fce21c
TO
470 /**
471 * Determine the native ID of the CMS user.
472 *
473 * @param string $username
e97c66ff 474 * @return int|null
84fce21c
TO
475 */
476 public function getUfId($username) {
477 $user = user_load_by_name($username);
478 if (empty($user->uid)) {
479 return NULL;
480 }
481 return $user->uid;
482 }
483
484 /**
485 * @inheritDoc
486 */
487 public function logout() {
488 module_load_include('inc', 'user', 'user.pages');
ddd5c06f 489 user_logout();
84fce21c
TO
490 }
491
492 /**
493 * Get the default location for CiviCRM blocks.
494 *
495 * @return string
496 */
497 public function getDefaultBlockLocation() {
498 return 'sidebar_first';
499 }
500
501 /**
ddd5c06f 502 * Load Backdrop bootstrap.
84fce21c
TO
503 *
504 * @param array $params
505 * Either uid, or name & pass.
506 * @param bool $loadUser
507 * Boolean Require CMS user load.
508 * @param bool $throwError
509 * If true, print error on failure and exit.
510 * @param bool|string $realPath path to script
511 *
512 * @return bool
513 */
be2fb01f 514 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
84fce21c
TO
515 $cmsPath = $this->cmsRootPath($realPath);
516
5c6ebf4c 517 if (!file_exists("$cmsPath/core/includes/bootstrap.inc")) {
84fce21c
TO
518 if ($throwError) {
519 echo '<br />Sorry, could not locate bootstrap.inc\n';
520 exit();
521 }
522 return FALSE;
523 }
84da17e3 524 // load Backdrop bootstrap
84fce21c 525 chdir($cmsPath);
5c6ebf4c 526 define('BACKDROP_ROOT', $cmsPath);
84fce21c 527
84da17e3 528 // For Backdrop multi-site CRM-11313
84fce21c
TO
529 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
530 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
531 if (!empty($matches[1])) {
532 $_SERVER['HTTP_HOST'] = $matches[1];
533 }
534 }
ddd5c06f 535 require_once "$cmsPath/core/includes/bootstrap.inc";
a620adeb 536 require_once "$cmsPath/core/includes/config.inc";
ddd5c06f 537 backdrop_bootstrap(BACKDROP_BOOTSTRAP_FULL);
84fce21c 538
ddd5c06f
NH
539 // Explicitly setting error reporting, since we cannot handle Backdrop
540 // related notices.
84fce21c
TO
541 error_reporting(1);
542 if (!function_exists('module_exists') || !module_exists('civicrm')) {
543 if ($throwError) {
ddd5c06f 544 echo '<br />Sorry, could not load Backdrop bootstrap.';
84fce21c
TO
545 exit();
546 }
547 return FALSE;
548 }
549
ddd5c06f 550 // Backdrop successfully bootstrapped.
84fce21c
TO
551 $config = CRM_Core_Config::singleton();
552
553 // lets also fix the clean url setting
554 // CRM-6948
ddd5c06f 555 $config->cleanURL = (int) config_get('system.core', 'clean_url');
84fce21c
TO
556
557 // we need to call the config hook again, since we now know
558 // all the modules that are listening on it, does not apply
559 // to J! and WP as yet
560 // CRM-8655
561 CRM_Utils_Hook::config($config);
562
563 if (!$loadUser) {
564 return TRUE;
565 }
566
9c1bc317 567 $uid = $params['uid'] ?? NULL;
84fce21c 568 if (!$uid) {
ddd5c06f 569 // Load the user we need to check Backdrop permissions.
84fce21c
TO
570 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
571 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
572
573 if ($name) {
574 $uid = user_authenticate($name, $pass);
575 if (!$uid) {
576 if ($throwError) {
577 echo '<br />Sorry, unrecognized username or password.';
578 exit();
579 }
580 return FALSE;
581 }
582 }
583 }
584
585 if ($uid) {
586 $account = user_load($uid);
587 if ($account && $account->uid) {
588 global $user;
589 $user = $account;
590 return TRUE;
591 }
592 }
593
594 if ($throwError) {
595 echo '<br />Sorry, can not load CMS user account.';
596 exit();
597 }
598
599 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
600 // which means that define(CIVICRM_CLEANURL) was correctly set.
601 // So we correct it
602 $config = CRM_Core_Config::singleton();
ddd5c06f 603 $config->cleanURL = (int) config_get('system.core', 'clean_url');
84fce21c 604
ddd5c06f
NH
605 // CRM-8655: Backdrop wasn't available during bootstrap, so
606 // hook_civicrm_config() never executes.
84fce21c
TO
607 CRM_Utils_Hook::config($config);
608
609 return FALSE;
610 }
611
612 /**
ddd5c06f 613 * @inheritDoc
84fce21c
TO
614 */
615 public function cmsRootPath($scriptFilename = NULL) {
a93a0366
TO
616 global $civicrm_paths;
617 if (!empty($civicrm_paths['cms.root']['path'])) {
618 return $civicrm_paths['cms.root']['path'];
619 }
620
ddd5c06f
NH
621 $cmsRoot = NULL;
622 $valid = NULL;
84fce21c
TO
623
624 if (!is_null($scriptFilename)) {
625 $path = $scriptFilename;
626 }
627 else {
628 $path = $_SERVER['SCRIPT_FILENAME'];
629 }
630
84fce21c
TO
631 // CRM-7582
632 $pathVars = explode('/',
633 str_replace('//', '/',
634 str_replace('\\', '/', $path)
635 )
636 );
637
ddd5c06f 638 // Keep the first directory name for later.
84fce21c
TO
639 $firstVar = array_shift($pathVars);
640
ddd5c06f 641 // Remove script name to reduce one iteration.
84fce21c
TO
642 array_pop($pathVars);
643
644 // CRM-7429 -- do check for uppermost 'includes' dir, which would
645 // work for multisite installation.
646 do {
647 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
5c6ebf4c
TO
648 // Stop if we find backdrop signature file.
649 if (file_exists("$cmsRoot/core/misc/backdrop.js")) {
84fce21c
TO
650 $valid = TRUE;
651 break;
652 }
ddd5c06f 653 // Remove one directory level.
84fce21c
TO
654 array_pop($pathVars);
655 } while (count($pathVars));
656
657 return ($valid) ? $cmsRoot : NULL;
658 }
659
660 /**
661 * @inheritDoc
662 */
663 public function isUserLoggedIn() {
664 $isloggedIn = FALSE;
665 if (function_exists('user_is_logged_in')) {
666 $isloggedIn = user_is_logged_in();
667 }
668
669 return $isloggedIn;
670 }
671
672 /**
673 * @inheritDoc
674 */
675 public function getLoggedInUfID() {
676 $ufID = NULL;
677 if (function_exists('user_is_logged_in') &&
678 user_is_logged_in() &&
679 function_exists('user_uid_optional_to_arg')
680 ) {
be2fb01f 681 $ufID = user_uid_optional_to_arg([]);
84fce21c
TO
682 }
683
684 return $ufID;
685 }
686
687 /**
688 * @inheritDoc
689 */
690 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
691 if (empty($url)) {
692 return $url;
693 }
694
ddd5c06f 695 if (function_exists('config_get') &&
84fce21c
TO
696 module_exists('locale') &&
697 function_exists('language_negotiation_get')
698 ) {
699 global $language;
700
ddd5c06f 701 // Check if language support from the URL (Path prefix or domain) is set.
84fce21c 702 if (language_negotiation_get('language') == 'locale-url') {
ddd5c06f 703 $urlType = config_get('locale.settings', 'locale_language_negotiation_url_part');
84fce21c 704
ddd5c06f
NH
705 // URL prefix negotiation.
706 if ($urlType == LANGUAGE_NEGOTIATION_URL_PREFIX) {
84fce21c
TO
707 if (isset($language->prefix) && $language->prefix) {
708 if ($addLanguagePart) {
709 $url .= $language->prefix . '/';
710 }
711 if ($removeLanguagePart) {
712 $url = str_replace("/{$language->prefix}/", '/', $url);
713 }
714 }
715 }
ddd5c06f
NH
716 // Domain negotiation.
717 if ($urlType == LANGUAGE_NEGOTIATION_URL_DOMAIN) {
84fce21c
TO
718 if (isset($language->domain) && $language->domain) {
719 if ($addLanguagePart) {
720 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain);
ddd5c06f
NH
721 // Backdrop function base_path() adds a "/" to the beginning and
722 // end of the returned path.
84fce21c
TO
723 if (substr($cleanedUrl, -1) == '/') {
724 $cleanedUrl = substr($cleanedUrl, 0, -1);
725 }
726 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $cleanedUrl . base_path();
727 }
728 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
729 $url = str_replace('\\', '/', $url);
730 $parseUrl = parse_url($url);
731
732 //kinda hackish but not sure how to do it right
733 //hope http_build_url() will help at some point.
734 if (is_array($parseUrl) && !empty($parseUrl)) {
735 $urlParts = explode('/', $url);
736 $hostKey = array_search($parseUrl['host'], $urlParts);
737 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
738 $urlParts[$hostKey] = $ufUrlParts['host'];
739 $url = implode('/', $urlParts);
740 }
741 }
742 }
743 }
744 }
745 }
746
747 return $url;
748 }
749
750 /**
751 * Find any users/roles/security-principals with the given permission
752 * and replace it with one or more permissions.
753 *
754 * @param string $oldPerm
755 * @param array $newPerms
756 * Array, strings.
757 */
758 public function replacePermission($oldPerm, $newPerms) {
759 $roles = user_roles(FALSE, $oldPerm);
760 if (!empty($roles)) {
761 foreach (array_keys($roles) as $rid) {
be2fb01f 762 user_role_revoke_permissions($rid, [$oldPerm]);
84fce21c
TO
763 user_role_grant_permissions($rid, $newPerms);
764 }
765 }
766 }
767
768 /**
769 * Wrapper for og_membership creation.
770 *
771 * @param int $ogID
772 * Organic Group ID.
ddd5c06f
NH
773 * @param int $userID
774 * Backdrop User ID.
84fce21c 775 */
ddd5c06f 776 public function og_membership_create($ogID, $userID) {
84fce21c
TO
777 if (function_exists('og_entity_query_alter')) {
778 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
779 //
780 // @TODO Find more solid way to check - try system_get_info('module', 'og').
781 //
782 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
be2fb01f 783 og_group('node', $ogID, ['entity' => user_load($userID)]);
84fce21c
TO
784 }
785 else {
786 // Works for the OG 7.x-1.x branch
be2fb01f 787 og_group($ogID, ['entity' => user_load($userID)]);
84fce21c
TO
788 }
789 }
790
791 /**
792 * Wrapper for og_membership deletion.
793 *
794 * @param int $ogID
795 * Organic Group ID.
ddd5c06f
NH
796 * @param int $userID
797 * Backdrop User ID.
84fce21c 798 */
ddd5c06f 799 public function og_membership_delete($ogID, $userID) {
84fce21c
TO
800 if (function_exists('og_entity_query_alter')) {
801 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
802 // TODO: Find a more solid way to make this test
803 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
ddd5c06f 804 og_ungroup('node', $ogID, 'user', user_load($userID));
84fce21c
TO
805 }
806 else {
807 // Works for the OG 7.x-1.x branch
ddd5c06f 808 og_ungroup($ogID, 'user', user_load($userID));
84fce21c
TO
809 }
810 }
811
812 /**
813 * @inheritDoc
814 */
815 public function getTimeZoneString() {
816 global $user;
817 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
ddd5c06f 818 if (config_get('system.date', 'user_configurable_timezones') && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
84fce21c
TO
819 $timezone = $user->timezone;
820 }
821 else {
ddd5c06f 822 $timezone = config_get('system.date', 'default_timezone');
84fce21c
TO
823 }
824 if (!$timezone) {
825 $timezone = parent::getTimeZoneString();
826 }
827 return $timezone;
828 }
829
830 /**
831 * @inheritDoc
832 */
833 public function setHttpHeader($name, $value) {
ddd5c06f 834 backdrop_add_http_header($name, $value);
84fce21c
TO
835 }
836
837 /**
838 * @inheritDoc
839 */
840 public function synchronizeUsers() {
841 $config = CRM_Core_Config::singleton();
842 if (PHP_SAPI != 'cli') {
843 set_time_limit(300);
844 }
845 $id = 'uid';
846 $mail = 'mail';
847 $name = 'name';
848
849 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
850
851 $user = new StdClass();
852 $uf = $config->userFramework;
853 $contactCount = 0;
854 $contactCreated = 0;
855 $contactMatching = 0;
856 foreach ($result as $row) {
857 $user->$id = $row->$id;
858 $user->$mail = $row->$mail;
859 $user->$name = $row->$name;
860 $contactCount++;
861 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
862 $contactCreated++;
863 }
864 else {
865 $contactMatching++;
866 }
84fce21c
TO
867 }
868
be2fb01f 869 return [
84fce21c
TO
870 'contactCount' => $contactCount,
871 'contactMatching' => $contactMatching,
872 'contactCreated' => $contactCreated,
be2fb01f 873 ];
84fce21c
TO
874 }
875
ec95d32c
TO
876 /**
877 * @inheritDoc
878 */
879 public function clearResourceCache() {
880 _backdrop_flush_css_js();
881 }
5c6ebf4c
TO
882
883 /**
884 * Get all the contact emails for users that have a specific permission.
885 *
886 * @param string $permissionName
887 * Name of the permission we are interested in.
888 *
889 * @return string
890 * a comma separated list of email addresses
891 */
892 public function permissionEmails($permissionName) {
893 // FIXME!!!!
be2fb01f 894 return [];
5c6ebf4c
TO
895 }
896
84da17e3 897 /**
898 * @inheritdoc
899 */
900 public function getDefaultFileStorage() {
901 $config = CRM_Core_Config::singleton();
902 $baseURL = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
903
904 $siteName = $this->parseBackdropSiteNameFromRequest('/files/civicrm');
905 if ($siteName) {
906 $filesURL = $baseURL . "sites/$siteName/files/civicrm/";
907 }
908 else {
909 $filesURL = $baseURL . "files/civicrm/";
910 }
911
be2fb01f 912 return [
84da17e3 913 'url' => $filesURL,
914 'path' => CRM_Utils_File::baseFilePath(),
be2fb01f 915 ];
84da17e3 916 }
917
918 /**
919 * Check if a resource url is within the Backdrop directory and format appropriately.
920 *
921 * @param $url (reference)
922 *
923 * @return bool
924 * TRUE for internal paths, FALSE for external. The backdrop_add_js fn is able to add js more
925 * efficiently if it is known to be in the Backdrop site
926 */
927 public function formatResourceUrl(&$url) {
928 $internal = FALSE;
929 $base = CRM_Core_Config::singleton()->resourceBase;
930 global $base_url;
931 // Handle absolute urls
932 // compares $url (which is some unknown/untrusted value from a third-party dev) to the CMS's base url (which is independent of civi's url)
933 // to see if the url is within our Backdrop dir, if it is we are able to treated it as an internal url
934 if (strpos($url, $base_url) === 0) {
935 $file = trim(str_replace($base_url, '', $url), '/');
936 // CRM-18130: Custom CSS URL not working if aliased or rewritten
937 if (file_exists(BACKDROP_ROOT . $file)) {
938 $url = $file;
939 $internal = TRUE;
940 }
941 }
942 // Handle relative urls that are within the CiviCRM module directory
943 elseif (strpos($url, $base) === 0) {
944 $internal = TRUE;
945 $url = $this->appendCoreDirectoryToResourceBase(dirname(backdrop_get_path('module', 'civicrm')) . '/') . trim(substr($url, strlen($base)), '/');
946 }
947 // Strip query string
948 $q = strpos($url, '?');
949 if ($q && $internal) {
950 $url = substr($url, 0, $q);
951 }
952 return $internal;
953 }
954
955 /**
956 * @inheritDoc
957 */
958 public function setMessage($message) {
959 backdrop_set_message($message);
960 }
961
962 /**
963 * @inheritDoc
964 */
965 public function permissionDenied() {
966 backdrop_access_denied();
967 }
968
969 /**
970 * @inheritDoc
971 */
972 public function flush() {
973 backdrop_flush_all_caches();
974 }
975
976 /**
977 * Determine if Backdrop multi-site applies to the current request -- and,
978 * specifically, determine the name of the multisite folder.
979 *
980 * @param string $flagFile
981 * Check if $flagFile exists inside the site dir.
982 * @return null|string
983 * string, e.g. `bar.example.com` if using multisite.
984 * NULL if using the default site.
985 */
986 private function parseBackdropSiteNameFromRequest($flagFile = '') {
987 $phpSelf = array_key_exists('PHP_SELF', $_SERVER) ? $_SERVER['PHP_SELF'] : '';
988 $httpHost = array_key_exists('HTTP_HOST', $_SERVER) ? $_SERVER['HTTP_HOST'] : '';
989 if (empty($httpHost)) {
990 $httpHost = parse_url(CIVICRM_UF_BASEURL, PHP_URL_HOST);
991 if (parse_url(CIVICRM_UF_BASEURL, PHP_URL_PORT)) {
992 $httpHost .= ':' . parse_url(CIVICRM_UF_BASEURL, PHP_URL_PORT);
993 }
994 }
995
996 $confdir = $this->cmsRootPath() . '/sites';
997
998 if (file_exists($confdir . "/sites.php")) {
999 include $confdir . "/sites.php";
1000 }
1001 else {
be2fb01f 1002 $sites = [];
84da17e3 1003 }
1004
1005 $uri = explode('/', $phpSelf);
1006 $server = explode('.', implode('.', array_reverse(explode(':', rtrim($httpHost, '.')))));
1007 for ($i = count($uri) - 1; $i > 0; $i--) {
1008 for ($j = count($server); $j > 0; $j--) {
1009 $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
1010 if (file_exists("$confdir/$dir" . $flagFile)) {
1011 \Civi::$statics[__CLASS__]['drupalSiteName'] = $dir;
1012 return \Civi::$statics[__CLASS__]['drupalSiteName'];
1013 }
1014 // check for alias
1015 if (isset($sites[$dir]) && file_exists("$confdir/{$sites[$dir]}" . $flagFile)) {
1016 \Civi::$statics[__CLASS__]['drupalSiteName'] = $sites[$dir];
1017 return \Civi::$statics[__CLASS__]['drupalSiteName'];
1018 }
1019 }
1020 }
1021 }
1022
88764dbe 1023 /**
8a09f4aa 1024 * Append Backdrop CSS and JS to coreResourcesList.
88764dbe 1025 *
303017a1 1026 * @param \Civi\Core\Event\GenericHookEvent $e
88764dbe 1027 */
303017a1
CW
1028 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent $e) {
1029 $e->list[] = 'css/backdrop.css';
1030 $e->list[] = 'js/crm.backdrop.js';
88764dbe 1031 }
fb3c1356 1032
84fce21c 1033}