Skip to content

Commit

Permalink
refactor: moved admin relevant methods in own class and added tests (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
thorsten committed Oct 29, 2024
1 parent 4eafe79 commit 6d0157a
Show file tree
Hide file tree
Showing 13 changed files with 348 additions and 168 deletions.
4 changes: 2 additions & 2 deletions phpmyfaq/admin/dashboard.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
$user = CurrentUser::getCurrentUser($faqConfig);
$userId = $user->getUserId();
$faqSystem = new System();
$faqSession = new Session($faqConfig);
$session = $container->get('phpmyfaq.admin.session');

$twig = new TwigWrapper(PMF_ROOT_DIR . '/assets/templates');
$template = $twig->loadTemplate('./admin/dashboard.twig');
Expand All @@ -54,7 +54,7 @@
System::getVersion(),
System::getGitHubIssuesUrl()
),
'adminDashboardInfoNumVisits' => $faqSession->getNumberOfSessions(),
'adminDashboardInfoNumVisits' => $session->getNumberOfSessions(),
'adminDashboardInfoNumFaqs' => $faqTableInfo[Database::getTablePrefix() . 'faqdata'],
'adminDashboardInfoNumComments' => $faqTableInfo[Database::getTablePrefix() . 'faqcomments'],
'adminDashboardInfoNumQuestions' => $faqTableInfo[Database::getTablePrefix() . 'faqquestions'],
Expand Down
6 changes: 2 additions & 4 deletions phpmyfaq/admin/statistics.sessions.day.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,9 @@
* @since 2003-02-24
*/

use phpMyFAQ\Configuration;
use phpMyFAQ\Date;
use phpMyFAQ\Enums\PermissionType;
use phpMyFAQ\Filter;
use phpMyFAQ\Session;
use phpMyFAQ\Template\TwigWrapper;
use phpMyFAQ\Translation;
use phpMyFAQ\User\CurrentUser;
Expand All @@ -31,7 +29,7 @@
exit();
}

$faqConfig = Configuration::getConfigurationInstance();
$faqConfig = $container->get('phpmyfaq.configuration');
$user = CurrentUser::getCurrentUser($faqConfig);
$request = Request::createFromGlobals();

Expand All @@ -41,7 +39,7 @@
$firstHour = strtotime('midnight', $day);
$lastHour = strtotime('tomorrow', $firstHour) - 1;

$session = new Session($faqConfig);
$session = $container->get('phpmyfaq.admin.session');
$sessionData = $session->getSessionsByDate($firstHour, $lastHour);
$date = new Date($faqConfig);

Expand Down
9 changes: 3 additions & 6 deletions phpmyfaq/admin/statistics.sessions.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,29 @@
* @since 2003-02-24
*/

use phpMyFAQ\Configuration;
use phpMyFAQ\Date;
use phpMyFAQ\Enums\PermissionType;
use phpMyFAQ\Filter;
use phpMyFAQ\Helper\StatisticsHelper;
use phpMyFAQ\Session;
use phpMyFAQ\Session\Token;
use phpMyFAQ\Template\TwigWrapper;
use phpMyFAQ\Translation;
use phpMyFAQ\User\CurrentUser;
use phpMyFAQ\Visits;
use Symfony\Component\HttpFoundation\Request;

if (!defined('IS_VALID_PHPMYFAQ')) {
http_response_code(400);
exit();
}

$faqConfig = Configuration::getConfigurationInstance();
$faqConfig = $container->get('phpmyfaq.configuration');
$user = CurrentUser::getCurrentUser($faqConfig);
$request = Request::createFromGlobals();

if ($user->perm->hasPermission($user->getUserId(), PermissionType::STATISTICS_VIEWLOGS->value)) {
$session = new Session($faqConfig);
$session = $container->get('phpmyfaq.admin.session');
$date = new Date($faqConfig);
$visits = new Visits($faqConfig);
$visits = $container->get('phpmyfaq.visits');
$statisticsHelper = new StatisticsHelper($session, $visits, $date);

$stats = $statisticsHelper->getTrackingFilesStatistics();
Expand Down
6 changes: 2 additions & 4 deletions phpmyfaq/admin/statistics.show.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,8 @@
* @since 2003-02-24
*/

use phpMyFAQ\Configuration;
use phpMyFAQ\Enums\PermissionType;
use phpMyFAQ\Filter;
use phpMyFAQ\Session;
use phpMyFAQ\Template\TwigWrapper;
use phpMyFAQ\Translation;
use phpMyFAQ\User\CurrentUser;
Expand All @@ -28,13 +26,13 @@
exit();
}

$faqConfig = Configuration::getConfigurationInstance();
$faqConfig = $container->get('phpmyfaq.configuration');
$user = CurrentUser::getCurrentUser($faqConfig);

$sessionId = Filter::filterInput(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if ($user->perm->hasPermission($user->getUserId(), PermissionType::STATISTICS_VIEWLOGS->value)) {
$session = new Session($faqConfig);
$session = $container->get('phpmyfaq.admin.session');
$time = $session->getTimeFromSessionId($sessionId);
$trackingData = explode("\n", file_get_contents(PMF_CONTENT_DIR . '/core/data/tracking' . date('dmY', $time)));

Expand Down
5 changes: 5 additions & 0 deletions phpmyfaq/src/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
use phpMyFAQ\Init;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;

//
// Debug mode:
Expand Down Expand Up @@ -178,7 +180,10 @@
if (defined('PMF_SESSION_SAVE_PATH') && !empty(PMF_SESSION_SAVE_PATH)) {
session_save_path(PMF_SESSION_SAVE_PATH);
}

session_start();
$session = new Session(new PhpBridgeSessionStorage());
$session->start();
}

//
Expand Down
168 changes: 168 additions & 0 deletions phpmyfaq/src/phpMyFAQ/Administration/Session.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
<?php

/**
* The Administration Session class.
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at https://mozilla.org/MPL/2.0/.
*
* @package phpMyFAQ
* @author Thorsten Rinne <thorsten@phpmyfaq.de>
* @copyright 2024 phpMyFAQ Team
* @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link https://www.phpmyfaq.de
* @since 2024-10-29
*/

namespace phpMyFAQ\Administration;

use phpMyFAQ\Configuration;
use phpMyFAQ\Database;
use stdClass;
use Symfony\Component\HttpFoundation\Request;

readonly class Session
{
public function __construct(private Configuration $configuration)
{
}

public function getTimeFromSessionId(int $sessionId): int
{
$timestamp = 0;

$query = sprintf('SELECT time FROM %sfaqsessions WHERE sid = %d', Database::getTablePrefix(), $sessionId);

$result = $this->configuration->getDb()->query($query);

if ($result) {
$res = $this->configuration->getDb()->fetchObject($result);
$timestamp = $res->time;
}

return $timestamp;
}


/**
* Returns all session from a date.
*
* @param int $firstHour First hour
* @param int $lastHour Last hour
*
* @return array<int, string[]>
*/
public function getSessionsByDate(int $firstHour, int $lastHour): array
{
$sessions = [];

$query = sprintf(
'SELECT sid, ip, time FROM %sfaqsessions WHERE time > %d AND time < %d ORDER BY time',
Database::getTablePrefix(),
$firstHour,
$lastHour
);

$result = $this->configuration->getDb()->query($query);
while ($row = $this->configuration->getDb()->fetchObject($result)) {
$sessions[$row->sid] = [
'ip' => $row->ip,
'time' => $row->time,
];
}

return $sessions;
}

/**
* Returns the number of sessions.
*/
public function getNumberOfSessions(): int
{
$num = 0;

$query = sprintf('SELECT COUNT(sid) as num_sessions FROM %sfaqsessions', Database::getTablePrefix());

$result = $this->configuration->getDb()->query($query);
if ($result) {
$row = $this->configuration->getDb()->fetchObject($result);
$num = $row->num_sessions;
}

return $num;
}

/**
* Deletes the sessions for a given timespan.
*
* @param int $first First session ID
* @param int $last Last session ID
*/
public function deleteSessions(int $first, int $last): bool
{
$query = sprintf(
'DELETE FROM %sfaqsessions WHERE time >= %d AND time <= %d',
Database::getTablePrefix(),
$first,
$last
);

return (bool) $this->configuration->getDb()->query($query);
}

/**
* Deletes all entries in the table.
*/
public function deleteAllSessions(): bool
{
$query = sprintf('DELETE FROM %sfaqsessions', Database::getTablePrefix());

return (bool) $this->configuration->getDb()->query($query);
}

/**
* Calculates the number of visits per day the last 30 days.
*
* @return array<int, stdClass>
*/
public function getLast30DaysVisits(): 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;',
Database::getTablePrefix(),
$startDate,
$endDate
);
$result = $this->configuration->getDb()->query($query);

while ($row = $this->configuration->getDb()->fetchObject($result)) {
$visits[] = $row->time;
}

for ($date = $startDate; $date <= $endDate; $date += 86400) {
$stats[date('Y-m-d', $date)] = 0;
}

foreach ($visits as $visitDate) {
if (isset($stats[date('Y-m-d', $visitDate)])) {
++$stats[date('Y-m-d', $visitDate)];
}
}

foreach (array_keys($stats) as $date) {
$visit = new stdClass();
$visit->date = $date;
$visit->number = $stats[$date];
$completeData[] = $visit;
}

return $completeData;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
use phpMyFAQ\Controller\AbstractController;
use phpMyFAQ\Core\Exception;
use phpMyFAQ\Faq;
use phpMyFAQ\Session;
use phpMyFAQ\System;
use phpMyFAQ\Translation;
use Symfony\Component\HttpFoundation\JsonResponse;
Expand Down Expand Up @@ -84,7 +83,7 @@ public function visits(): JsonResponse
$this->userIsAuthenticated();

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function export(Request $request): BinaryFileResponse|JsonResponse
return $this->json(['error' => Translation::get('err_NotAuth')], Response::HTTP_UNAUTHORIZED);
}

$session = new Session($this->configuration);
$session = $this->container->get('phpmyfaq.admin.session');
$data = $session->getSessionsByDate(
strtotime((string) $requestData->firstHour),
strtotime((string) $requestData->lastHour)
Expand Down
6 changes: 3 additions & 3 deletions phpmyfaq/src/phpMyFAQ/Helper/StatisticsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@

namespace phpMyFAQ\Helper;

use phpMyFAQ\Administration\Session;
use phpMyFAQ\Date;
use phpMyFAQ\Session;
use phpMyFAQ\Translation;
use phpMyFAQ\Visits;
use stdClass;
Expand Down Expand Up @@ -68,7 +68,7 @@ public function getFirstTrackingDate(int $firstDate): string

if (is_file(PMF_ROOT_DIR . '/content/core/data/tracking' . date('dmY', $firstDate))) {
$fp = @fopen(PMF_ROOT_DIR . '/content/core/data/tracking' . date('dmY', $firstDate), 'r');
while (($data = fgetcsv($fp, 1024, ';')) !== false) {
while (($data = fgetcsv($fp, 1024, ';', '"', '\\')) !== false) {
$date = isset($data[7]) && 10 === strlen((string) $data[7]) ? $data[7] : $requestTime;
}

Expand All @@ -86,7 +86,7 @@ public function getLastTrackingDate(int $lastDate): string
if (is_file(PMF_ROOT_DIR . '/content/core/data/tracking' . date('dmY', $lastDate))) {
$fp = fopen(PMF_ROOT_DIR . '/content/core/data/tracking' . date('dmY', $lastDate), 'r');

while (($data = fgetcsv($fp, 1024, ';')) !== false) {
while (($data = fgetcsv($fp, 1024, ';', '"', '\\')) !== false) {
$date = isset($data[7]) && 10 === strlen((string) $data[7]) ? $data[7] : $requestTime;
}

Expand Down
Loading

0 comments on commit 6d0157a

Please sign in to comment.