Add in unit test of searching when price field value label has changed
[civicrm-core.git] / CRM / Utils / System / Drupal6.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34/**
b8c71ffa 35 * Drupal specific stuff goes here.
6a488035 36 */
9977c6f5 37class CRM_Utils_System_Drupal6 extends CRM_Utils_System_DrupalBase {
6a488035
TO
38
39 /**
b8c71ffa 40 * Theme output.
41 *
42 * If we are using a theming system, invoke theme, else just print the content.
6a488035 43 *
77855840
TO
44 * @param string $content
45 * The content that will be themed.
46 * @param bool $print
47 * Are we displaying to the screen or bypassing theming?.
48 * @param bool $maintenance
49 * For maintenance mode.
6a488035 50 *
b8c71ffa 51 * @return null|string
a6c01b45 52 * prints content on stdout
6a488035 53 */
00be9182 54 public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
6a488035
TO
55 // TODO: Simplify; this was copied verbatim from CiviCRM 3.4's multi-UF theming function, but that's more complex than necessary
56 if (function_exists('theme') && !$print) {
57 if ($maintenance) {
58 drupal_set_breadcrumb('');
59 drupal_maintenance_theme();
60 }
61
62 // Arg 3 for D6 theme() is "show_blocks". Previously, we passed
63 // through a badly named variable ("$args") which was almost always
64 // TRUE (except on fatal error screen). However, this feature is
65 // non-functional on D6 default themes, was purposefully removed from
66 // D7, has no analog in other our other CMS's, and clutters the code.
67 // Hard-wiring to TRUE should be OK.
68 $out = theme('page', $content, TRUE);
69 }
70 else {
71 $out = $content;
72 }
73
74 print $out;
b8c71ffa 75 return NULL;
6a488035
TO
76 }
77
78 /**
b8c71ffa 79 * Create user.
80 *
17f443df 81 * @inheritDoc
6a488035 82 */
00be9182 83 public function createUser(&$params, $mail) {
be2fb01f
CW
84 $form_state = [];
85 $form_state['values'] = [
6a488035
TO
86 'name' => $params['cms_name'],
87 'mail' => $params[$mail],
88 'op' => 'Create new account',
be2fb01f 89 ];
a57957f7
KJ
90
91 $admin = user_access('administer users');
92 if (!variable_get('user_email_verification', TRUE) || $admin) {
6a488035
TO
93 $form_state['values']['pass']['pass1'] = $params['cms_pass'];
94 $form_state['values']['pass']['pass2'] = $params['cms_pass'];
95 }
96
97 $config = CRM_Core_Config::singleton();
98
99 // we also need to redirect b
100 $config->inCiviCRM = TRUE;
101
102 $form = drupal_retrieve_form('user_register', $form_state);
103 $form['#post'] = $form_state['values'];
104 drupal_prepare_form('user_register', $form, $form_state);
105
106 // remove the captcha element from the form prior to processing
107 unset($form['captcha']);
108
109 drupal_process_form('user_register', $form, $form_state);
110
111 $config->inCiviCRM = FALSE;
112
113 if (form_get_errors() || !isset($form_state['user'])) {
114 return FALSE;
115 }
6a488035 116 return $form_state['user']->uid;
6a488035
TO
117 }
118
bb3a214a 119 /**
17f443df 120 * @inheritDoc
bb3a214a 121 */
00be9182 122 public function updateCMSName($ufID, $ufName) {
6a488035
TO
123 // CRM-5555
124 if (function_exists('user_load')) {
be2fb01f 125 $user = user_load(['uid' => $ufID]);
6a488035 126 if ($user->mail != $ufName) {
be2fb01f
CW
127 user_save($user, ['mail' => $ufName]);
128 $user = user_load(['uid' => $ufID]);
6a488035
TO
129 }
130 }
131 }
132
133 /**
fe482240 134 * Check if username and email exists in the drupal db.
6a488035 135 *
77855840
TO
136 * @param array $params
137 * Array of name and mail values.
138 * @param array $errors
139 * Array of errors.
140 * @param string $emailName
141 * Field label for the 'email'.
6a488035 142 */
00be9182 143 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
6a488035
TO
144 $config = CRM_Core_Config::singleton();
145
353ffa53
TO
146 $dao = new CRM_Core_DAO();
147 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
6a488035
TO
148 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
149 _user_edit_validate(NULL, $params);
150 $errors = form_get_errors();
6a488035 151 if ($errors) {
a7488080 152 if (!empty($errors['name'])) {
6a488035
TO
153 $errors['cms_name'] = $errors['name'];
154 }
a7488080 155 if (!empty($errors['mail'])) {
6a488035
TO
156 $errors[$emailName] = $errors['mail'];
157 }
158 // also unset drupal messages to avoid twice display of errors
159 unset($_SESSION['messages']);
160 }
161
a5ecff8d 162 // Do the name check manually.
6a488035
TO
163 $nameError = user_validate_name($params['name']);
164 if ($nameError) {
165 $errors['cms_name'] = $nameError;
166 }
167
b27d1855 168 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
6a488035 169 $sql = "
b67a6d82
E
170 SELECT name, mail
171 FROM {users}
172 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))
173 ";
b67a6d82 174
48f12f07 175 $result = db_query($sql);
8982d5f8
EM
176 $row = db_fetch_array($result);
177 if (!$row) {
b67a6d82 178 return;
6a488035 179 }
5a604d61 180
b67a6d82
E
181 $user = NULL;
182
6a488035 183 if (!empty($row)) {
b67a6d82
E
184 $dbName = CRM_Utils_Array::value('name', $row);
185 $dbEmail = CRM_Utils_Array::value('mail', $row);
6a488035
TO
186 if (strtolower($dbName) == strtolower($name)) {
187 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
be2fb01f 188 [1 => $name]
6a488035
TO
189 );
190 }
191 if (strtolower($dbEmail) == strtolower($email)) {
22e263ad 192 if (empty($email)) {
b67a6d82 193 $errors[$emailName] = ts('You cannot create an email account for a contact with no email',
be2fb01f 194 [1 => $email]
b67a6d82
E
195 );
196 }
92e4c2a5 197 else {
161f725c 198 $errors[$emailName] = ts('This email %1 already has an account associated with it. Please select another email.',
be2fb01f 199 [1 => $email]
b67a6d82
E
200 );
201 }
6a488035
TO
202 }
203 }
204 }
205
f4aaa82a 206 /**
17f443df 207 * @inheritDoc
6a488035 208 */
00be9182 209 public function setTitle($title, $pageTitle = NULL) {
6a488035
TO
210 if (!$pageTitle) {
211 $pageTitle = $title;
212 }
213 if (arg(0) == 'civicrm') {
214 //set drupal title
215 drupal_set_title($pageTitle);
216 }
217 }
218
219 /**
17f443df 220 * @inheritDoc
6a488035 221 */
00be9182 222 public function appendBreadCrumb($breadCrumbs) {
6a488035
TO
223 $breadCrumb = drupal_get_breadcrumb();
224
225 if (is_array($breadCrumbs)) {
226 foreach ($breadCrumbs as $crumbs) {
227 if (stripos($crumbs['url'], 'id%%')) {
be2fb01f 228 $args = ['cid', 'mid'];
6a488035
TO
229 foreach ($args as $a) {
230 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
231 FALSE, NULL, $_GET
232 );
233 if ($val) {
234 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
235 }
236 }
237 }
238 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
239 }
240 }
241 drupal_set_breadcrumb($breadCrumb);
242 }
243
244 /**
17f443df 245 * @inheritDoc
6a488035 246 */
00be9182 247 public function resetBreadCrumb() {
be2fb01f 248 $bc = [];
6a488035
TO
249 drupal_set_breadcrumb($bc);
250 }
251
252 /**
fe482240 253 * Append a string to the head of the html file.
6a488035 254 *
77855840
TO
255 * @param string $head
256 * The new string to be appended.
6a488035 257 */
00be9182 258 public function addHTMLHead($head) {
6a488035
TO
259 drupal_set_html_head($head);
260 }
261
6a488035 262 /**
fe482240 263 * Add a css file.
6a488035 264 *
353ffa53 265 * @param $url : string, absolute path to file
5a4f6742
CW
266 * @param string $region
267 * location within the document: 'html-header', 'page-header', 'page-footer'.
6a488035
TO
268 *
269 * Note: This function is not to be called directly
270 * @see CRM_Core_Region::render()
271 *
a6c01b45
CW
272 * @return bool
273 * TRUE if we support this operation in this CMS, FALSE otherwise
6a488035
TO
274 */
275 public function addStyleUrl($url, $region) {
42e1a97c 276 if ($region != 'html-header' || !$this->formatResourceUrl($url)) {
6a488035
TO
277 return FALSE;
278 }
279 drupal_add_css($url);
280 return TRUE;
281 }
282
283 /**
17f443df 284 * @inheritDoc
6a488035 285 */
00be9182 286 public function mapConfigToSSL() {
6a488035
TO
287 global $base_url;
288 $base_url = str_replace('http://', 'https://', $base_url);
289 }
4f4a85f8 290
8246bca4 291 /**
292 * Get the name of the table that stores the user details.
293 *
294 * @return string
295 */
19f0072b 296 protected function getUsersTableName() {
76eeb935
LG
297 $userFrameworkUsersTableName = Civi::settings()->get('userFrameworkUsersTableName');
298 if (empty($userFrameworkUsersTableName)) {
299 $userFrameworkUsersTableName = 'users';
300 }
301 return $userFrameworkUsersTableName;
302 }
6a488035
TO
303
304 /**
17f443df 305 * @inheritDoc
6a488035 306 */
00be9182 307 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
e7292422
TO
308 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
309 // if ever now.
310 // probably if bootstrap is loaded this call
311 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
312 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
313 // safe in the unknown situation where authenticate might be called & it is important that
314 // false is returned
6a488035
TO
315 require_once 'DB.php';
316
317 $config = CRM_Core_Config::singleton();
318
319 $dbDrupal = DB::connect($config->userFrameworkDSN);
320 if (DB::isError($dbDrupal)) {
321 CRM_Core_Error::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
322 }
323
324 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
353ffa53
TO
325 $dbpassword = md5($password);
326 $name = $dbDrupal->escapeSimple($strtolower($name));
348754d5
TO
327 $userFrameworkUsersTableName = $this->getUsersTableName();
328 $sql = 'SELECT u.* FROM ' . $userFrameworkUsersTableName . " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
353ffa53 329 $query = $dbDrupal->query($sql);
6a488035
TO
330
331 $user = NULL;
332 // need to change this to make sure we matched only one row
333 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC)) {
334 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
335 $contactID = CRM_Core_BAO_UFMatch::getContactId($row['uid']);
336 if (!$contactID) {
337 return FALSE;
338 }
ae5ffbb7
TO
339 else {
340 //success
6a488035 341 if ($loadCMSBootstrap) {
be2fb01f 342 $bootStrapParams = [];
6a488035 343 if ($name && $password) {
be2fb01f 344 $bootStrapParams = [
353ffa53
TO
345 'name' => $name,
346 'pass' => $password,
be2fb01f 347 ];
6a488035
TO
348 }
349 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
350 }
be2fb01f 351 return [$contactID, $row['uid'], mt_rand()];
a5ecff8d 352 }
6a488035
TO
353 }
354 return FALSE;
355 }
356
f4aaa82a 357 /**
17f443df 358 * @inheritDoc
6a488035 359 */
00be9182 360 public function loadUser($username) {
6a488035 361 global $user;
be2fb01f 362 $user = user_load(['name' => $username]);
6a488035
TO
363 if (empty($user->uid)) {
364 return FALSE;
365 }
366
367 $uid = $user->uid;
368 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
369
370 // lets store contact id and user id in session
371 $session = CRM_Core_Session::singleton();
372 $session->set('ufID', $uid);
373 $session->set('userID', $contact_id);
374 return TRUE;
375 }
376
82d9c21e 377 /**
53980972 378 * Perform any post login activities required by the UF -
379 * e.g. for drupal : records a watchdog message about the new session,
380 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
e43cc689 381 *
ae5ffbb7 382 * @param array $params
95d68223
TO
383 *
384 * FIXME: Document values accepted/required by $params
53980972 385 */
be2fb01f 386 public function userLoginFinalize($params = []) {
53980972 387 user_authenticate_finalize($params);
82d9c21e 388 }
389
46b6363c 390 /**
fe482240 391 * Determine the native ID of the CMS user.
46b6363c 392 *
100fef9d 393 * @param string $username
e97c66ff 394 * @return int|null
46b6363c 395 */
00be9182 396 public function getUfId($username) {
be2fb01f 397 $user = user_load(['name' => $username]);
46b6363c
TO
398 if (empty($user->uid)) {
399 return NULL;
400 }
401 return $user->uid;
402 }
403
6a488035 404 /**
17f443df 405 * @inheritDoc
5bc392e6 406 */
00be9182 407 public function logout() {
6a488035
TO
408 module_load_include('inc', 'user', 'user.pages');
409 return user_logout();
410 }
411
6a488035 412 /**
fe482240 413 * Load drupal bootstrap.
6a488035 414 *
77855840
TO
415 * @param array $params
416 * Either uid, or name & pass.
417 * @param bool $loadUser
418 * Boolean Require CMS user load.
419 * @param bool $throwError
420 * If true, print error on failure and exit.
421 * @param bool|string $realPath path to script
f4aaa82a
EM
422 *
423 * @return bool
6a488035 424 */
be2fb01f 425 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
6a488035
TO
426 //take the cms root path.
427 $cmsPath = $this->cmsRootPath($realPath);
4459cd26 428
6a488035 429 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
4459cd26
CB
430 if ($throwError) {
431 echo '<br />Sorry, could not locate bootstrap.inc\n';
432 exit();
433 }
434 return FALSE;
6a488035 435 }
4459cd26 436 // load drupal bootstrap
6a488035 437 chdir($cmsPath);
4459cd26
CB
438 define('DRUPAL_ROOT', $cmsPath);
439
440 // For drupal multi-site CRM-11313
441 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
442 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
443 if (!empty($matches[1])) {
444 $_SERVER['HTTP_HOST'] = $matches[1];
445 }
446 }
6a488035 447 require_once 'includes/bootstrap.inc';
38507482 448 // @ to suppress notices eg 'DRUPALFOO already defined'.
6a488035
TO
449 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
450
4459cd26
CB
451 // explicitly setting error reporting, since we cannot handle drupal related notices
452 error_reporting(1);
a5ecff8d 453 if (!function_exists('module_exists') || !module_exists('civicrm')) {
4459cd26
CB
454 if ($throwError) {
455 echo '<br />Sorry, could not load drupal bootstrap.';
456 exit();
457 }
458 return FALSE;
6a488035 459 }
a5ecff8d 460
4459cd26
CB
461 // seems like we've bootstrapped drupal
462 $config = CRM_Core_Config::singleton();
463
6a488035
TO
464 // lets also fix the clean url setting
465 // CRM-6948
466 $config->cleanURL = (int) variable_get('clean_url', '0');
467
468 // we need to call the config hook again, since we now know
469 // all the modules that are listening on it, does not apply
470 // to J! and WP as yet
471 // CRM-8655
472 CRM_Utils_Hook::config($config);
473
474 if (!$loadUser) {
475 return TRUE;
476 }
95915c38 477 global $user;
4459cd26
CB
478 // If $uid is passed in, authentication has been done already.
479 $uid = CRM_Utils_Array::value('uid', $params);
480 if (!$uid) {
481 //load user, we need to check drupal permissions.
482 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
483 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
484
485 if ($name) {
be2fb01f 486 $user = user_authenticate(['name' => $name, 'pass' => $pass]);
95915c38 487 if (!$user->uid) {
4459cd26
CB
488 if ($throwError) {
489 echo '<br />Sorry, unrecognized username or password.';
490 exit();
491 }
492 return FALSE;
493 }
95915c38
E
494 else {
495 return TRUE;
496 }
6a488035
TO
497 }
498 }
4459cd26
CB
499
500 if ($uid) {
501 $account = user_load($uid);
502 if ($account && $account->uid) {
6a488035 503 $user = $account;
4459cd26 504 return TRUE;
6a488035
TO
505 }
506 }
4459cd26
CB
507
508 if ($throwError) {
509 echo '<br />Sorry, can not load CMS user account.';
510 exit();
511 }
512
513 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
514 // which means that define(CIVICRM_CLEANURL) was correctly set.
515 // So we correct it
516 $config = CRM_Core_Config::singleton();
e7292422 517 $config->cleanURL = (int) variable_get('clean_url', '0');
4459cd26
CB
518
519 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
520 CRM_Utils_Hook::config($config);
521
522 return FALSE;
6a488035
TO
523 }
524
a5ecff8d 525 /**
ea3ddccf 526 * Get CMS root path.
527 *
528 * @param string $scriptFilename
529 *
530 * @return null|string
a5ecff8d 531 */
00be9182 532 public function cmsRootPath($scriptFilename = NULL) {
6a488035
TO
533 $cmsRoot = $valid = NULL;
534
535 if (!is_null($scriptFilename)) {
536 $path = $scriptFilename;
537 }
538 else {
539 $path = $_SERVER['SCRIPT_FILENAME'];
540 }
a5ecff8d 541
6a488035
TO
542 if (function_exists('drush_get_context')) {
543 // drush anyway takes care of multisite install etc
544 return drush_get_context('DRUSH_DRUPAL_ROOT');
545 }
a93a0366
TO
546
547 global $civicrm_paths;
548 if (!empty($civicrm_paths['cms.root']['path'])) {
549 return $civicrm_paths['cms.root']['path'];
550 }
551
6a488035
TO
552 // CRM-7582
553 $pathVars = explode('/',
554 str_replace('//', '/',
555 str_replace('\\', '/', $path)
556 )
557 );
558
559 //lets store first var,
560 //need to get back for windows.
561 $firstVar = array_shift($pathVars);
562
563 //lets remove sript name to reduce one iteration.
564 array_pop($pathVars);
565
566 //CRM-7429 --do check for upper most 'includes' dir,
567 //which would effectually work for multisite installation.
568 do {
569 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
570 $cmsIncludePath = "$cmsRoot/includes";
948d11bf 571 // Stop if we found bootstrap.
f81c7606 572 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
6a488035
TO
573 $valid = TRUE;
574 break;
575 }
576 //remove one directory level.
577 array_pop($pathVars);
578 } while (count($pathVars));
579
580 return ($valid) ? $cmsRoot : NULL;
581 }
582
583 /**
17f443df 584 * @inheritDoc
6a488035
TO
585 */
586 public function isUserLoggedIn() {
587 $isloggedIn = FALSE;
588 if (function_exists('user_is_logged_in')) {
589 $isloggedIn = user_is_logged_in();
590 }
591
592 return $isloggedIn;
593 }
594
595 /**
17f443df 596 * @inheritDoc
6a488035
TO
597 */
598 public function getLoggedInUfID() {
599 $ufID = NULL;
600 if (function_exists('user_is_logged_in') &&
601 user_is_logged_in() &&
602 function_exists('user_uid_optional_to_arg')
603 ) {
be2fb01f 604 $ufID = user_uid_optional_to_arg([]);
6a488035
TO
605 }
606
607 return $ufID;
608 }
609
610 /**
17f443df 611 * @inheritDoc
6a488035 612 */
00be9182 613 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
6a488035
TO
614 if (empty($url)) {
615 return $url;
616 }
617
b44e3f84 618 //up to d6 only, already we have code in place for d7
6a488035
TO
619 $config = CRM_Core_Config::singleton();
620 if (function_exists('variable_get') &&
621 module_exists('locale')
622 ) {
623 global $language;
624
625 //get the mode.
626 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE);
627
628 //url prefix / path.
629 if (isset($language->prefix) &&
630 $language->prefix &&
be2fb01f 631 in_array($mode, [
6a488035 632 LANGUAGE_NEGOTIATION_PATH,
353ffa53 633 LANGUAGE_NEGOTIATION_PATH_DEFAULT,
be2fb01f 634 ])
6a488035
TO
635 ) {
636
637 if ($addLanguagePart) {
638 $url .= $language->prefix . '/';
639 }
640 if ($removeLanguagePart) {
641 $url = str_replace("/{$language->prefix}/", '/', $url);
642 }
643 }
644 if (isset($language->domain) &&
645 $language->domain &&
646 $mode == LANGUAGE_NEGOTIATION_DOMAIN
647 ) {
648
649 if ($addLanguagePart) {
650 $url = CRM_Utils_File::addTrailingSlash($language->domain, '/');
651 }
652 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
653 $url = str_replace('\\', '/', $url);
654 $parseUrl = parse_url($url);
655
656 //kinda hackish but not sure how to do it right
657 //hope http_build_url() will help at some point.
658 if (is_array($parseUrl) && !empty($parseUrl)) {
353ffa53
TO
659 $urlParts = explode('/', $url);
660 $hostKey = array_search($parseUrl['host'], $urlParts);
661 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
6a488035 662 $urlParts[$hostKey] = $ufUrlParts['host'];
353ffa53 663 $url = implode('/', $urlParts);
6a488035
TO
664 }
665 }
666 }
667 }
668
669 return $url;
670 }
671
672 /**
673 * Find any users/roles/security-principals with the given permission
674 * and replace it with one or more permissions.
675 *
5a4f6742
CW
676 * @param string $oldPerm
677 * @param array $newPerms
77855840 678 * Array, strings.
6a488035 679 */
00be9182 680 public function replacePermission($oldPerm, $newPerms) {
6a488035
TO
681 $roles = user_roles(FALSE, $oldPerm);
682 foreach ($roles as $rid => $roleName) {
683 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
684 $perms = drupal_map_assoc(explode(', ', $permList));
685 unset($perms[$oldPerm]);
686 $perms = $perms + drupal_map_assoc($newPerms);
687 $permList = implode(', ', $perms);
688 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
e70a7fc0 689 /* @codingStandardsIgnoreStart
6a488035
TO
690 if ( ! empty( $roles ) ) {
691 $rids = implode(',', array_keys($roles));
692 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
693 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
e70a7fc0
TO
694 $oldPerm, implode(', ', $newPerms) );
695 @codingStandardsIgnoreEnd */
6a488035
TO
696 }
697 }
698
699 /**
66e42142 700 * @inheritDoc
6a488035 701 */
00be9182 702 public function getModules() {
be2fb01f 703 $result = [];
6a488035
TO
704 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
705 while ($row = db_fetch_object($q)) {
706 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
707 }
708 return $result;
709 }
710
711 /**
17f443df 712 * @inheritDoc
6a488035
TO
713 */
714 public function getLoginURL($destination = '') {
715 $config = CRM_Core_Config::singleton();
716 $loginURL = $config->userFrameworkBaseURL;
717 $loginURL .= 'user';
718 if (!empty($destination)) {
719 // append destination so user is returned to form they came from after login
720 $loginURL .= '?destination=' . urlencode($destination);
721 }
722 return $loginURL;
723 }
724
d761c4d8 725 /**
fe482240 726 * Wrapper for og_membership creation.
d761c4d8 727 *
77855840
TO
728 * @param int $ogID
729 * Organic Group ID.
730 * @param int $drupalID
731 * Drupal User ID.
6a488035 732 */
9b873358 733 public function og_membership_create($ogID, $drupalID) {
be2fb01f 734 og_save_subscription($ogID, $drupalID, ['is_active' => 1]);
6a488035
TO
735 }
736
737 /**
fe482240 738 * Wrapper for og_membership deletion.
d761c4d8 739 *
77855840
TO
740 * @param int $ogID
741 * Organic Group ID.
742 * @param int $drupalID
743 * Drupal User ID.
6a488035 744 */
00be9182 745 public function og_membership_delete($ogID, $drupalID) {
481a74f4 746 og_delete_subscription($ogID, $drupalID);
6a488035
TO
747 }
748
5a604d61 749 /**
17f443df 750 * @inheritDoc
5a604d61 751 */
00be9182 752 public function getTimeZoneString() {
5a604d61 753 global $user;
e41775f6 754 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
755 if (variable_get('configurable_timezones', 1) && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
5a604d61 756 $timezone = $user->timezone;
0db6c3e1
TO
757 }
758 else {
e7292422 759 $timezone = variable_get('date_default_timezone', NULL);
5a604d61 760 }
1c642d5c
FG
761
762 // Retrieved timezone will be represented as GMT offset in seconds but, according
763 // to the doc for the overridden method, ought to be returned as a region string
764 // (e.g., America/Havana).
765 if (strlen($timezone)) {
eb4185e9 766 $timezone = timezone_name_from_abbr("", (int) $timezone);
1c642d5c
FG
767 }
768
48ec57ab
TO
769 if (!$timezone) {
770 $timezone = parent::getTimeZoneString();
5a604d61 771 }
1c642d5c 772
48ec57ab 773 return $timezone;
5a604d61
E
774 }
775
d42a224c
CW
776 /**
777 * @inheritDoc
778 */
779 public function setHttpHeader($name, $value) {
780 drupal_set_header("$name: $value");
781 }
782
03d5592a
CW
783 /**
784 * @inheritDoc
785 */
786 public function synchronizeUsers() {
787 $config = CRM_Core_Config::singleton();
788 if (PHP_SAPI != 'cli') {
789 set_time_limit(300);
790 }
be2fb01f 791 $rows = [];
03d5592a
CW
792 $id = 'uid';
793 $mail = 'mail';
794 $name = 'name';
795
796 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
797
798 while ($row = db_fetch_array($result)) {
799 $rows[] = $row;
800 }
801
802 $user = new StdClass();
803 $uf = $config->userFramework;
804 $contactCount = 0;
805 $contactCreated = 0;
806 $contactMatching = 0;
807 foreach ($rows as $row) {
808 $user->$id = $row[$id];
809 $user->$mail = $row[$mail];
810 $user->$name = $row[$name];
811 $contactCount++;
812 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row[$id], $row[$mail], $uf, 1, 'Individual', TRUE)) {
813 $contactCreated++;
814 }
815 else {
816 $contactMatching++;
817 }
03d5592a
CW
818 }
819
be2fb01f 820 return [
03d5592a
CW
821 'contactCount' => $contactCount,
822 'contactMatching' => $contactMatching,
823 'contactCreated' => $contactCreated,
be2fb01f 824 ];
03d5592a
CW
825 }
826
6a488035 827}