Skip to content

Commit

Permalink
Add ability to filter out visits from staff
Browse files Browse the repository at this point in the history
  • Loading branch information
joecorall committed Dec 4, 2024
1 parent 170cfea commit 6d95ce5
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 5 deletions.
8 changes: 8 additions & 0 deletions config/schema/entity_metrics.schema.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Schema for the configuration files of the Entity Metrics module.
entity_metrics.settings:
type: config_object
label: 'Entity Metrics settings'
mapping:
cookie:
type: string
label: 'Cookie'
26 changes: 25 additions & 1 deletion entity_metrics.install
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ function entity_metrics_install() {
'type' => 'int',
'unsigned' => TRUE,
],
'cookie_set' => [
'type' => 'int',
'size' => 'tiny',
'not null' => TRUE,
'default' => 0,
],
],
'primary key' => ['id'],
'indexes' => [
Expand Down Expand Up @@ -100,7 +106,6 @@ function entity_metrics_install() {
];

Database::getConnection()->schema()->createTable('entity_metrics_regions', $schema);

}

/**
Expand All @@ -110,3 +115,22 @@ function entity_metrics_uninstall() {
Database::getConnection()->schema()->dropTable('entity_metrics_data');
Database::getConnection()->schema()->dropTable('entity_metrics_regions');
}

/**
* Add cookie_set field.
*/
function entity_metrics_update_10001() {
$schema = \Drupal::database()->schema();
if (!$schema->tableExists('entity_metrics_data')) {
return;
}
if ($schema->fieldExists('entity_metrics_data', 'cookie_set')) {
return;
}
$schema->addField('entity_metrics_data', 'cookie_set', [
'type' => 'int',
'size' => 'tiny',
'not null' => TRUE,
'default' => 0,
]);
}
6 changes: 6 additions & 0 deletions entity_metrics.links.menu.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
entity_metrics.settings:
title: Entity Metrics
description: Configure the entity metrics module
parent: system.admin_config_system
route_name: entity_metrics.settings
weight: 10
3 changes: 3 additions & 0 deletions entity_metrics.module
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,16 @@ function entity_metrics_file_download($uri) {
':uri' => $uri,
])->fetchField();
if ($mid) {
$config = \Drupal::config()->get('entity_metrics.settings');
$cookieName = $config && $config->get('cookie');
\Drupal::database()->insert('entity_metrics_data')
->fields([
'entity_type' => 'media',
'entity_id' => $mid,
'session_id' => \Drupal::service('session_manager')->getId(),
'timestamp' => \Drupal::time()->getCurrentTime(),
'ip_address' => $ip,
'cookie_set' => !empty($cookieName) && isset($_COOKIE[$cookieName]) && $_COOKIE[$cookieName] === '1' ? '1' : '0',
])
->execute();
}
Expand Down
8 changes: 8 additions & 0 deletions entity_metrics.routing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,11 @@ entity_metrics.view:
methods: [GET]
requirements:
_permission: 'access content'

entity_metrics.settings:
path: '/admin/config/system/entity-metrics'
defaults:
_title: 'Entity Metrics Settings'
_form: 'Drupal\entity_metrics\Form\SettingsForm'
requirements:
_permission: 'administer site configuration'
25 changes: 21 additions & 4 deletions src/Controller/VisitController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Drupal\entity_metrics\Controller;

use Drupal\Component\Datetime\Time;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Drupal\Core\Session\SessionManager;
Expand Down Expand Up @@ -39,6 +40,13 @@ class VisitController extends ControllerBase {
*/
protected $time;

/**
* The config factory service.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;

/**
* VisitController constructor.
*
Expand All @@ -48,11 +56,14 @@ class VisitController extends ControllerBase {
* The database connection service.
* @param \Drupal\Core\Datetime\TimeInterface $time
* The time service.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory service.
*/
public function __construct(SessionManager $session, Connection $database, Time $time) {
public function __construct(SessionManager $session, Connection $database, Time $time, ConfigFactoryInterface $configFactory) {
$this->session = $session;
$this->database = $database;
$this->time = $time;
$this->configFactory = $configFactory;
}

/**
Expand All @@ -62,7 +73,8 @@ public static function create(ContainerInterface $container) {
return new static(
$container->get('session_manager'),
$container->get('database'),
$container->get('datetime.time')
$container->get('datetime.time'),
$container->get('config.factory')
);
}

Expand All @@ -80,6 +92,8 @@ public function recordVisit(Request $request) {
return $response;
}

$config = $this->configFactory->get('entity_metrics.settings');
$cookieName = $config->get('cookie');
$currentPath = explode('/', $request->request->get('currentPath'));
$entity_id = array_pop($currentPath);
$this->database->insert('entity_metrics_data')
Expand All @@ -89,6 +103,7 @@ public function recordVisit(Request $request) {
'session_id' => $this->session->getId(),
'timestamp' => $this->time->getCurrentTime(),
'ip_address' => $ip,
'cookie_set' => !empty($cookieName) && isset($_COOKIE[$cookieName]) && $_COOKIE[$cookieName] === '1' ? '1' : '0',
])
->execute();
$response = new Response();
Expand All @@ -104,14 +119,16 @@ public function getVisits($type, $id) {
'monthly' => $this->database->query('SELECT COUNT(id) FROM {entity_metrics_data}
WHERE entity_type = :type
AND entity_id = :id
AND timestamp > :thirtyDays', [
AND timestamp > :thirtyDays
AND cookie_set = 0', [
':type' => $type,
':id' => $id,
':thirtyDays' => $this->time->getCurrentTime() - 2592000,
])->fetchField(),
'total' => $this->database->query('SELECT COUNT(id) FROM {entity_metrics_data}
WHERE entity_type = :type
AND entity_id = :id', [
AND entity_id = :id
AND cookie_set = 0', [
':type' => $type,
':id' => $id,
])->fetchField(),
Expand Down
54 changes: 54 additions & 0 deletions src/Form/SettingsForm.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

namespace Drupal\entity_metrics\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
* Configure Entity Metrics settings for this site.
*/
final class SettingsForm extends ConfigFormBase {

/**
* {@inheritdoc}
*/
public function getFormId(): string {
return 'entity_metrics_settings';
}

/**
* {@inheritdoc}
*/
protected function getEditableConfigNames(): array {
return ['entity_metrics.settings'];
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
$form['cookie'] = [
'#type' => 'textfield',
'#title' => $this->t('Cookie name'),
'#description' => $this->t('<p>Name of cookie that when set and equal to "1" will set a flag to allow filtering out those metrics.</p>
<p>This allows not tracking things like staff page views.</p>
<p>The value will need set by some other service, this module does not handle setting the cookie. e.g. <a href="https://github.com/lehigh-university-libraries/cookie-toggler">cookie-toggler</a>.</p>'),
'#default_value' => $this->config('entity_metrics.settings')->get('cookie'),
];
return parent::buildForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
$this->config('entity_metrics.settings')
->set('cookie', $form_state->getValue('cookie'))
->save();
parent::submitForm($form, $form_state);
}

}

0 comments on commit 6d95ce5

Please sign in to comment.