timezone_detect.module in Timezone Detect 8
Same filename and directory in other branches
Module provides automatic timezone detection via javascript.
File
timezone_detect.moduleView source
<?php
/**
* @file
* Module provides automatic timezone detection via javascript.
*/
use Drupal\timezone_detect\TimezoneDetectInterface;
use Drupal\user\UserInterface;
/**
* Implements hook_user_login().
*/
function timezone_detect_user_login(UserInterface $account) {
$timezone_detect_settings = \Drupal::config('timezone_detect.settings');
if ($timezone_detect_settings
->get('mode') === TimezoneDetectInterface::MODE_LOGIN || empty($account->timezone)) {
// Set session flag to update user's timezone. Note that we cannot add the
// js directly from this function, as the user is redirected after this
// hook fires.
$_SESSION['timezone_detect']['update_timezone'] = TRUE;
}
}
/**
* Implements hook_page_attachments().
*/
function timezone_detect_page_attachments(array &$attachments) {
// Include the javascript only when appropriate.
if (isset($_SESSION['timezone_detect']['update_timezone']) || \Drupal::currentUser()
->isAuthenticated() && \Drupal::config('timezone_detect.settings')
->get('mode') === TimezoneDetectInterface::MODE_ALWAYS) {
$account = \Drupal::currentUser()
->getAccount();
// Store the current timezone for comparison.
$timezone = $account
->getTimeZone();
if (!empty($_SESSION['timezone_detect']['current_timezone'])) {
$timezone = $_SESSION['timezone_detect']['current_timezone'];
}
$attachments['#attached']['library'][] = 'timezone_detect/init';
$attachments['#attached']['drupalSettings']['timezone_detect'] = [
'current_timezone' => $timezone,
'token' => \Drupal::csrfToken()
->get(),
];
}
}
Functions
Name | Description |
---|---|
timezone_detect_page_attachments | Implements hook_page_attachments(). |
timezone_detect_user_login | Implements hook_user_login(). |