You are here

public function KernelTerminateSubscriber::onTerminate in Visitors 8.2

Store visitors data when a request terminates.

Parameters

Symfony\Component\HttpKernel\Event\PostResponseEvent $event: The Event to process.

File

src/EventSubscriber/KernelTerminateSubscriber.php, line 39
Contains Drupal\visitors\EventSubscriber\KernelTerminateSubscriber.

Class

KernelTerminateSubscriber
Store visitors data when a request terminates.

Namespace

Drupal\visitors\EventSubscriber

Code

public function onTerminate(PostResponseEvent $event) {
  $this->request = $event
    ->getRequest();
  $user = \Drupal::currentUser();
  if (isset($user) && !is_null($user)) {
    $not_admin = !in_array('administrator', $user
      ->getRoles());
  }
  else {
    $not_admin = true;
  }
  $log_admin = !\Drupal::config('visitors.config')
    ->get('exclude_administer_users');
  $visitors_uid = isset($user) ? $user
    ->id() : '';
  if ($log_admin || $not_admin) {
    $ip_str = $this
      ->_getIpStr();
    $fields = array(
      'visitors_uid' => $visitors_uid,
      'visitors_ip' => $ip_str,
      'visitors_date_time' => time(),
      'visitors_url' => $this
        ->_getUrl(),
      'visitors_referer' => $this
        ->_getReferer(),
      'visitors_path' => Url::fromRoute('<current>')
        ->toString(),
      'visitors_title' => $this
        ->_getTitle(),
      'visitors_user_agent' => $this
        ->_getUserAgent(),
    );
    if (\Drupal::service('module_handler')
      ->moduleExists('visitors_geoip')) {
      $geoip_data = $this
        ->_getGeoipData($ip_str);
      $fields['visitors_continent_code'] = $geoip_data['continent_code'];
      $fields['visitors_country_code'] = $geoip_data['country_code'];
      $fields['visitors_country_code3'] = $geoip_data['country_code3'];
      $fields['visitors_country_name'] = $geoip_data['country_name'];
      $fields['visitors_region'] = $geoip_data['region'];
      $fields['visitors_city'] = $geoip_data['city'];
      $fields['visitors_postal_code'] = $geoip_data['postal_code'];
      $fields['visitors_latitude'] = $geoip_data['latitude'];
      $fields['visitors_longitude'] = $geoip_data['longitude'];
      $fields['visitors_dma_code'] = $geoip_data['dma_code'];
      $fields['visitors_area_code'] = $geoip_data['area_code'];
    }
    try {
      \Drupal::database()
        ->insert('visitors')
        ->fields($fields)
        ->execute();
    } catch (\Exception $e) {
    }
  }
}