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