Repository navigation
Expand file tree
/
Copy pathMostReadBlockPlugin.php
More file actions
267 lines (236 loc) · 8.52 KB
/
Copy pathMostReadBlockPlugin.php
File metadata and controls
267 lines (236 loc) · 8.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
<?php
/**
* @file plugins/blocks/mostRead/MostReadBlockPlugin.php
*
* Copyright (c) 2014-2024 Simon Fraser University
* Copyright (c) 2003-2024 John Willinsky
* Copyright (c) 2026 OJSBR (https://ojsbr.com)
* Distributed under the GNU GPL v3. For full terms see the file docs/COPYING.
*
* @class MostReadBlockPlugin
*
* @ingroup plugins_blocks_mostRead
*
* @brief Class for "Most Read" block plugin
*/
namespace APP\plugins\blocks\mostRead;
use APP\core\Application;
use APP\facades\Repo;
use Illuminate\Support\Facades\Cache;
use PKP\core\JSONMessage;
use PKP\facades\Locale;
use PKP\linkAction\LinkAction;
use PKP\linkAction\request\AjaxModal;
use PKP\plugins\BlockPlugin;
use PKP\submission\PKPSubmission;
class MostReadBlockPlugin extends BlockPlugin
{
/** Cache lifetime in seconds (1 day). */
public const CACHE_TTL = 60 * 60 * 24;
/** Defaults and limits of the settings. */
public const DEFAULT_DAYS = 7;
public const MAX_DAYS = 3650;
public const DEFAULT_COUNT = 5;
public const MAX_COUNT = 50;
/**
* Install default settings on journal creation.
*/
public function getContextSpecificPluginSettingsFile(): string
{
return $this->getPluginPath() . '/settings.xml';
}
/**
* Name shown in the plugins list.
*/
public function getDisplayName(): string
{
return __('plugins.blocks.mostRead.displayName');
}
/**
* Description shown in the plugins list.
*/
public function getDescription(): string
{
return __('plugins.blocks.mostRead.description');
}
/**
* Add the settings action to the plugin entry in the plugins list.
*/
public function getActions($request, $actionArgs): array
{
// The settings belong to a journal; there is nothing to configure site-wide.
if (!$request->getContext()) {
return parent::getActions($request, $actionArgs);
}
$router = $request->getRouter();
return array_merge(
$this->getEnabled() ? [
new LinkAction(
'settings',
new AjaxModal(
$router->url($request, null, null, 'manage', null, array_merge($actionArgs, ['verb' => 'settings'])),
$this->getDisplayName()
),
__('manager.plugins.settings'),
null
),
] : [],
parent::getActions($request, $actionArgs)
);
}
/**
* Show and save the settings form.
*/
public function manage($args, $request): JSONMessage
{
$context = $request->getContext();
if ($request->getUserVar('verb') !== 'settings' || !$context) {
return parent::manage($args, $request);
}
$form = new MostReadSettingsForm($this, $context->getId());
if ($request->getUserVar('save')) {
$form->readInputData();
if ($form->validate()) {
$form->execute();
return new JSONMessage(true);
}
} else {
$form->initData();
}
return new JSONMessage(true, $form->fetch($request));
}
/**
* Render the block for the journal of the request.
*
* The list is cached per journal and language as it is rendered - title,
* best id and count - so a page view costs one cache read, not one query per
* article.
*
* @param null|mixed $request
*/
public function getContents($templateMgr, $request = null): string
{
$request ??= Application::get()->getRequest();
$context = $request->getContext();
if (!$context) {
return '';
}
$contextId = (int) $context->getId();
$locale = Locale::getLocale();
$items = Cache::remember(
$this->getCacheKey($contextId, $locale),
self::CACHE_TTL,
fn () => $this->loadMostRead($contextId, $locale)
);
$mostRead = [];
foreach ($items as $item) {
$mostRead[] = [
'url' => $this->submissionUrl($request, $context, $item['bestId']),
'metric' => $item['metric'],
'title' => self::readableTitle($item['title']),
];
}
$titles = self::decodeTitles($this->getSetting($contextId, 'mostReadBlockTitle'));
$templateMgr->assign([
'blockTitle' => $titles[$locale] ?? '',
'mostRead' => $mostRead,
]);
return parent::getContents($templateMgr, $request);
}
/**
* The reader's page of a published submission: OJS opens the article, OMP the
* monograph in the catalogue.
*/
protected function submissionUrl($request, $context, string $bestId): string
{
return Application::get()->getName() === 'omp'
? $request->url($context->getPath(), 'catalog', 'book', [$bestId])
: $request->url($context->getPath(), 'article', 'view', [$bestId]);
}
/**
* The block titles per locale, from the stored JSON.
*
* @return array<string, string>
*/
public static function decodeTitles($stored): array
{
$titles = json_decode((string) $stored, true);
return is_array($titles) ? array_filter(array_map(fn ($title) => is_string($title) ? trim($title) : '', $titles), 'strlen') : [];
}
/**
* A setting read as a whole number within its limits, or its default.
*/
public static function boundedInt($value, int $default, int $max): int
{
return ctype_digit(trim((string) $value)) && (int) $value >= 1 ? min((int) $value, $max) : $default;
}
/**
* A title that wraps in a narrow sidebar. Titles pasted from a word processor often join their
* words with no-break spaces (U+00A0 or the entity), which turns the whole title into one
* word that cannot wrap and runs out of the block. Those spaces and line breaks become plain
* spaces; the rest of the HTML (italics, sub/superscript) is kept.
*/
public static function readableTitle(string $title): string
{
$title = str_ireplace([' ', ' ', ' '], ' ', $title);
$title = preg_replace('/[\s\x{00A0}\x{2007}\x{202F}]+/u', ' ', $title) ?? $title;
return trim($title);
}
/**
* Build the cache key for a context and a locale.
*/
public function getCacheKey(int $contextId, string $locale): string
{
return "plugins.blocks.mostRead.{$contextId}.{$locale}";
}
/**
* Clear the cached lists of a context, in every language it offers.
*/
public function clearCache(int $contextId): void
{
$context = Application::getContextDAO()->getById($contextId);
foreach ($context ? (array) $context->getSupportedLocales() : [] as $locale) {
Cache::forget($this->getCacheKey($contextId, $locale));
}
}
/**
* Query the most read published articles of a context, ready to display.
*
* @return array<int, array{bestId: string|int, metric: int, title: string}>
*/
public function loadMostRead(int $contextId, string $locale): array
{
$days = self::boundedInt($this->getSetting($contextId, 'mostReadDays'), self::DEFAULT_DAYS, self::MAX_DAYS);
$count = self::boundedInt($this->getSetting($contextId, 'mostReadCount'), self::DEFAULT_COUNT, self::MAX_COUNT);
$totals = $this->getStatsService()->getTotals([
'dateStart' => date('Y-m-d', strtotime('-' . $days . ' days')),
'contextIds' => [$contextId],
'count' => $count,
'assocTypes' => [Application::ASSOC_TYPE_SUBMISSION_FILE],
]);
$items = [];
foreach ($totals as $row) {
if (!$row->submission_id || !$row->metric) {
continue;
}
$submission = Repo::submission()->get((int) $row->submission_id);
$publication = $submission?->getCurrentPublication();
if (!$publication || (int) $publication->getData('status') !== PKPSubmission::STATUS_PUBLISHED) {
continue;
}
$items[] = [
'bestId' => $submission->getBestId(),
'metric' => (int) $row->metric,
'title' => (string) $publication->getLocalizedFullTitle($locale, 'html'),
];
}
return $items;
}
/**
* The publication statistics service of this OJS version.
*/
protected function getStatsService()
{
return app()->get('publicationStats');
}
}