CRM-20780 Add drupal option to define CMS_ROOT
[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
76 $form = drupal_retrieve_form('user_register_form', $form_state);
77 $form_state['process_input'] = 1;
78 $form_state['submitted'] = 1;
79 $form['#array_parents'] = array();
80 $form['#tree'] = FALSE;
81 drupal_process_form('user_register_form', $form, $form_state);
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 /**
106 * Check if username and email exists in the drupal db.
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) {
118 // unset drupal messages to avoid twice display of errors
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
167 drupal_set_title($pageTitle, PASS_THROUGH);
168 }
169 }
170
171 /**
172 * @inheritDoc
173 */
174 public function appendBreadCrumb($breadCrumbs) {
175 $breadCrumb = drupal_get_breadcrumb();
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 }
193 drupal_set_breadcrumb($breadCrumb);
194 }
195
196 /**
197 * @inheritDoc
198 */
199 public function resetBreadCrumb() {
200 $bc = array();
201 drupal_set_breadcrumb($bc);
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 );
215 drupal_add_html_head($data, $key);
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 }
233 // If the path is within the drupal directory we can use the more efficient 'file' setting
234 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
235 drupal_add_js($url, $params);
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 }
253 drupal_add_js($code, $params);
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();
265 // If the path is within the drupal directory we can use the more efficient 'file' setting
266 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
267 drupal_add_css($url, $params);
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');
279 drupal_add_css($code, $params);
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
334 // SOAP cannot load drupal bootstrap and hence we do it the old way
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() {
417 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
418 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
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 }
518 // load drupal bootstrap
519 chdir($cmsPath);
5c6ebf4c 520 define('BACKDROP_ROOT', $cmsPath);
84fce21c
TO
521
522 // For drupal multi-site CRM-11313
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) {
ddd5c06f
NH
609 $cmsRoot = NULL;
610 $valid = NULL;
84fce21c
TO
611
612 if (!is_null($scriptFilename)) {
613 $path = $scriptFilename;
614 }
615 else {
616 $path = $_SERVER['SCRIPT_FILENAME'];
617 }
618
84fce21c
TO
619 // CRM-7582
620 $pathVars = explode('/',
621 str_replace('//', '/',
622 str_replace('\\', '/', $path)
623 )
624 );
625
ddd5c06f 626 // Keep the first directory name for later.
84fce21c
TO
627 $firstVar = array_shift($pathVars);
628
ddd5c06f 629 // Remove script name to reduce one iteration.
84fce21c
TO
630 array_pop($pathVars);
631
632 // CRM-7429 -- do check for uppermost 'includes' dir, which would
633 // work for multisite installation.
634 do {
635 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
5c6ebf4c
TO
636 // Stop if we find backdrop signature file.
637 if (file_exists("$cmsRoot/core/misc/backdrop.js")) {
84fce21c
TO
638 $valid = TRUE;
639 break;
640 }
ddd5c06f 641 // Remove one directory level.
84fce21c
TO
642 array_pop($pathVars);
643 } while (count($pathVars));
644
645 return ($valid) ? $cmsRoot : NULL;
646 }
647
648 /**
649 * @inheritDoc
650 */
651 public function isUserLoggedIn() {
652 $isloggedIn = FALSE;
653 if (function_exists('user_is_logged_in')) {
654 $isloggedIn = user_is_logged_in();
655 }
656
657 return $isloggedIn;
658 }
659
660 /**
661 * @inheritDoc
662 */
663 public function getLoggedInUfID() {
664 $ufID = NULL;
665 if (function_exists('user_is_logged_in') &&
666 user_is_logged_in() &&
667 function_exists('user_uid_optional_to_arg')
668 ) {
669 $ufID = user_uid_optional_to_arg(array());
670 }
671
672 return $ufID;
673 }
674
675 /**
676 * @inheritDoc
677 */
678 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
679 if (empty($url)) {
680 return $url;
681 }
682
ddd5c06f 683 if (function_exists('config_get') &&
84fce21c
TO
684 module_exists('locale') &&
685 function_exists('language_negotiation_get')
686 ) {
687 global $language;
688
ddd5c06f 689 // Check if language support from the URL (Path prefix or domain) is set.
84fce21c 690 if (language_negotiation_get('language') == 'locale-url') {
ddd5c06f 691 $urlType = config_get('locale.settings', 'locale_language_negotiation_url_part');
84fce21c 692
ddd5c06f
NH
693 // URL prefix negotiation.
694 if ($urlType == LANGUAGE_NEGOTIATION_URL_PREFIX) {
84fce21c
TO
695 if (isset($language->prefix) && $language->prefix) {
696 if ($addLanguagePart) {
697 $url .= $language->prefix . '/';
698 }
699 if ($removeLanguagePart) {
700 $url = str_replace("/{$language->prefix}/", '/', $url);
701 }
702 }
703 }
ddd5c06f
NH
704 // Domain negotiation.
705 if ($urlType == LANGUAGE_NEGOTIATION_URL_DOMAIN) {
84fce21c
TO
706 if (isset($language->domain) && $language->domain) {
707 if ($addLanguagePart) {
708 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain);
ddd5c06f
NH
709 // Backdrop function base_path() adds a "/" to the beginning and
710 // end of the returned path.
84fce21c
TO
711 if (substr($cleanedUrl, -1) == '/') {
712 $cleanedUrl = substr($cleanedUrl, 0, -1);
713 }
714 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $cleanedUrl . base_path();
715 }
716 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
717 $url = str_replace('\\', '/', $url);
718 $parseUrl = parse_url($url);
719
720 //kinda hackish but not sure how to do it right
721 //hope http_build_url() will help at some point.
722 if (is_array($parseUrl) && !empty($parseUrl)) {
723 $urlParts = explode('/', $url);
724 $hostKey = array_search($parseUrl['host'], $urlParts);
725 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
726 $urlParts[$hostKey] = $ufUrlParts['host'];
727 $url = implode('/', $urlParts);
728 }
729 }
730 }
731 }
732 }
733 }
734
735 return $url;
736 }
737
738 /**
739 * Find any users/roles/security-principals with the given permission
740 * and replace it with one or more permissions.
741 *
742 * @param string $oldPerm
743 * @param array $newPerms
744 * Array, strings.
745 */
746 public function replacePermission($oldPerm, $newPerms) {
747 $roles = user_roles(FALSE, $oldPerm);
748 if (!empty($roles)) {
749 foreach (array_keys($roles) as $rid) {
750 user_role_revoke_permissions($rid, array($oldPerm));
751 user_role_grant_permissions($rid, $newPerms);
752 }
753 }
754 }
755
756 /**
757 * Wrapper for og_membership creation.
758 *
759 * @param int $ogID
760 * Organic Group ID.
ddd5c06f
NH
761 * @param int $userID
762 * Backdrop User ID.
84fce21c 763 */
ddd5c06f 764 public function og_membership_create($ogID, $userID) {
84fce21c
TO
765 if (function_exists('og_entity_query_alter')) {
766 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
767 //
768 // @TODO Find more solid way to check - try system_get_info('module', 'og').
769 //
770 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
ddd5c06f 771 og_group('node', $ogID, array('entity' => user_load($userID)));
84fce21c
TO
772 }
773 else {
774 // Works for the OG 7.x-1.x branch
ddd5c06f 775 og_group($ogID, array('entity' => user_load($userID)));
84fce21c
TO
776 }
777 }
778
779 /**
780 * Wrapper for og_membership deletion.
781 *
782 * @param int $ogID
783 * Organic Group ID.
ddd5c06f
NH
784 * @param int $userID
785 * Backdrop User ID.
84fce21c 786 */
ddd5c06f 787 public function og_membership_delete($ogID, $userID) {
84fce21c
TO
788 if (function_exists('og_entity_query_alter')) {
789 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
790 // TODO: Find a more solid way to make this test
791 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
ddd5c06f 792 og_ungroup('node', $ogID, 'user', user_load($userID));
84fce21c
TO
793 }
794 else {
795 // Works for the OG 7.x-1.x branch
ddd5c06f 796 og_ungroup($ogID, 'user', user_load($userID));
84fce21c
TO
797 }
798 }
799
800 /**
801 * @inheritDoc
802 */
803 public function getTimeZoneString() {
804 global $user;
805 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
ddd5c06f 806 if (config_get('system.date', 'user_configurable_timezones') && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
84fce21c
TO
807 $timezone = $user->timezone;
808 }
809 else {
ddd5c06f 810 $timezone = config_get('system.date', 'default_timezone');
84fce21c
TO
811 }
812 if (!$timezone) {
813 $timezone = parent::getTimeZoneString();
814 }
815 return $timezone;
816 }
817
818 /**
819 * @inheritDoc
820 */
821 public function setHttpHeader($name, $value) {
ddd5c06f 822 backdrop_add_http_header($name, $value);
84fce21c
TO
823 }
824
825 /**
826 * @inheritDoc
827 */
828 public function synchronizeUsers() {
829 $config = CRM_Core_Config::singleton();
830 if (PHP_SAPI != 'cli') {
831 set_time_limit(300);
832 }
833 $id = 'uid';
834 $mail = 'mail';
835 $name = 'name';
836
837 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
838
839 $user = new StdClass();
840 $uf = $config->userFramework;
841 $contactCount = 0;
842 $contactCreated = 0;
843 $contactMatching = 0;
844 foreach ($result as $row) {
845 $user->$id = $row->$id;
846 $user->$mail = $row->$mail;
847 $user->$name = $row->$name;
848 $contactCount++;
849 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
850 $contactCreated++;
851 }
852 else {
853 $contactMatching++;
854 }
855 if (is_object($match)) {
856 $match->free();
857 }
858 }
859
860 return array(
861 'contactCount' => $contactCount,
862 'contactMatching' => $contactMatching,
863 'contactCreated' => $contactCreated,
864 );
865 }
866
ec95d32c
TO
867 /**
868 * @inheritDoc
869 */
870 public function clearResourceCache() {
871 _backdrop_flush_css_js();
872 }
5c6ebf4c
TO
873
874 /**
875 * Get all the contact emails for users that have a specific permission.
876 *
877 * @param string $permissionName
878 * Name of the permission we are interested in.
879 *
880 * @return string
881 * a comma separated list of email addresses
882 */
883 public function permissionEmails($permissionName) {
884 // FIXME!!!!
885 return array();
886 }
887
84fce21c 888}