remove unnecessary E_ blocker
[civicrm-core.git] / CRM / Utils / System / Drupal.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Drupal specific stuff goes here
20 */
21 class CRM_Utils_System_Drupal extends CRM_Utils_System_DrupalBase {
22
23 /**
24 * @inheritDoc
25 */
26 public function createUser(&$params, $mail) {
27 $form_state = form_state_defaults();
28
29 $form_state['input'] = [
30 'name' => $params['cms_name'],
31 'mail' => $params[$mail],
32 'op' => 'Create new account',
33 ];
34
35 $admin = user_access('administer users');
36 if (!variable_get('user_email_verification', TRUE) || $admin) {
37 $form_state['input']['pass'] = ['pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']];
38 }
39
40 if (!empty($params['notify'])) {
41 $form_state['input']['notify'] = $params['notify'];
42 }
43
44 $form_state['rebuild'] = FALSE;
45 $form_state['programmed'] = TRUE;
46 $form_state['complete form'] = FALSE;
47 $form_state['method'] = 'post';
48 $form_state['build_info']['args'] = [];
49 /*
50 * if we want to submit this form more than once in a process (e.g. create more than one user)
51 * we must force it to validate each time for this form. Otherwise it will not validate
52 * subsequent submissions and the manner in which the password is passed in will be invalid
53 */
54 $form_state['must_validate'] = TRUE;
55 $config = CRM_Core_Config::singleton();
56
57 // we also need to redirect b
58 $config->inCiviCRM = TRUE;
59
60 $form = drupal_retrieve_form('user_register_form', $form_state);
61 $form_state['process_input'] = 1;
62 $form_state['submitted'] = 1;
63 $form['#array_parents'] = [];
64 $form['#tree'] = FALSE;
65 drupal_process_form('user_register_form', $form, $form_state);
66
67 $config->inCiviCRM = FALSE;
68
69 if (form_get_errors()) {
70 return FALSE;
71 }
72 return $form_state['user']->uid;
73 }
74
75 /**
76 * Appends a Drupal 7 Javascript file when the CRM Menubar Javascript file has
77 * been included. The file is added before the menu bar so we can properly listen
78 * for the menu bar ready event.
79 */
80 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent $event) {
81 $menuBarFileIndex = array_search('js/crm.menubar.js', $event->list);
82
83 if ($menuBarFileIndex !== FALSE) {
84 array_splice($event->list, $menuBarFileIndex, 0, ['js/crm.drupal7.js']);
85 }
86 }
87
88 /**
89 * @inheritDoc
90 */
91 public function updateCMSName($ufID, $ufName) {
92 // CRM-5555
93 if (function_exists('user_load')) {
94 $user = user_load($ufID);
95 if ($user->mail != $ufName) {
96 user_save($user, ['mail' => $ufName]);
97 $user = user_load($ufID);
98 }
99 }
100 }
101
102 /**
103 * Check if username and email exists in the drupal db.
104 *
105 * @param array $params
106 * Array of name and mail values.
107 * @param array $errors
108 * Array of errors.
109 * @param string $emailName
110 * Field label for the 'email'.
111 */
112 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
113 $config = CRM_Core_Config::singleton();
114
115 $dao = new CRM_Core_DAO();
116 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
117 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
118 $errors = form_get_errors();
119 if ($errors) {
120 // unset drupal messages to avoid twice display of errors
121 unset($_SESSION['messages']);
122 }
123
124 if (!empty($params['name'])) {
125 if ($nameError = user_validate_name($params['name'])) {
126 $errors['cms_name'] = $nameError;
127 }
128 else {
129 $uid = db_query(
130 "SELECT uid FROM {users} WHERE name = :name",
131 [':name' => $params['name']]
132 )->fetchField();
133 if ((bool) $uid) {
134 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
135 }
136 }
137 }
138
139 if (!empty($params['mail'])) {
140 if ($emailError = user_validate_mail($params['mail'])) {
141 $errors[$emailName] = $emailError;
142 }
143 else {
144 $uid = db_query(
145 "SELECT uid FROM {users} WHERE mail = :mail",
146 [':mail' => $params['mail']]
147 )->fetchField();
148 if ((bool) $uid) {
149 $resetUrl = url('user/password');
150 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
151 [1 => $params['mail'], 2 => $resetUrl]
152 );
153 }
154 }
155 }
156 }
157
158 /**
159 * @inheritDoc
160 */
161 public function getLoginURL($destination = '') {
162 $query = $destination ? ['destination' => $destination] : NULL;
163 return CRM_Utils_System::url('user', $query, TRUE);
164 }
165
166 /**
167 * @inheritDoc
168 */
169 public function setTitle($title, $pageTitle = NULL) {
170 if (arg(0) == 'civicrm') {
171 if (!$pageTitle) {
172 $pageTitle = $title;
173 }
174
175 drupal_set_title($pageTitle, PASS_THROUGH);
176 }
177 }
178
179 /**
180 * @inheritDoc
181 */
182 public function appendBreadCrumb($breadCrumbs) {
183 $breadCrumb = drupal_get_breadcrumb();
184
185 if (is_array($breadCrumbs)) {
186 foreach ($breadCrumbs as $crumbs) {
187 if (stripos($crumbs['url'], 'id%%')) {
188 $args = ['cid', 'mid'];
189 foreach ($args as $a) {
190 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
191 FALSE, NULL, $_GET
192 );
193 if ($val) {
194 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
195 }
196 }
197 }
198 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
199 }
200 }
201 drupal_set_breadcrumb($breadCrumb);
202 }
203
204 /**
205 * @inheritDoc
206 */
207 public function resetBreadCrumb() {
208 $bc = [];
209 drupal_set_breadcrumb($bc);
210 }
211
212 /**
213 * @inheritDoc
214 */
215 public function addHTMLHead($header) {
216 static $count = 0;
217 if (!empty($header)) {
218 $key = 'civi_' . ++$count;
219 $data = [
220 '#type' => 'markup',
221 '#markup' => $header,
222 ];
223 drupal_add_html_head($data, $key);
224 }
225 }
226
227 /**
228 * @inheritDoc
229 */
230 public function addScriptUrl($url, $region) {
231 $params = ['group' => JS_LIBRARY, 'weight' => 10];
232 switch ($region) {
233 case 'html-header':
234 case 'page-footer':
235 $params['scope'] = substr($region, 5);
236 break;
237
238 default:
239 return FALSE;
240 }
241 // If the path is within the drupal directory we can use the more efficient 'file' setting
242 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
243 drupal_add_js($url, $params);
244 return TRUE;
245 }
246
247 /**
248 * @inheritDoc
249 */
250 public function addScript($code, $region) {
251 $params = ['type' => 'inline', 'group' => JS_LIBRARY, 'weight' => 10];
252 switch ($region) {
253 case 'html-header':
254 case 'page-footer':
255 $params['scope'] = substr($region, 5);
256 break;
257
258 default:
259 return FALSE;
260 }
261 drupal_add_js($code, $params);
262 return TRUE;
263 }
264
265 /**
266 * @inheritDoc
267 */
268 public function addStyleUrl($url, $region) {
269 if ($region != 'html-header') {
270 return FALSE;
271 }
272 $params = [];
273 // If the path is within the drupal directory we can use the more efficient 'file' setting
274 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
275 drupal_add_css($url, $params);
276 return TRUE;
277 }
278
279 /**
280 * @inheritDoc
281 */
282 public function addStyle($code, $region) {
283 if ($region != 'html-header') {
284 return FALSE;
285 }
286 $params = ['type' => 'inline'];
287 drupal_add_css($code, $params);
288 return TRUE;
289 }
290
291 /**
292 * @inheritDoc
293 */
294 public function mapConfigToSSL() {
295 global $base_url;
296 $base_url = str_replace('http://', 'https://', $base_url);
297 }
298
299 /**
300 * Get the name of the users table.
301 *
302 * @return string
303 */
304 protected function getUsersTableName() {
305 $userFrameworkUsersTableName = Civi::settings()->get('userFrameworkUsersTableName');
306 if (empty($userFrameworkUsersTableName)) {
307 $userFrameworkUsersTableName = 'users';
308 }
309 return $userFrameworkUsersTableName;
310 }
311
312 /**
313 * @inheritDoc
314 */
315 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
316 require_once 'DB.php';
317
318 $config = CRM_Core_Config::singleton();
319
320 $ufDSN = CRM_Utils_SQL::autoSwitchDSN($config->userFrameworkDSN);
321 try {
322 $dbDrupal = DB::connect($ufDSN);
323 }
324 catch (Exception $e) {
325 throw new CRM_Core_Exception("Cannot connect to drupal db via $ufDSN, " . $e->getMessage());
326 }
327
328 $account = $userUid = $userMail = NULL;
329 if ($loadCMSBootstrap) {
330 $bootStrapParams = [];
331 if ($name && $password) {
332 $bootStrapParams = [
333 'name' => $name,
334 'pass' => $password,
335 ];
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
351 require_once "$cmsPath/includes/bootstrap.inc";
352 require_once "$cmsPath/includes/password.inc";
353
354 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
355 $name = $dbDrupal->escapeSimple($strtolower($name));
356 $userFrameworkUsersTableName = $this->getUsersTableName();
357
358 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
359 $sql = "
360 SELECT u.*
361 FROM {$userFrameworkUsersTableName} u
362 WHERE LOWER(u.name) = '$name'
363 AND 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 }
387 return [$contactID, $userUid, mt_rand()];
388 }
389 return FALSE;
390 }
391
392 /**
393 * @inheritDoc
394 */
395 public function loadUser($username) {
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
414 /**
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.
418 *
419 * @param array $params
420 *
421 * FIXME: Document values accepted/required by $params
422 */
423 public function userLoginFinalize($params = []) {
424 user_login_finalize($params);
425 }
426
427 /**
428 * Determine the native ID of the CMS user.
429 *
430 * @param string $username
431 * @return int|null
432 */
433 public function getUfId($username) {
434 $user = user_load_by_name($username);
435 if (empty($user->uid)) {
436 return NULL;
437 }
438 return $user->uid;
439 }
440
441 /**
442 * @inheritDoc
443 */
444 public function logout() {
445 module_load_include('inc', 'user', 'user.pages');
446 return user_logout();
447 }
448
449 /**
450 * Get the default location for CiviCRM blocks.
451 *
452 * @return string
453 */
454 public function getDefaultBlockLocation() {
455 return 'sidebar_first';
456 }
457
458 /**
459 * Load drupal bootstrap.
460 *
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
468 *
469 * @return bool
470 */
471 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
472 //take the cms root path.
473 $cmsPath = $this->cmsRootPath($realPath);
474
475 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
476 if ($throwError) {
477 throw new Exception('Sorry, could not locate bootstrap.inc');
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';
493 // @ to suppress notices eg 'DRUPALFOO already defined'.
494 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
495
496 if (!function_exists('module_exists')) {
497 if ($throwError) {
498 throw new Exception('Sorry, could not load drupal bootstrap.');
499 }
500 return FALSE;
501 }
502 if (!module_exists('civicrm')) {
503 if ($throwError) {
504 throw new Exception('Sorry, drupal cannot find CiviCRM');
505 }
506 return FALSE;
507 }
508
509 // seems like we've bootstrapped drupal
510 $config = CRM_Core_Config::singleton();
511
512 // lets also fix the clean url setting
513 // CRM-6948
514 $config->cleanURL = (int) variable_get('clean_url', '0');
515
516 // we need to call the config hook again, since we now know
517 // all the modules that are listening on it, does not apply
518 // to J! and WP as yet
519 // CRM-8655
520 CRM_Utils_Hook::config($config);
521
522 if (!$loadUser) {
523 return TRUE;
524 }
525
526 $uid = $params['uid'] ?? NULL;
527 if (!$uid) {
528 //load user, we need to check drupal permissions.
529 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
530 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
531
532 if ($name) {
533 $uid = user_authenticate($name, $pass);
534 if (!$uid) {
535 if ($throwError) {
536 throw new Exception('Sorry, unrecognized username or password.');
537 }
538 return FALSE;
539 }
540 }
541 }
542
543 if ($uid) {
544 $account = user_load($uid);
545 if ($account && $account->uid) {
546 global $user;
547 $user = $account;
548 return TRUE;
549 }
550 }
551
552 if ($throwError) {
553 throw new Exception('Sorry, can not load CMS user account.');
554 }
555
556 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
557 // which means that define(CIVICRM_CLEANURL) was correctly set.
558 // So we correct it
559 $config = CRM_Core_Config::singleton();
560 $config->cleanURL = (int) variable_get('clean_url', '0');
561
562 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
563 CRM_Utils_Hook::config($config);
564
565 return FALSE;
566 }
567
568 /**
569 * Get CMS root path.
570 *
571 * @param string $scriptFilename
572 *
573 * @return null|string
574 */
575 public function cmsRootPath($scriptFilename = NULL) {
576 $cmsRoot = $valid = NULL;
577
578 if (!is_null($scriptFilename)) {
579 $path = $scriptFilename;
580 }
581 else {
582 $path = $_SERVER['SCRIPT_FILENAME'];
583 }
584
585 if (function_exists('drush_get_context')) {
586 // drush anyway takes care of multisite install etc
587 return drush_get_context('DRUSH_DRUPAL_ROOT');
588 }
589
590 global $civicrm_paths;
591 if (!empty($civicrm_paths['cms.root']['path'])) {
592 return $civicrm_paths['cms.root']['path'];
593 }
594
595 // CRM-7582
596 $pathVars = explode('/',
597 str_replace('//', '/',
598 str_replace('\\', '/', $path)
599 )
600 );
601
602 //lets store first var,
603 //need to get back for windows.
604 $firstVar = array_shift($pathVars);
605
606 // Remove the script name to remove an necessary iteration of the loop.
607 array_pop($pathVars);
608
609 // CRM-7429 -- do check for uppermost 'includes' dir, which would
610 // work for multisite installation.
611 do {
612 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
613 $cmsIncludePath = "$cmsRoot/includes";
614 // Stop if we find bootstrap.
615 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
616 $valid = TRUE;
617 break;
618 }
619 //remove one directory level.
620 array_pop($pathVars);
621 } while (count($pathVars));
622
623 return ($valid) ? $cmsRoot : NULL;
624 }
625
626 /**
627 * @inheritDoc
628 */
629 public function isUserLoggedIn() {
630 $isloggedIn = FALSE;
631 if (function_exists('user_is_logged_in')) {
632 $isloggedIn = user_is_logged_in();
633 }
634
635 return $isloggedIn;
636 }
637
638 /**
639 * @inheritDoc
640 */
641 public function getLoggedInUfID() {
642 $ufID = NULL;
643 if (function_exists('user_is_logged_in') &&
644 user_is_logged_in() &&
645 function_exists('user_uid_optional_to_arg')
646 ) {
647 $ufID = user_uid_optional_to_arg([]);
648 }
649
650 return $ufID;
651 }
652
653 /**
654 * @inheritDoc
655 */
656 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
657 if (empty($url)) {
658 return $url;
659 }
660
661 //CRM-7803 -from d7 onward.
662 $config = CRM_Core_Config::singleton();
663 if (function_exists('variable_get') &&
664 module_exists('locale') &&
665 function_exists('language_negotiation_get')
666 ) {
667 global $language;
668
669 //does user configuration allow language
670 //support from the URL (Path prefix or domain)
671 if (language_negotiation_get('language') == 'locale-url') {
672 $urlType = variable_get('locale_language_negotiation_url_part');
673
674 //url prefix
675 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
676 if (isset($language->prefix) && $language->prefix) {
677 if ($addLanguagePart) {
678 $url .= $language->prefix . '/';
679 }
680 if ($removeLanguagePart) {
681 $url = str_replace("/{$language->prefix}/", '/', $url);
682 }
683 }
684 }
685 //domain
686 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
687 if (isset($language->domain) && $language->domain) {
688 if ($addLanguagePart) {
689 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain);
690 // drupal function base_path() adds a "/" to the beginning and end of the returned path
691 if (substr($cleanedUrl, -1) == '/') {
692 $cleanedUrl = substr($cleanedUrl, 0, -1);
693 }
694 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $cleanedUrl . base_path();
695 }
696 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
697 $url = str_replace('\\', '/', $url);
698 $parseUrl = parse_url($url);
699
700 //kinda hackish but not sure how to do it right
701 //hope http_build_url() will help at some point.
702 if (is_array($parseUrl) && !empty($parseUrl)) {
703 $urlParts = explode('/', $url);
704 $hostKey = array_search($parseUrl['host'], $urlParts);
705 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
706 $urlParts[$hostKey] = $ufUrlParts['host'];
707 $url = implode('/', $urlParts);
708 }
709 }
710 }
711 }
712 }
713 }
714
715 return $url;
716 }
717
718 /**
719 * Find any users/roles/security-principals with the given permission
720 * and replace it with one or more permissions.
721 *
722 * @param string $oldPerm
723 * @param array $newPerms
724 * Array, strings.
725 */
726 public function replacePermission($oldPerm, $newPerms) {
727 $roles = user_roles(FALSE, $oldPerm);
728 if (!empty($roles)) {
729 foreach (array_keys($roles) as $rid) {
730 user_role_revoke_permissions($rid, [$oldPerm]);
731 user_role_grant_permissions($rid, $newPerms);
732 }
733 }
734 }
735
736 /**
737 * Wrapper for og_membership creation.
738 *
739 * @param int $ogID
740 * Organic Group ID.
741 * @param int $drupalID
742 * Drupal User ID.
743 */
744 public function og_membership_create($ogID, $drupalID) {
745 if (function_exists('og_entity_query_alter')) {
746 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
747 //
748 // @TODO Find more solid way to check - try system_get_info('module', 'og').
749 //
750 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
751 og_group('node', $ogID, ['entity' => user_load($drupalID)]);
752 }
753 else {
754 // Works for the OG 7.x-1.x branch
755 og_group($ogID, ['entity' => user_load($drupalID)]);
756 }
757 }
758
759 /**
760 * Wrapper for og_membership deletion.
761 *
762 * @param int $ogID
763 * Organic Group ID.
764 * @param int $drupalID
765 * Drupal User ID.
766 */
767 public function og_membership_delete($ogID, $drupalID) {
768 if (function_exists('og_entity_query_alter')) {
769 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
770 // TODO: Find a more solid way to make this test
771 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
772 og_ungroup('node', $ogID, 'user', user_load($drupalID));
773 }
774 else {
775 // Works for the OG 7.x-1.x branch
776 og_ungroup($ogID, 'user', user_load($drupalID));
777 }
778 }
779
780 /**
781 * @inheritDoc
782 */
783 public function getTimeZoneString() {
784 global $user;
785 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
786 if (variable_get('configurable_timezones', 1) && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
787 $timezone = $user->timezone;
788 }
789 else {
790 $timezone = variable_get('date_default_timezone', NULL);
791 }
792 if (!$timezone) {
793 $timezone = parent::getTimeZoneString();
794 }
795 return $timezone;
796 }
797
798 /**
799 * @inheritDoc
800 */
801 public function setHttpHeader($name, $value) {
802 drupal_add_http_header($name, $value);
803 }
804
805 /**
806 * @inheritDoc
807 */
808 public function synchronizeUsers() {
809 $config = CRM_Core_Config::singleton();
810 if (PHP_SAPI != 'cli') {
811 set_time_limit(300);
812 }
813 $id = 'uid';
814 $mail = 'mail';
815 $name = 'name';
816
817 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
818
819 $user = new StdClass();
820 $uf = $config->userFramework;
821 $contactCount = 0;
822 $contactCreated = 0;
823 $contactMatching = 0;
824 foreach ($result as $row) {
825 $user->$id = $row->$id;
826 $user->$mail = $row->$mail;
827 $user->$name = $row->$name;
828 $contactCount++;
829 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
830 $contactCreated++;
831 }
832 else {
833 $contactMatching++;
834 }
835 }
836
837 return [
838 'contactCount' => $contactCount,
839 'contactMatching' => $contactMatching,
840 'contactCreated' => $contactCreated,
841 ];
842 }
843
844 /**
845 * Commit the session before exiting.
846 * Similar to drupal_exit().
847 */
848 public function onCiviExit() {
849 if (function_exists('module_invoke_all')) {
850 if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
851 module_invoke_all('exit');
852 }
853 drupal_session_commit();
854 }
855 }
856
857 }