Skip to content

Commit

Permalink
refactor: migrated single session page to controller (#3257)
Browse files Browse the repository at this point in the history
  • Loading branch information
thorsten committed Nov 29, 2024
1 parent 01add1d commit ece9e7f
Show file tree
Hide file tree
Showing 17 changed files with 129 additions and 124 deletions.
2 changes: 2 additions & 0 deletions phpmyfaq/admin/assets/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
handleDeleteAdminLog,
handleDeleteSessions,
handleSessions,
handleSessionsFilter,
handleStatistics,
} from './statistics';
import {
Expand Down Expand Up @@ -135,6 +136,7 @@ document.addEventListener('DOMContentLoaded', async () => {
handleClearRatings();
handleClearVisits();
handleDeleteSessions();
handleSessionsFilter();

// Configuration → FAQ configuration
await handleConfiguration();
Expand Down
15 changes: 15 additions & 0 deletions phpmyfaq/admin/assets/src/statistics/sessions.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,21 @@
import { pushErrorNotification, pushNotification } from '../utils';
import { clearVisits, deleteSessions } from '../api/index.js';

export const handleSessionsFilter = () => {
const button = document.getElementById('pmf-admin-session-day');

if (button) {
button.addEventListener('click', async (event) => {
event.preventDefault();
const form = document.getElementById('pmf-admin-form-session');
const timestamp = document.getElementById('day').value;
const day = new Date(timestamp * 1000).toISOString().split('T')[0];
form.action = `./statistics/sessions/${day}`;
form.submit();
});
}
};

export const handleSessions = () => {
const firstHour = document.getElementById('firstHour');
const lastHour = document.getElementById('lastHour');
Expand Down
3 changes: 0 additions & 3 deletions phpmyfaq/admin/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -315,9 +315,6 @@
require 'glossary.php';
break;
// functions for session administration
case 'viewsession':
require 'statistics.show.php';
break;
case 'truncatesearchterms':
case 'searchstats':
require 'statistics.search.php';
Expand Down
55 changes: 0 additions & 55 deletions phpmyfaq/admin/statistics.show.php

This file was deleted.

7 changes: 6 additions & 1 deletion phpmyfaq/assets/templates/admin/statistics/sessions.day.twig
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,15 @@
<tr>
<td>{{ data.ip }}</td>
<td>{{ data.time | date }}</td>
<td><a href="?action=viewsession&id={{ sid }}">{{ sid }}</a></td>
<td><a href="./statistics/session/{{ sid }}">{{ sid }}</a></td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td colspan="3"><a href="./statistics/sessions">{{ 'ad_sess_back' | translate }}</a></td>
</tr>
</tfoot>
</table>
</div>
</div>
Expand Down
47 changes: 47 additions & 0 deletions phpmyfaq/assets/templates/admin/statistics/sessions.session.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{% extends '@admin/index.twig' %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">
<i aria-hidden="true" class="bi bi-clock-history"></i>
{{ ad_sess_session }} #{{ sessionId }}
</h1>
</div>
<table class="table table-striped align-middle border shadow">
<tbody>
{% set num = 0 %}
{% for line in trackingData %}
{% set data = line|split(';') %}
{% if data.0 == sessionId %}
{% set num = num + 1 %}
<tr>
<td>{{ data.7|date('Y-m-d H:i:s') }}</td>
<td>{{ data.1 }} ({{ data.2 }})</td>
</tr>
{% if num == 1 %}
<tr>
<td>{{ ad_sess_referer }}:</td>
<td>
{% set temp = data.5|replace({'?': '? '}) %}
{{ temp|escape }}
</td>
</tr>
<tr>
<td>{{ ad_sess_browser }}:</td>
<td>{{ data.6|escape }}</td>
</tr>
<tr>
<td>{{ ad_sess_ip }}:</td>
<td>{{ data.3|escape }}</td>
</tr>
{% endif %}
{% endif %}
{% endfor %}
</tbody>
<tfoot>
<tr>
<td colspan="2"><a href="./statistics/sessions/{{ thisDay }}">{{ ad_sess_back }}</a></td>
</tr>
</tfoot>
</table>
{% endblock %}
6 changes: 3 additions & 3 deletions phpmyfaq/assets/templates/admin/statistics/sessions.twig
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@
<tr>
<th>{{ msgSessionBrowse }}</th>
<td class="col-lg-10">
<form action="./statistics/session" method="post" accept-charset="utf-8"
class="row row-cols-lg-auto g-3 align-items-center">
<form class="row row-cols-lg-auto g-3 align-items-center" method="post" id="pmf-admin-form-session"
action="">
<div class="mr-2">
<label for="day" class="d-none">
{{ msgSessionBrowse }}
Expand All @@ -57,7 +57,7 @@
{{ renderedDaySelector | raw }}
</select>
</div>
<button class="btn btn-primary" type="submit" name="statbrowse">
<button class="btn btn-primary" type="button" id="pmf-admin-session-day">
{{ buttonOkay }}
</button>
</form>
Expand Down
43 changes: 0 additions & 43 deletions phpmyfaq/assets/templates/admin/statistics/statistics.show.twig

This file was deleted.

13 changes: 9 additions & 4 deletions phpmyfaq/src/admin-routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,15 @@
'controller' => [StatisticsSessionsController::class, 'index'],
'methods' => 'GET'
],
'admin.statistics.session' => [
'path' => '/statistics/session',
'controller' => [StatisticsSessionsController::class, 'session'],
'methods' => 'POST'
'admin.statistics.sessions.day' => [
'path' => '/statistics/sessions/{date}',
'controller' => [StatisticsSessionsController::class, 'viewDay'],
'methods' => 'POST, GET'
],
'admin.statistics.session.id' => [
'path' => '/statistics/session/{sessionId}',
'controller' => [StatisticsSessionsController::class, 'viewSession'],
'methods' => 'GET'
],
'admin.stopwords' => [
'path' => '/stopwords',
Expand Down
3 changes: 1 addition & 2 deletions phpmyfaq/src/phpMyFAQ/Administration/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,12 @@ public function deleteAllSessions(): bool
*
* @return array<int, stdClass>
*/
public function getLast30DaysVisits(): array
public function getLast30DaysVisits(int $endDate): array
{
$stats = [];
$visits = [];
$completeData = [];
$startDate = strtotime('-1 month');
$endDate = Request::createFromGlobals()->server->get('REQUEST_TIME');

$query = sprintf(
'SELECT time FROM %sfaqsessions WHERE time > %d AND time < %d;',
Expand Down
3 changes: 2 additions & 1 deletion phpmyfaq/src/phpMyFAQ/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use phpMyFAQ\Core\Exception;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
Expand Down Expand Up @@ -112,7 +113,7 @@ private function handleRequest(RouteCollection $routeCollection): void
Response::HTTP_NOT_FOUND
);
} catch (UnauthorizedHttpException) {
$response = new Response('Unauthorized', Response::HTTP_UNAUTHORIZED);
$response = new RedirectResponse('/login');
} catch (BadRequestException $exception) {
$response = new Response(
sprintf(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,14 @@ public function versions(): JsonResponse
* @throws \Exception
*/
#[Route('admin/api/dashboard/visits')]
public function visits(): JsonResponse
public function visits(Request $request): JsonResponse
{
$this->userIsAuthenticated();

if ($this->configuration->get('main.enableUserTracking')) {
$session = $this->container->get('phpmyfaq.admin.session');
return $this->json($session->getLast30DaysVisits());
$endDate = $request->server->get('REQUEST_TIME');
return $this->json($session->getLast30DaysVisits($endDate));
}

return $this->json(['error' => 'User tracking is disabled.'], 400);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,13 @@ public function index(Request $request): Response
* @throws LoaderError
* @throws \Exception
*/
#[Route('/statistics/session', name: 'admin.statistics.session', methods: ['GET'])]
public function session(Request $request): Response
#[Route('/statistics/sessions/:day', name: 'admin.statistics.session', methods: ['GET'])]
public function viewDay(Request $request): Response
{
$this->userHasPermission(PermissionType::STATISTICS_VIEWLOGS);

$day = Filter::filterVar($request->get('day'), FILTER_VALIDATE_INT);

$firstHour = strtotime('midnight', $day);
$lastHour = strtotime('tomorrow', $firstHour) - 1;

Expand All @@ -100,4 +101,37 @@ public function session(Request $request): Response
]
);
}

/**
* @throws Exception
* @throws LoaderError
* @throws \Exception
*/
#[Route('/statistics/session/:sessionId', name: 'admin.statistics.session', methods: ['POST'])]
public function viewSession(Request $request): Response
{
$this->userHasPermission(PermissionType::STATISTICS_VIEWLOGS);

$sessionId = Filter::filterVar($request->get('sessionId'), FILTER_VALIDATE_INT);

$session = $this->container->get('phpmyfaq.admin.session');
$time = $session->getTimeFromSessionId($sessionId);
$trackingData = explode("\n", file_get_contents(PMF_CONTENT_DIR . '/core/data/tracking' . date('dmY', $time)));

return $this->render(
'@admin/statistics/sessions.session.twig',
[
... $this->getHeader($request),
... $this->getFooter(),
'ad_sess_session' => Translation::get('ad_sess_session'),
'sessionId' => $sessionId,
'ad_sess_back' => Translation::get('ad_sess_back'),
'ad_sess_referer' => Translation::get('ad_sess_referer'),
'ad_sess_browser' => Translation::get('ad_sess_browser'),
'ad_sess_ip' => Translation::get('ad_sess_ip'),
'trackingData' => $trackingData,
'thisDay' => date('Y-m-d', $time),
]
);
}
}
4 changes: 2 additions & 2 deletions phpmyfaq/src/phpMyFAQ/Date.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ public function getTrackingFileDate(string $file, bool $endOfDay = false): int
$year = Strings::substr($file, 12, 4);

if (!$endOfDay) {
return mktime(0, 0, 0, (int)$month, (int)$day, (int)$year);
return gmmktime(0, 0, 0, (int)$month, (int)$day, (int)$year);
}

return mktime(23, 59, 59, (int) $month, (int) $day, (int) $year);
return gmmktime(23, 59, 59, (int) $month, (int) $day, (int) $year);
}

return -1;
Expand Down
3 changes: 0 additions & 3 deletions phpmyfaq/src/phpMyFAQ/Helper/StatisticsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,6 @@ public function getAllTrackingDates(): array

public function deleteTrackingFiles(string $month): bool
{
return false;
/*
$dir = opendir(PMF_ROOT_DIR . '/content/core/data');
$first = PHP_INT_MAX;
$last = 0;
Expand All @@ -150,7 +148,6 @@ public function deleteTrackingFiles(string $month): bool
closedir($dir);

return $this->session->deleteSessions($first, $last);
*/
}

public function clearAllVisits(): bool
Expand Down
2 changes: 1 addition & 1 deletion tests/phpMyFAQ/Administration/SessionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public function testGetLast30DaysVisits()
$this->databaseMock->method('query')->willReturn(true);
$this->databaseMock->method('fetchObject')->willReturnOnConsecutiveCalls($resultMock, false);

$actualVisits = $this->session->getLast30DaysVisits();
$actualVisits = $this->session->getLast30DaysVisits($endDate);

$expectedVisits = [];
for ($date = $startDate; $date <= $endDate; $date += 86400) {
Expand Down
Loading

0 comments on commit ece9e7f

Please sign in to comment.