Remove ?last? instances of ->free() dev/core#562
[civicrm-core.git] / CRM / Utils / System / Drupal.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/**
35 * Drupal specific stuff goes here
36 */
9977c6f5 37class CRM_Utils_System_Drupal extends CRM_Utils_System_DrupalBase {
6a488035
TO
38
39 /**
17f443df 40 * @inheritDoc
6a488035 41 */
00be9182 42 public function createUser(&$params, $mail) {
88b91745 43 $form_state = form_state_defaults();
d0ffa3e4 44
be2fb01f 45 $form_state['input'] = [
6a488035
TO
46 'name' => $params['cms_name'],
47 'mail' => $params[$mail],
48 'op' => 'Create new account',
be2fb01f 49 ];
6a488035
TO
50
51 $admin = user_access('administer users');
52 if (!variable_get('user_email_verification', TRUE) || $admin) {
be2fb01f 53 $form_state['input']['pass'] = ['pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']];
6a488035
TO
54 }
55
9b873358 56 if (!empty($params['notify'])) {
6a488035
TO
57 $form_state['input']['notify'] = $params['notify'];
58 }
59
60 $form_state['rebuild'] = FALSE;
61 $form_state['programmed'] = TRUE;
805b0f6e 62 $form_state['complete form'] = FALSE;
6a488035 63 $form_state['method'] = 'post';
be2fb01f 64 $form_state['build_info']['args'] = [];
41d551ad 65 /*
e70a7fc0
TO
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 */
41d551ad 70 $form_state['must_validate'] = TRUE;
6a488035
TO
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;
be2fb01f 79 $form['#array_parents'] = [];
805b0f6e 80 $form['#tree'] = FALSE;
6a488035
TO
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 }
a5ecff8d 88 return $form_state['user']->uid;
6a488035
TO
89 }
90
bb3a214a 91 /**
17f443df 92 * @inheritDoc
bb3a214a 93 */
00be9182 94 public function updateCMSName($ufID, $ufName) {
6a488035
TO
95 // CRM-5555
96 if (function_exists('user_load')) {
97 $user = user_load($ufID);
98 if ($user->mail != $ufName) {
be2fb01f 99 user_save($user, ['mail' => $ufName]);
6a488035
TO
100 $user = user_load($ufID);
101 }
102 }
103 }
104
105 /**
fe482240 106 * Check if username and email exists in the drupal db.
6a488035 107 *
77855840
TO
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'.
6a488035 114 */
00be9182 115 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
6a488035
TO
116 $config = CRM_Core_Config::singleton();
117
353ffa53
TO
118 $dao = new CRM_Core_DAO();
119 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
120 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
6a488035
TO
121 $errors = form_get_errors();
122 if ($errors) {
123 // unset drupal messages to avoid twice display of errors
124 unset($_SESSION['messages']);
125 }
126
a7488080 127 if (!empty($params['name'])) {
6a488035
TO
128 if ($nameError = user_validate_name($params['name'])) {
129 $errors['cms_name'] = $nameError;
130 }
131 else {
132 $uid = db_query(
133 "SELECT uid FROM {users} WHERE name = :name",
be2fb01f 134 [':name' => $params['name']]
6a488035
TO
135 )->fetchField();
136 if ((bool) $uid) {
be2fb01f 137 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
6a488035
TO
138 }
139 }
140 }
141
a7488080 142 if (!empty($params['mail'])) {
6a488035
TO
143 if ($emailError = user_validate_mail($params['mail'])) {
144 $errors[$emailName] = $emailError;
145 }
146 else {
147 $uid = db_query(
148 "SELECT uid FROM {users} WHERE mail = :mail",
be2fb01f 149 [':mail' => $params['mail']]
6a488035
TO
150 )->fetchField();
151 if ((bool) $uid) {
aaba8ae5 152 $resetUrl = url('user/password');
db18d815 153 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
be2fb01f 154 [1 => $params['mail'], 2 => $resetUrl]
6a488035
TO
155 );
156 }
157 }
158 }
159 }
160
d424ffde 161 /**
17f443df 162 * @inheritDoc
6a488035
TO
163 */
164 public function getLoginURL($destination = '') {
be2fb01f 165 $query = $destination ? ['destination' => $destination] : NULL;
cd2e7151 166 return CRM_Utils_System::url('user', $query, TRUE);
6a488035
TO
167 }
168
6a488035 169 /**
17f443df 170 * @inheritDoc
6a488035 171 */
00be9182 172 public function setTitle($title, $pageTitle = NULL) {
6a488035
TO
173 if (arg(0) == 'civicrm') {
174 if (!$pageTitle) {
175 $pageTitle = $title;
176 }
177
178 drupal_set_title($pageTitle, PASS_THROUGH);
179 }
180 }
181
182 /**
17f443df 183 * @inheritDoc
6a488035 184 */
00be9182 185 public function appendBreadCrumb($breadCrumbs) {
6a488035
TO
186 $breadCrumb = drupal_get_breadcrumb();
187
188 if (is_array($breadCrumbs)) {
189 foreach ($breadCrumbs as $crumbs) {
190 if (stripos($crumbs['url'], 'id%%')) {
be2fb01f 191 $args = ['cid', 'mid'];
6a488035
TO
192 foreach ($args as $a) {
193 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
194 FALSE, NULL, $_GET
195 );
196 if ($val) {
197 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
198 }
199 }
200 }
201 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
202 }
203 }
204 drupal_set_breadcrumb($breadCrumb);
205 }
206
207 /**
17f443df 208 * @inheritDoc
6a488035 209 */
00be9182 210 public function resetBreadCrumb() {
be2fb01f 211 $bc = [];
6a488035
TO
212 drupal_set_breadcrumb($bc);
213 }
214
215 /**
17f443df 216 * @inheritDoc
6a488035 217 */
00be9182 218 public function addHTMLHead($header) {
6a488035
TO
219 static $count = 0;
220 if (!empty($header)) {
221 $key = 'civi_' . ++$count;
be2fb01f 222 $data = [
6a488035
TO
223 '#type' => 'markup',
224 '#markup' => $header,
be2fb01f 225 ];
6a488035
TO
226 drupal_add_html_head($data, $key);
227 }
228 }
229
230 /**
17f443df 231 * @inheritDoc
6a488035
TO
232 */
233 public function addScriptUrl($url, $region) {
be2fb01f 234 $params = ['group' => JS_LIBRARY, 'weight' => 10];
6a488035
TO
235 switch ($region) {
236 case 'html-header':
237 case 'page-footer':
238 $params['scope'] = substr($region, 5);
239 break;
e7292422 240
6a488035
TO
241 default:
242 return FALSE;
243 }
244 // If the path is within the drupal directory we can use the more efficient 'file' setting
42e1a97c 245 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
6a488035
TO
246 drupal_add_js($url, $params);
247 return TRUE;
248 }
249
250 /**
17f443df 251 * @inheritDoc
6a488035
TO
252 */
253 public function addScript($code, $region) {
be2fb01f 254 $params = ['type' => 'inline', 'group' => JS_LIBRARY, 'weight' => 10];
6a488035
TO
255 switch ($region) {
256 case 'html-header':
257 case 'page-footer':
258 $params['scope'] = substr($region, 5);
259 break;
e7292422 260
6a488035
TO
261 default:
262 return FALSE;
263 }
264 drupal_add_js($code, $params);
265 return TRUE;
266 }
267
268 /**
17f443df 269 * @inheritDoc
6a488035
TO
270 */
271 public function addStyleUrl($url, $region) {
272 if ($region != 'html-header') {
273 return FALSE;
274 }
be2fb01f 275 $params = [];
6a488035 276 // If the path is within the drupal directory we can use the more efficient 'file' setting
42e1a97c 277 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
6a488035
TO
278 drupal_add_css($url, $params);
279 return TRUE;
280 }
281
282 /**
17f443df 283 * @inheritDoc
6a488035
TO
284 */
285 public function addStyle($code, $region) {
286 if ($region != 'html-header') {
287 return FALSE;
288 }
be2fb01f 289 $params = ['type' => 'inline'];
6a488035
TO
290 drupal_add_css($code, $params);
291 return TRUE;
292 }
293
6a488035 294 /**
17f443df 295 * @inheritDoc
6a488035 296 */
00be9182 297 public function mapConfigToSSL() {
6a488035
TO
298 global $base_url;
299 $base_url = str_replace('http://', 'https://', $base_url);
300 }
301
f2ac86d1 302 /**
303 * Get the name of the users table.
304 *
305 * @return string
306 */
348754d5
TO
307 protected function getUsersTableName() {
308 $userFrameworkUsersTableName = Civi::settings()->get('userFrameworkUsersTableName');
309 if (empty($userFrameworkUsersTableName)) {
310 $userFrameworkUsersTableName = 'users';
311 }
312 return $userFrameworkUsersTableName;
313 }
314
6a488035 315 /**
17f443df 316 * @inheritDoc
6a488035 317 */
17f443df 318 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
6a488035
TO
319 require_once 'DB.php';
320
321 $config = CRM_Core_Config::singleton();
322
323 $dbDrupal = DB::connect($config->userFrameworkDSN);
324 if (DB::isError($dbDrupal)) {
325 CRM_Core_Error::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
326 }
327
328 $account = $userUid = $userMail = NULL;
329 if ($loadCMSBootstrap) {
be2fb01f 330 $bootStrapParams = [];
6a488035 331 if ($name && $password) {
be2fb01f 332 $bootStrapParams = [
6a488035
TO
333 'name' => $name,
334 'pass' => $password,
be2fb01f 335 ];
6a488035
TO
336 }
337 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
338
339 global $user;
340 if ($user) {
341 $userUid = $user->uid;
342 $userMail = $user->mail;
343 }
344 }
345 else {
346 // CRM-8638
347 // SOAP cannot load drupal bootstrap and hence we do it the old way
348 // Contact CiviSMTP folks if we run into issues with this :)
349 $cmsPath = $config->userSystem->cmsRootPath($realPath);
350
e7292422
TO
351 require_once "$cmsPath/includes/bootstrap.inc";
352 require_once "$cmsPath/includes/password.inc";
6a488035
TO
353
354 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
353ffa53 355 $name = $dbDrupal->escapeSimple($strtolower($name));
348754d5 356 $userFrameworkUsersTableName = $this->getUsersTableName();
b27d1855 357
358 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
353ffa53 359 $sql = "
6a488035 360SELECT u.*
348754d5 361FROM {$userFrameworkUsersTableName} u
6a488035
TO
362WHERE LOWER(u.name) = '$name'
363AND u.status = 1
364";
365
366 $query = $dbDrupal->query($sql);
367 $row = $query->fetchRow(DB_FETCHMODE_ASSOC);
368
369 if ($row) {
370 $fakeDrupalAccount = drupal_anonymous_user();
371 $fakeDrupalAccount->name = $name;
372 $fakeDrupalAccount->pass = $row['pass'];
373 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
374 if ($passwordCheck) {
375 $userUid = $row['uid'];
376 $userMail = $row['mail'];
377 }
378 }
379 }
380
381 if ($userUid && $userMail) {
382 CRM_Core_BAO_UFMatch::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
383 $contactID = CRM_Core_BAO_UFMatch::getContactId($userUid);
384 if (!$contactID) {
385 return FALSE;
386 }
be2fb01f 387 return [$contactID, $userUid, mt_rand()];
6a488035
TO
388 }
389 return FALSE;
390 }
391
bb3a214a 392 /**
17f443df 393 * @inheritDoc
bb3a214a 394 */
00be9182 395 public function loadUser($username) {
6a488035
TO
396 global $user;
397
398 $user = user_load_by_name($username);
399
400 if (empty($user->uid)) {
401 return FALSE;
402 }
403
404 $uid = $user->uid;
405 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
406
407 // lets store contact id and user id in session
408 $session = CRM_Core_Session::singleton();
409 $session->set('ufID', $uid);
410 $session->set('userID', $contact_id);
411 return TRUE;
412 }
413
82d9c21e 414 /**
53980972 415 * Perform any post login activities required by the UF -
416 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
417 * calls hook_user op 'login' and generates a new session.
e43cc689 418 *
c301f76e 419 * @param array $params
95d68223
TO
420 *
421 * FIXME: Document values accepted/required by $params
53980972 422 */
be2fb01f 423 public function userLoginFinalize($params = []) {
53980972 424 user_login_finalize($params);
82d9c21e 425 }
426
46b6363c 427 /**
fe482240 428 * Determine the native ID of the CMS user.
46b6363c 429 *
100fef9d 430 * @param string $username
e97c66ff 431 * @return int|null
46b6363c 432 */
00be9182 433 public function getUfId($username) {
46b6363c
TO
434 $user = user_load_by_name($username);
435 if (empty($user->uid)) {
436 return NULL;
437 }
438 return $user->uid;
439 }
440
6a488035 441 /**
17f443df 442 * @inheritDoc
bb3a214a 443 */
00be9182 444 public function logout() {
6a488035
TO
445 module_load_include('inc', 'user', 'user.pages');
446 return user_logout();
447 }
448
6a488035 449 /**
fe482240 450 * Get the default location for CiviCRM blocks.
6a488035
TO
451 *
452 * @return string
453 */
00be9182 454 public function getDefaultBlockLocation() {
6a488035
TO
455 return 'sidebar_first';
456 }
457
6a488035 458 /**
fe482240 459 * Load drupal bootstrap.
6a488035 460 *
77855840
TO
461 * @param array $params
462 * Either uid, or name & pass.
463 * @param bool $loadUser
464 * Boolean Require CMS user load.
465 * @param bool $throwError
466 * If true, print error on failure and exit.
467 * @param bool|string $realPath path to script
f4aaa82a
EM
468 *
469 * @return bool
6a488035 470 */
be2fb01f 471 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
6a488035
TO
472 //take the cms root path.
473 $cmsPath = $this->cmsRootPath($realPath);
474
475 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
476 if ($throwError) {
de1a27d0 477 throw new Exception('Sorry, could not locate bootstrap.inc');
6a488035
TO
478 }
479 return FALSE;
480 }
481 // load drupal bootstrap
482 chdir($cmsPath);
483 define('DRUPAL_ROOT', $cmsPath);
484
485 // For drupal multi-site CRM-11313
486 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
487 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
488 if (!empty($matches[1])) {
489 $_SERVER['HTTP_HOST'] = $matches[1];
490 }
491 }
492 require_once 'includes/bootstrap.inc';
38507482
CB
493 // @ to suppress notices eg 'DRUPALFOO already defined'.
494 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
6a488035
TO
495
496 // explicitly setting error reporting, since we cannot handle drupal related notices
3ccadca3
ES
497 // @todo 1 = E_ERROR, but more to the point setting error reporting deep in code
498 // causes grief with debugging scripts
6a488035 499 error_reporting(1);
de1a27d0 500 if (!function_exists('module_exists')) {
6a488035 501 if ($throwError) {
de1a27d0
ES
502 throw new Exception('Sorry, could not load drupal bootstrap.');
503 }
504 return FALSE;
505 }
506 if (!module_exists('civicrm')) {
507 if ($throwError) {
508 throw new Exception('Sorry, drupal cannot find CiviCRM');
6a488035
TO
509 }
510 return FALSE;
511 }
512
513 // seems like we've bootstrapped drupal
514 $config = CRM_Core_Config::singleton();
515
6a488035
TO
516 // lets also fix the clean url setting
517 // CRM-6948
518 $config->cleanURL = (int) variable_get('clean_url', '0');
519
520 // we need to call the config hook again, since we now know
521 // all the modules that are listening on it, does not apply
522 // to J! and WP as yet
523 // CRM-8655
524 CRM_Utils_Hook::config($config);
525
526 if (!$loadUser) {
527 return TRUE;
528 }
529
530 $uid = CRM_Utils_Array::value('uid', $params);
531 if (!$uid) {
532 //load user, we need to check drupal permissions.
533 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
534 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
535
536 if ($name) {
537 $uid = user_authenticate($name, $pass);
538 if (!$uid) {
539 if ($throwError) {
de1a27d0 540 throw new Exception('Sorry, unrecognized username or password.');
6a488035
TO
541 }
542 return FALSE;
543 }
544 }
545 }
546
547 if ($uid) {
548 $account = user_load($uid);
549 if ($account && $account->uid) {
550 global $user;
551 $user = $account;
552 return TRUE;
553 }
554 }
555
556 if ($throwError) {
de1a27d0 557 throw new Exception('Sorry, can not load CMS user account.');
6a488035
TO
558 }
559
0af0e4c9
DL
560 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
561 // which means that define(CIVICRM_CLEANURL) was correctly set.
6a488035
TO
562 // So we correct it
563 $config = CRM_Core_Config::singleton();
e7292422 564 $config->cleanURL = (int) variable_get('clean_url', '0');
6a488035
TO
565
566 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
567 CRM_Utils_Hook::config($config);
568
569 return FALSE;
570 }
571
a5ecff8d 572 /**
ea3ddccf 573 * Get CMS root path.
574 *
575 * @param string $scriptFilename
576 *
577 * @return null|string
a5ecff8d 578 */
00be9182 579 public function cmsRootPath($scriptFilename = NULL) {
6a488035
TO
580 $cmsRoot = $valid = NULL;
581
582 if (!is_null($scriptFilename)) {
583 $path = $scriptFilename;
584 }
585 else {
586 $path = $_SERVER['SCRIPT_FILENAME'];
587 }
588
589 if (function_exists('drush_get_context')) {
590 // drush anyway takes care of multisite install etc
591 return drush_get_context('DRUSH_DRUPAL_ROOT');
592 }
d33e2f7d 593
594 global $civicrm_paths;
595 if (!empty($civicrm_paths['cms.root']['path'])) {
596 return $civicrm_paths['cms.root']['path'];
597 }
598
6a488035
TO
599 // CRM-7582
600 $pathVars = explode('/',
601 str_replace('//', '/',
602 str_replace('\\', '/', $path)
603 )
604 );
605
606 //lets store first var,
607 //need to get back for windows.
608 $firstVar = array_shift($pathVars);
609
e0e68bf4 610 // Remove the script name to remove an necessary iteration of the loop.
6a488035
TO
611 array_pop($pathVars);
612
948d11bf
CB
613 // CRM-7429 -- do check for uppermost 'includes' dir, which would
614 // work for multisite installation.
6a488035
TO
615 do {
616 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
617 $cmsIncludePath = "$cmsRoot/includes";
948d11bf 618 // Stop if we find bootstrap.
f81c7606 619 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
6a488035
TO
620 $valid = TRUE;
621 break;
622 }
623 //remove one directory level.
624 array_pop($pathVars);
625 } while (count($pathVars));
626
627 return ($valid) ? $cmsRoot : NULL;
628 }
629
630 /**
17f443df 631 * @inheritDoc
6a488035
TO
632 */
633 public function isUserLoggedIn() {
634 $isloggedIn = FALSE;
635 if (function_exists('user_is_logged_in')) {
636 $isloggedIn = user_is_logged_in();
637 }
638
639 return $isloggedIn;
640 }
641
642 /**
17f443df 643 * @inheritDoc
6a488035
TO
644 */
645 public function getLoggedInUfID() {
646 $ufID = NULL;
647 if (function_exists('user_is_logged_in') &&
648 user_is_logged_in() &&
649 function_exists('user_uid_optional_to_arg')
650 ) {
be2fb01f 651 $ufID = user_uid_optional_to_arg([]);
6a488035
TO
652 }
653
654 return $ufID;
655 }
656
657 /**
17f443df 658 * @inheritDoc
6a488035 659 */
00be9182 660 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
6a488035
TO
661 if (empty($url)) {
662 return $url;
663 }
664
665 //CRM-7803 -from d7 onward.
666 $config = CRM_Core_Config::singleton();
667 if (function_exists('variable_get') &&
668 module_exists('locale') &&
669 function_exists('language_negotiation_get')
670 ) {
671 global $language;
672
673 //does user configuration allow language
674 //support from the URL (Path prefix or domain)
675 if (language_negotiation_get('language') == 'locale-url') {
676 $urlType = variable_get('locale_language_negotiation_url_part');
677
678 //url prefix
679 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
680 if (isset($language->prefix) && $language->prefix) {
681 if ($addLanguagePart) {
3fe61451 682 $url .= $language->prefix . '/';
6a488035
TO
683 }
684 if ($removeLanguagePart) {
685 $url = str_replace("/{$language->prefix}/", '/', $url);
686 }
687 }
688 }
689 //domain
690 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
691 if (isset($language->domain) && $language->domain) {
692 if ($addLanguagePart) {
b276048c 693 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain);
ea54c1ae 694 // drupal function base_path() adds a "/" to the beginning and end of the returned path
34020e33 695 if (substr($cleanedUrl, -1) == '/') {
ea54c1ae
LS
696 $cleanedUrl = substr($cleanedUrl, 0, -1);
697 }
b276048c 698 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $cleanedUrl . base_path();
6a488035
TO
699 }
700 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
701 $url = str_replace('\\', '/', $url);
702 $parseUrl = parse_url($url);
703
704 //kinda hackish but not sure how to do it right
705 //hope http_build_url() will help at some point.
706 if (is_array($parseUrl) && !empty($parseUrl)) {
353ffa53
TO
707 $urlParts = explode('/', $url);
708 $hostKey = array_search($parseUrl['host'], $urlParts);
709 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
6a488035 710 $urlParts[$hostKey] = $ufUrlParts['host'];
353ffa53 711 $url = implode('/', $urlParts);
6a488035
TO
712 }
713 }
714 }
715 }
716 }
717 }
718
719 return $url;
720 }
721
722 /**
723 * Find any users/roles/security-principals with the given permission
724 * and replace it with one or more permissions.
725 *
5a4f6742
CW
726 * @param string $oldPerm
727 * @param array $newPerms
77855840 728 * Array, strings.
6a488035 729 */
00be9182 730 public function replacePermission($oldPerm, $newPerms) {
6a488035
TO
731 $roles = user_roles(FALSE, $oldPerm);
732 if (!empty($roles)) {
733 foreach (array_keys($roles) as $rid) {
be2fb01f 734 user_role_revoke_permissions($rid, [$oldPerm]);
6a488035
TO
735 user_role_grant_permissions($rid, $newPerms);
736 }
737 }
738 }
739
6a488035 740 /**
fe482240 741 * Wrapper for og_membership creation.
a5ecff8d 742 *
77855840
TO
743 * @param int $ogID
744 * Organic Group ID.
745 * @param int $drupalID
746 * Drupal User ID.
6a488035 747 */
9b873358 748 public function og_membership_create($ogID, $drupalID) {
6a488035 749 if (function_exists('og_entity_query_alter')) {
a5ecff8d
CB
750 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
751 //
752 // @TODO Find more solid way to check - try system_get_info('module', 'og').
753 //
754 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
be2fb01f 755 og_group('node', $ogID, ['entity' => user_load($drupalID)]);
6a488035
TO
756 }
757 else {
758 // Works for the OG 7.x-1.x branch
be2fb01f 759 og_group($ogID, ['entity' => user_load($drupalID)]);
6a488035
TO
760 }
761 }
762
763 /**
fe482240 764 * Wrapper for og_membership deletion.
a5ecff8d 765 *
77855840
TO
766 * @param int $ogID
767 * Organic Group ID.
768 * @param int $drupalID
769 * Drupal User ID.
6a488035 770 */
00be9182 771 public function og_membership_delete($ogID, $drupalID) {
6a488035
TO
772 if (function_exists('og_entity_query_alter')) {
773 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
774 // TODO: Find a more solid way to make this test
775 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
776 og_ungroup('node', $ogID, 'user', user_load($drupalID));
0db6c3e1
TO
777 }
778 else {
6a488035
TO
779 // Works for the OG 7.x-1.x branch
780 og_ungroup($ogID, 'user', user_load($drupalID));
781 }
782 }
d8a4acc0 783
5a604d61 784 /**
17f443df 785 * @inheritDoc
5a604d61 786 */
00be9182 787 public function getTimeZoneString() {
5a604d61 788 global $user;
e41775f6 789 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
790 if (variable_get('configurable_timezones', 1) && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
5a604d61 791 $timezone = $user->timezone;
0db6c3e1
TO
792 }
793 else {
e7292422 794 $timezone = variable_get('date_default_timezone', NULL);
5a604d61 795 }
48ec57ab
TO
796 if (!$timezone) {
797 $timezone = parent::getTimeZoneString();
5a604d61 798 }
48ec57ab 799 return $timezone;
5a604d61 800 }
353ffa53 801
d42a224c
CW
802 /**
803 * @inheritDoc
804 */
805 public function setHttpHeader($name, $value) {
806 drupal_add_http_header($name, $value);
807 }
808
03d5592a
CW
809 /**
810 * @inheritDoc
811 */
812 public function synchronizeUsers() {
813 $config = CRM_Core_Config::singleton();
814 if (PHP_SAPI != 'cli') {
815 set_time_limit(300);
816 }
03d5592a
CW
817 $id = 'uid';
818 $mail = 'mail';
819 $name = 'name';
820
821 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
822
03d5592a
CW
823 $user = new StdClass();
824 $uf = $config->userFramework;
825 $contactCount = 0;
826 $contactCreated = 0;
827 $contactMatching = 0;
2eb3dae2
CW
828 foreach ($result as $row) {
829 $user->$id = $row->$id;
830 $user->$mail = $row->$mail;
831 $user->$name = $row->$name;
03d5592a 832 $contactCount++;
2eb3dae2 833 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
03d5592a
CW
834 $contactCreated++;
835 }
836 else {
837 $contactMatching++;
838 }
03d5592a
CW
839 }
840
be2fb01f 841 return [
03d5592a
CW
842 'contactCount' => $contactCount,
843 'contactMatching' => $contactMatching,
844 'contactCreated' => $contactCreated,
be2fb01f 845 ];
03d5592a
CW
846 }
847
f2e906d7
JP
848 /**
849 * Commit the session before exiting.
850 * Similar to drupal_exit().
851 */
852 public function onCiviExit() {
eb3277f9
JP
853 if (function_exists('module_invoke_all')) {
854 if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
855 module_invoke_all('exit');
856 }
857 drupal_session_commit();
f2e906d7 858 }
f2e906d7
JP
859 }
860
6a488035 861}