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