Merge pull request #15968 from eileenmcnaughton/bom
[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)) {
b67a6d82
E
168 $dbName = CRM_Utils_Array::value('name', $row);
169 $dbEmail = CRM_Utils_Array::value('mail', $row);
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
303 $dbDrupal = DB::connect($config->userFrameworkDSN);
304 if (DB::isError($dbDrupal)) {
309310bf 305 throw new CRM_Core_Exception("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
6a488035
TO
306 }
307
308 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
353ffa53
TO
309 $dbpassword = md5($password);
310 $name = $dbDrupal->escapeSimple($strtolower($name));
348754d5
TO
311 $userFrameworkUsersTableName = $this->getUsersTableName();
312 $sql = 'SELECT u.* FROM ' . $userFrameworkUsersTableName . " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
353ffa53 313 $query = $dbDrupal->query($sql);
6a488035
TO
314
315 $user = NULL;
316 // need to change this to make sure we matched only one row
317 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC)) {
318 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
319 $contactID = CRM_Core_BAO_UFMatch::getContactId($row['uid']);
320 if (!$contactID) {
321 return FALSE;
322 }
ae5ffbb7
TO
323 else {
324 //success
6a488035 325 if ($loadCMSBootstrap) {
be2fb01f 326 $bootStrapParams = [];
6a488035 327 if ($name && $password) {
be2fb01f 328 $bootStrapParams = [
353ffa53
TO
329 'name' => $name,
330 'pass' => $password,
be2fb01f 331 ];
6a488035
TO
332 }
333 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
334 }
be2fb01f 335 return [$contactID, $row['uid'], mt_rand()];
a5ecff8d 336 }
6a488035
TO
337 }
338 return FALSE;
339 }
340
f4aaa82a 341 /**
17f443df 342 * @inheritDoc
6a488035 343 */
00be9182 344 public function loadUser($username) {
6a488035 345 global $user;
be2fb01f 346 $user = user_load(['name' => $username]);
6a488035
TO
347 if (empty($user->uid)) {
348 return FALSE;
349 }
350
351 $uid = $user->uid;
352 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
353
354 // lets store contact id and user id in session
355 $session = CRM_Core_Session::singleton();
356 $session->set('ufID', $uid);
357 $session->set('userID', $contact_id);
358 return TRUE;
359 }
360
82d9c21e 361 /**
53980972 362 * Perform any post login activities required by the UF -
363 * e.g. for drupal : records a watchdog message about the new session,
364 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
e43cc689 365 *
ae5ffbb7 366 * @param array $params
95d68223
TO
367 *
368 * FIXME: Document values accepted/required by $params
53980972 369 */
be2fb01f 370 public function userLoginFinalize($params = []) {
53980972 371 user_authenticate_finalize($params);
82d9c21e 372 }
373
46b6363c 374 /**
fe482240 375 * Determine the native ID of the CMS user.
46b6363c 376 *
100fef9d 377 * @param string $username
e97c66ff 378 * @return int|null
46b6363c 379 */
00be9182 380 public function getUfId($username) {
be2fb01f 381 $user = user_load(['name' => $username]);
46b6363c
TO
382 if (empty($user->uid)) {
383 return NULL;
384 }
385 return $user->uid;
386 }
387
6a488035 388 /**
17f443df 389 * @inheritDoc
5bc392e6 390 */
00be9182 391 public function logout() {
6a488035
TO
392 module_load_include('inc', 'user', 'user.pages');
393 return user_logout();
394 }
395
6a488035 396 /**
fe482240 397 * Load drupal bootstrap.
6a488035 398 *
77855840
TO
399 * @param array $params
400 * Either uid, or name & pass.
401 * @param bool $loadUser
402 * Boolean Require CMS user load.
403 * @param bool $throwError
404 * If true, print error on failure and exit.
405 * @param bool|string $realPath path to script
f4aaa82a
EM
406 *
407 * @return bool
6a488035 408 */
be2fb01f 409 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
6a488035
TO
410 //take the cms root path.
411 $cmsPath = $this->cmsRootPath($realPath);
4459cd26 412
6a488035 413 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
4459cd26
CB
414 if ($throwError) {
415 echo '<br />Sorry, could not locate bootstrap.inc\n';
416 exit();
417 }
418 return FALSE;
6a488035 419 }
4459cd26 420 // load drupal bootstrap
6a488035 421 chdir($cmsPath);
4459cd26
CB
422 define('DRUPAL_ROOT', $cmsPath);
423
424 // For drupal multi-site CRM-11313
425 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
426 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
427 if (!empty($matches[1])) {
428 $_SERVER['HTTP_HOST'] = $matches[1];
429 }
430 }
6a488035 431 require_once 'includes/bootstrap.inc';
38507482 432 // @ to suppress notices eg 'DRUPALFOO already defined'.
6a488035
TO
433 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
434
4459cd26
CB
435 // explicitly setting error reporting, since we cannot handle drupal related notices
436 error_reporting(1);
a5ecff8d 437 if (!function_exists('module_exists') || !module_exists('civicrm')) {
4459cd26
CB
438 if ($throwError) {
439 echo '<br />Sorry, could not load drupal bootstrap.';
440 exit();
441 }
442 return FALSE;
6a488035 443 }
a5ecff8d 444
4459cd26
CB
445 // seems like we've bootstrapped drupal
446 $config = CRM_Core_Config::singleton();
447
6a488035
TO
448 // lets also fix the clean url setting
449 // CRM-6948
450 $config->cleanURL = (int) variable_get('clean_url', '0');
451
452 // we need to call the config hook again, since we now know
453 // all the modules that are listening on it, does not apply
454 // to J! and WP as yet
455 // CRM-8655
456 CRM_Utils_Hook::config($config);
457
458 if (!$loadUser) {
459 return TRUE;
460 }
95915c38 461 global $user;
4459cd26
CB
462 // If $uid is passed in, authentication has been done already.
463 $uid = CRM_Utils_Array::value('uid', $params);
464 if (!$uid) {
465 //load user, we need to check drupal permissions.
466 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
467 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
468
469 if ($name) {
be2fb01f 470 $user = user_authenticate(['name' => $name, 'pass' => $pass]);
95915c38 471 if (!$user->uid) {
4459cd26
CB
472 if ($throwError) {
473 echo '<br />Sorry, unrecognized username or password.';
474 exit();
475 }
476 return FALSE;
477 }
95915c38
E
478 else {
479 return TRUE;
480 }
6a488035
TO
481 }
482 }
4459cd26
CB
483
484 if ($uid) {
485 $account = user_load($uid);
486 if ($account && $account->uid) {
6a488035 487 $user = $account;
4459cd26 488 return TRUE;
6a488035
TO
489 }
490 }
4459cd26
CB
491
492 if ($throwError) {
493 echo '<br />Sorry, can not load CMS user account.';
494 exit();
495 }
496
497 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
498 // which means that define(CIVICRM_CLEANURL) was correctly set.
499 // So we correct it
500 $config = CRM_Core_Config::singleton();
e7292422 501 $config->cleanURL = (int) variable_get('clean_url', '0');
4459cd26
CB
502
503 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
504 CRM_Utils_Hook::config($config);
505
506 return FALSE;
6a488035
TO
507 }
508
a5ecff8d 509 /**
ea3ddccf 510 * Get CMS root path.
511 *
512 * @param string $scriptFilename
513 *
514 * @return null|string
a5ecff8d 515 */
00be9182 516 public function cmsRootPath($scriptFilename = NULL) {
6a488035
TO
517 $cmsRoot = $valid = NULL;
518
519 if (!is_null($scriptFilename)) {
520 $path = $scriptFilename;
521 }
522 else {
523 $path = $_SERVER['SCRIPT_FILENAME'];
524 }
a5ecff8d 525
6a488035
TO
526 if (function_exists('drush_get_context')) {
527 // drush anyway takes care of multisite install etc
528 return drush_get_context('DRUSH_DRUPAL_ROOT');
529 }
a93a0366
TO
530
531 global $civicrm_paths;
532 if (!empty($civicrm_paths['cms.root']['path'])) {
533 return $civicrm_paths['cms.root']['path'];
534 }
535
6a488035
TO
536 // CRM-7582
537 $pathVars = explode('/',
538 str_replace('//', '/',
539 str_replace('\\', '/', $path)
540 )
541 );
542
543 //lets store first var,
544 //need to get back for windows.
545 $firstVar = array_shift($pathVars);
546
547 //lets remove sript name to reduce one iteration.
548 array_pop($pathVars);
549
550 //CRM-7429 --do check for upper most 'includes' dir,
551 //which would effectually work for multisite installation.
552 do {
553 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
554 $cmsIncludePath = "$cmsRoot/includes";
948d11bf 555 // Stop if we found bootstrap.
f81c7606 556 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
6a488035
TO
557 $valid = TRUE;
558 break;
559 }
560 //remove one directory level.
561 array_pop($pathVars);
562 } while (count($pathVars));
563
564 return ($valid) ? $cmsRoot : NULL;
565 }
566
567 /**
17f443df 568 * @inheritDoc
6a488035
TO
569 */
570 public function isUserLoggedIn() {
571 $isloggedIn = FALSE;
572 if (function_exists('user_is_logged_in')) {
573 $isloggedIn = user_is_logged_in();
574 }
575
576 return $isloggedIn;
577 }
578
579 /**
17f443df 580 * @inheritDoc
6a488035
TO
581 */
582 public function getLoggedInUfID() {
583 $ufID = NULL;
584 if (function_exists('user_is_logged_in') &&
585 user_is_logged_in() &&
586 function_exists('user_uid_optional_to_arg')
587 ) {
be2fb01f 588 $ufID = user_uid_optional_to_arg([]);
6a488035
TO
589 }
590
591 return $ufID;
592 }
593
594 /**
17f443df 595 * @inheritDoc
6a488035 596 */
00be9182 597 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
6a488035
TO
598 if (empty($url)) {
599 return $url;
600 }
601
b44e3f84 602 //up to d6 only, already we have code in place for d7
6a488035
TO
603 $config = CRM_Core_Config::singleton();
604 if (function_exists('variable_get') &&
605 module_exists('locale')
606 ) {
607 global $language;
608
609 //get the mode.
610 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE);
611
612 //url prefix / path.
613 if (isset($language->prefix) &&
614 $language->prefix &&
be2fb01f 615 in_array($mode, [
6a488035 616 LANGUAGE_NEGOTIATION_PATH,
353ffa53 617 LANGUAGE_NEGOTIATION_PATH_DEFAULT,
be2fb01f 618 ])
6a488035
TO
619 ) {
620
621 if ($addLanguagePart) {
622 $url .= $language->prefix . '/';
623 }
624 if ($removeLanguagePart) {
625 $url = str_replace("/{$language->prefix}/", '/', $url);
626 }
627 }
628 if (isset($language->domain) &&
629 $language->domain &&
630 $mode == LANGUAGE_NEGOTIATION_DOMAIN
631 ) {
632
633 if ($addLanguagePart) {
634 $url = CRM_Utils_File::addTrailingSlash($language->domain, '/');
635 }
636 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
637 $url = str_replace('\\', '/', $url);
638 $parseUrl = parse_url($url);
639
640 //kinda hackish but not sure how to do it right
641 //hope http_build_url() will help at some point.
642 if (is_array($parseUrl) && !empty($parseUrl)) {
353ffa53
TO
643 $urlParts = explode('/', $url);
644 $hostKey = array_search($parseUrl['host'], $urlParts);
645 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
6a488035 646 $urlParts[$hostKey] = $ufUrlParts['host'];
353ffa53 647 $url = implode('/', $urlParts);
6a488035
TO
648 }
649 }
650 }
651 }
652
653 return $url;
654 }
655
656 /**
657 * Find any users/roles/security-principals with the given permission
658 * and replace it with one or more permissions.
659 *
5a4f6742
CW
660 * @param string $oldPerm
661 * @param array $newPerms
77855840 662 * Array, strings.
6a488035 663 */
00be9182 664 public function replacePermission($oldPerm, $newPerms) {
6a488035
TO
665 $roles = user_roles(FALSE, $oldPerm);
666 foreach ($roles as $rid => $roleName) {
667 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
668 $perms = drupal_map_assoc(explode(', ', $permList));
669 unset($perms[$oldPerm]);
670 $perms = $perms + drupal_map_assoc($newPerms);
671 $permList = implode(', ', $perms);
672 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
e70a7fc0 673 /* @codingStandardsIgnoreStart
6a488035
TO
674 if ( ! empty( $roles ) ) {
675 $rids = implode(',', array_keys($roles));
676 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
677 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
e70a7fc0
TO
678 $oldPerm, implode(', ', $newPerms) );
679 @codingStandardsIgnoreEnd */
6a488035
TO
680 }
681 }
682
683 /**
66e42142 684 * @inheritDoc
6a488035 685 */
00be9182 686 public function getModules() {
be2fb01f 687 $result = [];
6a488035
TO
688 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
689 while ($row = db_fetch_object($q)) {
690 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
691 }
692 return $result;
693 }
694
695 /**
17f443df 696 * @inheritDoc
6a488035
TO
697 */
698 public function getLoginURL($destination = '') {
699 $config = CRM_Core_Config::singleton();
700 $loginURL = $config->userFrameworkBaseURL;
701 $loginURL .= 'user';
702 if (!empty($destination)) {
703 // append destination so user is returned to form they came from after login
704 $loginURL .= '?destination=' . urlencode($destination);
705 }
706 return $loginURL;
707 }
708
d761c4d8 709 /**
fe482240 710 * Wrapper for og_membership creation.
d761c4d8 711 *
77855840
TO
712 * @param int $ogID
713 * Organic Group ID.
714 * @param int $drupalID
715 * Drupal User ID.
6a488035 716 */
9b873358 717 public function og_membership_create($ogID, $drupalID) {
be2fb01f 718 og_save_subscription($ogID, $drupalID, ['is_active' => 1]);
6a488035
TO
719 }
720
721 /**
fe482240 722 * Wrapper for og_membership deletion.
d761c4d8 723 *
77855840
TO
724 * @param int $ogID
725 * Organic Group ID.
726 * @param int $drupalID
727 * Drupal User ID.
6a488035 728 */
00be9182 729 public function og_membership_delete($ogID, $drupalID) {
481a74f4 730 og_delete_subscription($ogID, $drupalID);
6a488035
TO
731 }
732
5a604d61 733 /**
17f443df 734 * @inheritDoc
5a604d61 735 */
00be9182 736 public function getTimeZoneString() {
5a604d61 737 global $user;
e41775f6 738 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
739 if (variable_get('configurable_timezones', 1) && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
5a604d61 740 $timezone = $user->timezone;
0db6c3e1
TO
741 }
742 else {
e7292422 743 $timezone = variable_get('date_default_timezone', NULL);
5a604d61 744 }
1c642d5c
FG
745
746 // Retrieved timezone will be represented as GMT offset in seconds but, according
747 // to the doc for the overridden method, ought to be returned as a region string
748 // (e.g., America/Havana).
749 if (strlen($timezone)) {
eb4185e9 750 $timezone = timezone_name_from_abbr("", (int) $timezone);
1c642d5c
FG
751 }
752
48ec57ab
TO
753 if (!$timezone) {
754 $timezone = parent::getTimeZoneString();
5a604d61 755 }
1c642d5c 756
48ec57ab 757 return $timezone;
5a604d61
E
758 }
759
d42a224c
CW
760 /**
761 * @inheritDoc
762 */
763 public function setHttpHeader($name, $value) {
764 drupal_set_header("$name: $value");
765 }
766
03d5592a
CW
767 /**
768 * @inheritDoc
769 */
770 public function synchronizeUsers() {
771 $config = CRM_Core_Config::singleton();
772 if (PHP_SAPI != 'cli') {
773 set_time_limit(300);
774 }
be2fb01f 775 $rows = [];
03d5592a
CW
776 $id = 'uid';
777 $mail = 'mail';
778 $name = 'name';
779
780 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
781
782 while ($row = db_fetch_array($result)) {
783 $rows[] = $row;
784 }
785
786 $user = new StdClass();
787 $uf = $config->userFramework;
788 $contactCount = 0;
789 $contactCreated = 0;
790 $contactMatching = 0;
791 foreach ($rows as $row) {
792 $user->$id = $row[$id];
793 $user->$mail = $row[$mail];
794 $user->$name = $row[$name];
795 $contactCount++;
796 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row[$id], $row[$mail], $uf, 1, 'Individual', TRUE)) {
797 $contactCreated++;
798 }
799 else {
800 $contactMatching++;
801 }
03d5592a
CW
802 }
803
be2fb01f 804 return [
03d5592a
CW
805 'contactCount' => $contactCount,
806 'contactMatching' => $contactMatching,
807 'contactCreated' => $contactCreated,
be2fb01f 808 ];
03d5592a
CW
809 }
810
6a488035 811}