Skip to content

Commit

Permalink
refactor: migrated ratings page to controller (#3257)
Browse files Browse the repository at this point in the history
  • Loading branch information
thorsten committed Nov 24, 2024
1 parent 5b4d031 commit 17b768d
Show file tree
Hide file tree
Showing 16 changed files with 219 additions and 123 deletions.
2 changes: 1 addition & 1 deletion nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ server {
rewrite admin/api/(.*) /admin/api/index.php last;

# Administration pages
rewrite admin/(attachments|backup|configuration|elasticsearch|export|group|import|instance|instances|password|session-keep-alive|stopwords|system|update|user) /admin/front.php last;
rewrite admin/(attachments|backup|configuration|elasticsearch|export|group|import|instance|instances|password|session-keep-alive|statistics|stopwords|system|update|user) /admin/front.php last;

# REST API v3.0 and v3.1
rewrite ^api/v3\.[01]/(.*) /api/index.php last;
Expand Down
2 changes: 1 addition & 1 deletion phpmyfaq/.htaccess
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ Header set Access-Control-Allow-Headers "Content-Type, Authorization"
# Administration API
RewriteRule ^admin/api/(.*) admin/api/index.php [L,QSA]
# Administration pages
RewriteRule ^admin/(attachments|backup|configuration|elasticsearch|export|group|import|instance|instances|password|session-keep-alive|stopwords|system|update|user) admin/front.php [L,QSA]
RewriteRule ^admin/(attachments|backup|configuration|elasticsearch|export|group|import|instance|instances|password|session-keep-alive|statistics|stopwords|system|update|user) admin/front.php [L,QSA]
# Private APIs
RewriteRule ^api/(autocomplete|bookmark/delete|bookmark/create|user/data/update|user/password/update|user/request-removal|user/remove-twofactor|contact|voting|register|captcha|share|comment/create|faq/create|question/create|webauthn/prepare|webauthn/register|webauthn/prepare-login|webauthn/login) api/index.php [L,QSA]
# Setup APIs
Expand Down
21 changes: 21 additions & 0 deletions phpmyfaq/admin/assets/src/api/statistics.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,24 @@ export const truncateSearchTerms = async (csrfToken) => {
console.error(error);
}
};

export const clearRatings = async (csrfToken) => {
try {
const response = await fetch(`./api/statistics/ratings/clear`, {
method: 'DELETE',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
csrfToken: csrfToken,
}),
redirect: 'follow',
referrerPolicy: 'no-referrer',
});

return await response.json();
} catch (error) {
console.error(error);
}
};
9 changes: 8 additions & 1 deletion phpmyfaq/admin/assets/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@
*/

import { getLatestVersion, renderVisitorCharts, renderTopTenCharts, handleVerificationModal } from './dashboard';
import { handleCreateReport, handleDeleteAdminLog, handleSessions, handleStatistics } from './statistics';
import {
handleClearRatings,
handleCreateReport,
handleDeleteAdminLog,
handleSessions,
handleStatistics,
} from './statistics';
import {
handleConfiguration,
handleInstances,
Expand Down Expand Up @@ -124,6 +130,7 @@ document.addEventListener('DOMContentLoaded', async () => {
handleStatistics();
handleCreateReport();
handleTruncateSearchTerms();
handleClearRatings();

// Configuration → FAQ configuration
await handleConfiguration();
Expand Down
2 changes: 2 additions & 0 deletions phpmyfaq/admin/assets/src/statistics/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export * from './admin-log';
export * from './ratings';
export * from './report';
export * from './search';
export * from './sessions';
export * from './statistics';
35 changes: 35 additions & 0 deletions phpmyfaq/admin/assets/src/statistics/ratings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Clear Ratings Handling
*
* 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 <[email protected]>
* @copyright 2024 phpMyFAQ Team
* @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link https://www.phpmyfaq.de
* @since 2024-11-14
*/

import { pushErrorNotification, pushNotification } from '../utils/index.js';
import { clearRatings } from '../api/index.js';

export const handleClearRatings = () => {
const buttonClearRatings = document.getElementById('pmf-admin-clear-ratings');

if (buttonClearRatings) {
buttonClearRatings.addEventListener('click', async (event) => {
event.preventDefault();
const csrf = event.target.getAttribute('data-pmf-csrf');
const response = await clearRatings(csrf);

if (response.success) {
pushNotification(response.success);
} else {
pushErrorNotification(response.error);
}
});
}
};
3 changes: 2 additions & 1 deletion phpmyfaq/admin/header.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@
$secLevelEntries['statistics'] = $adminHelper->addMenuEntry(
PermissionType::STATISTICS_VIEWLOGS->value,
'statistics',
'ad_menu_stat'
'ad_menu_stat',
'statistics/ratings'
);
$secLevelEntries['statistics'] .= $adminHelper->addMenuEntry(
PermissionType::STATISTICS_VIEWLOGS->value,
Expand Down
4 changes: 0 additions & 4 deletions phpmyfaq/admin/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -328,10 +328,6 @@
case 'viewsession':
require 'statistics.show.php';
break;
case 'clear-statistics':
case 'statistics':
require 'statistics.ratings.php';
break;
case 'truncatesearchterms':
case 'searchstats':
require 'statistics.search.php';
Expand Down
91 changes: 0 additions & 91 deletions phpmyfaq/admin/statistics.ratings.php

This file was deleted.

21 changes: 6 additions & 15 deletions phpmyfaq/assets/templates/admin/statistics/ratings.twig
Original file line number Diff line number Diff line change
@@ -1,29 +1,19 @@
{% 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-bar-chart"></i> {{ adminHeaderRatings }}
</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group mr-2">
<a class="btn btn-outline-danger"
href="?action=clear-statistics&csrf={{ csrfToken }}">
<button type="button" class="btn btn-outline-danger" data-pmf-csrf="{{ csrfToken }}" id="pmf-admin-clear-ratings">
<i aria-hidden="true" class="bi bi-trash"></i> {{ buttonDeleteAllVotings }}
</a>
</button>
</div>
</div>
</div>

{% if isDeleteAllVotings %}
{% if isDeletedStatistics %}
<div class="alert alert-success" role="alert">
{{ msgDeleteAllVotings }}
</div>
{% else %}
<div class="alert alert-danger" role="alert">
{{ msgDeleteAllVotingsError }}
</div>
{% endif %}
{% endif %}

<div class="row">
<div class="col-lg-12">
<table class="table border shadow">
Expand Down Expand Up @@ -81,3 +71,4 @@

</div>
</div>
{% endblock %}
5 changes: 5 additions & 0 deletions phpmyfaq/src/admin-api-routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,11 @@
'controller' => [StatisticsController::class, 'truncateSearchTerms'],
'methods' => 'DELETE'
],
'admin.api.statistics.ratings.clear' => [
'path' => '/statistics/ratings/clear',
'controller' => [StatisticsController::class, 'clearRatings'],
'methods' => 'DELETE'
],
// Forms API
'admin.api.forms.activate' => [
'path' => '/forms/activate',
Expand Down
6 changes: 6 additions & 0 deletions phpmyfaq/src/admin-routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use phpMyFAQ\Controller\Administration\ImportController;
use phpMyFAQ\Controller\Administration\InstanceController;
use phpMyFAQ\Controller\Administration\PasswordChangeController;
use phpMyFAQ\Controller\Administration\RatingController;
use phpMyFAQ\Controller\Administration\SessionKeepAliveController;
use phpMyFAQ\Controller\Administration\StopWordsController;
use phpMyFAQ\Controller\Administration\SystemInformationController;
Expand Down Expand Up @@ -145,6 +146,11 @@
'controller' => [SessionKeepAliveController::class, 'index'],
'methods' => 'GET'
],
'admin.statistics.ratings' => [
'path' => '/statistics/ratings',
'controller' => [RatingController::class, 'index'],
'methods' => 'GET'
],
'admin.stopwords' => [
'path' => '/stopwords',
'controller' => [StopwordsController::class, 'index'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ protected function getHeader(Request $request): array
$secLevelEntries['statistics'] = $adminHelper->addMenuEntry(
PermissionType::STATISTICS_VIEWLOGS->value,
'statistics',
'ad_menu_stat'
'ad_menu_stat',
'statistics/ratings'
);
$secLevelEntries['statistics'] .= $adminHelper->addMenuEntry(
PermissionType::STATISTICS_VIEWLOGS->value,
Expand Down Expand Up @@ -232,7 +233,6 @@ protected function getHeader(Request $request): array
case 'stickyfaqs':
$contentPage = true;
break;
case 'statistics':
case 'viewsessions':
case 'sessionbrowse':
case 'sessionsuche':
Expand Down Expand Up @@ -268,6 +268,9 @@ protected function getHeader(Request $request): array
case 'admin.attachments':
$contentPage = true;
break;
case 'admin.statistics.ratings':
$statisticsPage = true;
break;
case 'admin.export':
case 'admin.import':
$exportsPage = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,21 @@
namespace phpMyFAQ\Controller\Administration\Api;

use JsonException;
use phpMyFAQ\Administration\AdminLog;
use phpMyFAQ\Controller\AbstractController;
use phpMyFAQ\Core\Exception;
use phpMyFAQ\Enums\PermissionType;
use phpMyFAQ\Search;
use phpMyFAQ\Session\Token;
use phpMyFAQ\Translation;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Attribute\Route;

class StatisticsController extends AbstractController
{
/**
* @throws Exception|JsonException
* @throws \Exception
*/
#[Route('./admin/api/statistics/admin-log', methods: ['DELETE'])]
public function deleteAdminLog(Request $request): JsonResponse
Expand All @@ -46,8 +45,7 @@ public function deleteAdminLog(Request $request): JsonResponse
return $this->json(['error' => Translation::get('msgNoPermission')], Response::HTTP_UNAUTHORIZED);
}

$logging = new AdminLog($this->configuration);
if ($logging->delete()) {
if ($this->container->get('phpmyfaq.admin.admin-log')->delete()) {
return $this->json(['success' => Translation::get('ad_adminlog_delete_success')], Response::HTTP_OK);
}

Expand All @@ -56,6 +54,7 @@ public function deleteAdminLog(Request $request): JsonResponse

/**
* @throws Exception|JsonException
* @throws \Exception
*/
#[Route('./admin/api/statistics/search-terms', methods: ['DELETE'])]
public function truncateSearchTerms(Request $request): JsonResponse
Expand All @@ -71,11 +70,31 @@ public function truncateSearchTerms(Request $request): JsonResponse
return $this->json(['error' => Translation::get('msgNoPermission')], Response::HTTP_UNAUTHORIZED);
}

$search = new Search($this->configuration);
if ($search->deleteAllSearchTerms()) {
if ($this->container->get('phpmyfaq.search')->deleteAllSearchTerms()) {
return $this->json(['success' => Translation::get('ad_searchterm_del_suc')], Response::HTTP_OK);
}

return $this->json(['error' => Translation::get('ad_searchterm_del_err')], Response::HTTP_BAD_REQUEST);
}

/**
* @throws \Exception
*/
#[Route('./admin/api/statistics/ratings/clear', name: 'admin.api.statistics.ratings.clear', methods: ['DELETE'])]
public function clearRatings(Request $request): JsonResponse
{
$this->userHasPermission(PermissionType::STATISTICS_VIEWLOGS);

$data = json_decode($request->getContent(), false, 512, JSON_THROW_ON_ERROR);

if (!Token::getInstance($this->container->get('session'))->verifyToken('clear-statistics', $data->csrfToken)) {
return $this->json(['error' => Translation::get('msgNoPermission')], Response::HTTP_UNAUTHORIZED);
}

if ($this->container->get('phpmyfaq.rating')->deleteAll()) {
return $this->json(['success' => Translation::get('msgDeleteAllVotings')], Response::HTTP_OK);
}

return $this->json(['error' => Translation::get('msgDeleteAllVotings')], Response::HTTP_BAD_REQUEST);
}
}
Loading

0 comments on commit 17b768d

Please sign in to comment.