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