forked from pkp/paperbuzz
-
Notifications
You must be signed in to change notification settings - Fork 2
/
PaperbuzzPlugin.php
461 lines (411 loc) · 17.2 KB
/
PaperbuzzPlugin.php
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
<?php
/**
* @file PaperbuzzPlugin.inc.php
*
* Copyright (c) 2013-2023 Simon Fraser University
* Copyright (c) 2003-2023 John Willinsky
* Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
*
* @class PaperbuzzPlugin
* @brief Paperbuzz plugin class
*/
namespace APP\plugins\generic\paperbuzz;
use APP\core\Application;
use APP\core\Services;
use APP\plugins\generic\paperbuzz\PaperbuzzSettingsForm;
use APP\statistics\StatisticsHelper;
use APP\submission\Submission;
use APP\template\TemplateManager;
use PKP\cache\CacheManager;
use PKP\cache\FileCache;
use PKP\config\Config;
use PKP\core\JSONMessage;
use PKP\linkAction\LinkAction;
use PKP\linkAction\request\AjaxModal;
use PKP\plugins\GenericPlugin;
use PKP\plugins\Hook;
class PaperbuzzPlugin extends GenericPlugin
{
public const PAPERBUZZ_API_URL = 'https://api.paperbuzz.org/v0/';
private FileCache $_paperbuzzCache;
private FileCache $_downloadsCache;
private Submission $_article;
/**
* @copydoc Plugin::register()
*/
public function register($category, $path, $mainContextId = null): bool
{
$success = parent::register($category, $path, $mainContextId);
if (!Config::getVar('general', 'installed')) {
return false;
}
$request = $this->getRequest();
$context = $request->getContext();
if ($success && $this->getEnabled($mainContextId)) {
$this->_registerTemplateResource();
if ($context && $this->getSetting($context->getId(), 'apiEmail')) {
// Add visualization to article view page
Hook::add('Templates::Article::Main', array($this, 'articleMainCallback'));
// Add visualization to preprint view page
Hook::add('Templates::Preprint::Main', array(&$this, 'preprintMainCallback'));
// Add JavaScript and CSS needed, when the article template is displyed
Hook::add('TemplateManager::display', array(&$this, 'templateManagerDisplayCallback'));
}
}
return $success;
}
/**
* @copydoc Plugin::getName()
*/
public function getName(): string
{
return 'PaperbuzzPlugin';
}
/**
* @copydoc Plugin::getDisplayName()
*/
public function getDisplayName(): string
{
return __('plugins.generic.paperbuzz.displayName');
}
/**
* @copydoc Plugin::getDescription()
*/
public function getDescription(): string
{
return __('plugins.generic.paperbuzz.description');
}
/**
* @copydoc Plugin::getActions()
*/
public function getActions($request, $actionArgs): array
{
$actions = parent::getActions($request, $actionArgs);
// Settings are only context-specific
if (!$this->getEnabled()) {
return $actions;
}
$router = $request->getRouter();
$linkAction = new LinkAction(
id: 'settings',
actionRequest: new AjaxModal(
url: $router->url(
request: $request,
op: 'manage',
params: [
'verb' => 'settings',
'plugin' => $this->getName(),
'category' => 'generic'
]
),
title: $this->getDisplayName()
),
title: __('manager.plugins.settings')
);
array_unshift($actions, $linkAction);
return $actions;
}
/**
* @copydoc Plugin::manage()
*/
public function manage($args, $request): JSONMessage
{
switch ($request->getUserVar('verb')) {
case 'settings':
$form = new PaperbuzzSettingsForm($this);
if ($request->getUserVar('save')) {
$form->readInputData();
if ($form->validate()) {
$form->execute($request);
return new JSONMessage(true);
}
}
$form->initData($request);
return new JSONMessage(true, $form->fetch($request));
}
return parent::manage($args, $request);
}
/**
* Template manager hook callback.
* Add JavaScript and CSS required for the visualization.
*/
public function templateManagerDisplayCallback(string $hookName, array $params): bool
{
/** @var PKPTemplateManager $templateMgr */
$templateMgr =& $params[0];
/** @var string $template */
$template =& $params[1];
$application = Application::get();
$applicationName = $application->getName();
($applicationName == 'ops' ? $publication = 'preprint' : $publication = 'article');
if ($template == 'frontend/pages/' . $publication . '.tpl') {
$request = $this->getRequest();
$baseImportPath = $request->getBaseUrl() . '/' . $this->getPluginPath() . '/' . 'paperbuzzviz' . '/';
$templateMgr = TemplateManager::getManager($request);
$templateMgr->addJavaScript('d3', 'https://d3js.org/d3.v4.min.js', array('context' => 'frontend-'.$publication.'-view'));
$templateMgr->addJavaScript('d3-tip', 'https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.9.1/d3-tip.min.js', array('context' => 'frontend-'.$publication.'-view'));
$templateMgr->addJavaScript('paperbuzzvizJS', $baseImportPath . 'paperbuzzviz.js', array('context' => 'frontend-'.$publication.'-view'));
$templateMgr->addStyleSheet('paperbuzzvizCSS', $baseImportPath . 'assets/css/paperbuzzviz.css', array('context' => 'frontend-'.$publication.'-view'));
}
return Hook::CONTINUE;
}
/**
* Adds the visualization of the preprint level metrics.
*/
public function preprintMainCallback(string $hookName, array $params): bool
{
/** @var \Smarty $smarty */
$smarty = &$params[1];
/** @var string $output */
$output = &$params[2];
/** @var Submission $preprint */
$preprint = $smarty->getTemplateVars('preprint');
$this->_article = $preprint;
$originalPublication = $this->_article->getOriginalPublication();
if (!$originalPublication) {
return Hook::CONTINUE;
}
$request = $this->getRequest();
$context = $request->getContext();
$paperbuzzJsonDecoded = $this->_getPaperbuzzJsonDecoded();
$downloadJsonDecoded = [];
if (!$this->getSetting($context->getId(), 'hideDownloads')) {
$downloadJsonDecoded = $this->_getDownloadsJsonDecoded();
}
if (!empty($downloadJsonDecoded) || !empty($paperbuzzJsonDecoded)) {
$allStatsJson = $this->_buildRequiredJson($paperbuzzJsonDecoded, $downloadJsonDecoded);
$smarty->assign('allStatsJson', $allStatsJson);
if (!empty($originalPublication->getData('datePublished'))) {
$datePublishedShort = date('[Y, n, j]', strtotime($originalPublication->getData('datePublished')));
$smarty->assign('datePublished', $datePublishedShort);
}
$showMini = $this->getSetting($context->getId(), 'showMini') ? 'true' : 'false';
$smarty->assign('showMini', $showMini);
$metricsHTML = $smarty->fetch($this->getTemplateResource('output.tpl'));
$output .= $metricsHTML;
}
return Hook::CONTINUE;
}
/**
* Adds the visualization of the article level metrics.
*/
public function articleMainCallback(string $hookName, array $params): bool
{
/** @var \Smarty $smarty */
$smarty =& $params[1];
/** @var string $output */
$output =& $params[2];
/** @var Submission $article */
$article = $smarty->getTemplateVars('article');
$this->_article = $article;
$originalPublication = $this->_article->getOriginalPublication();
if (!$originalPublication) {
return Hook::CONTINUE;
}
$request = $this->getRequest();
$context = $request->getContext();
$paperbuzzJsonDecoded = $this->_getPaperbuzzJsonDecoded();
$downloadJsonDecoded = [];
if (!$this->getSetting($context->getId(), 'hideDownloads')) {
$downloadJsonDecoded = $this->_getDownloadsJsonDecoded();
}
if (!empty($downloadJsonDecoded) || !empty($paperbuzzJsonDecoded)) {
$allStatsJson = $this->_buildRequiredJson($paperbuzzJsonDecoded, $downloadJsonDecoded);
$smarty->assign('allStatsJson', $allStatsJson);
if (!empty($originalPublication->getData('datePublished'))) {
$datePublishedShort = date('[Y, n, j]', strtotime($originalPublication->getData('datePublished')));
$smarty->assign('datePublished', $datePublishedShort);
}
$showMini = $this->getSetting($context->getId(), 'showMini') ? 'true' : 'false';
$smarty->assign('showMini', $showMini);
$metricsHTML = $smarty->fetch($this->getTemplateResource('output.tpl'));
$output .= $metricsHTML;
}
return Hook::CONTINUE;
}
//
// Private helper methods.
//
/**
* Get Paperbuzz events for the article.
*
* @return array JSON decoded paperbuzz result or an empty array
*/
public function _getPaperbuzzJsonDecoded(): array
{
if (!isset($this->_paperbuzzCache)) {
$cacheManager = CacheManager::getManager();
/** @var FileCache $_paperbuzzCache */
$this->_paperbuzzCache = $cacheManager->getCache('paperbuzz', $this->_article->getId(), array(&$this, '_paperbuzzCacheMiss'));
}
if (time() - $this->_paperbuzzCache->getCacheTime() > 60 * 60 * 24) {
// Cache is older than one day, erase it.
$this->_paperbuzzCache->flush();
}
$cacheContent = $this->_paperbuzzCache->getContents() ?? [];
return $cacheContent;
}
/**
* Cache miss callback.
*
* @param FileCache $cache
* @return array JSON decoded paperbuzz result or an empty array
*/
public function _paperbuzzCacheMiss(FileCache $cache): array
{
$request = $this->getRequest();
$context = $request->getContext();
$apiEmail = $this->getSetting($context->getId(), 'apiEmail');
$url = self::PAPERBUZZ_API_URL . 'doi/' . $this->_article->getCurrentPublication()->getDoi() . '?email=' . urlencode($apiEmail);
// For teting use one of the following two lines instead of the line above and do not forget to clear the cache
// $url = self::PAPERBUZZ_API_URL . 'doi/10.1787/180d80ad-en?email=' . urlencode($apiEmail);
// $url = self::PAPERBUZZ_API_URL . 'doi/10.1371/journal.pmed.0020124?email=' . urlencode($apiEmail);
$paperbuzzStatsJsonDecoded = [];
$httpClient = Application::get()->getHttpClient();
try {
$response = $httpClient->request('GET', $url);
} catch (\GuzzleHttp\Exception\RequestException $e) {
return $paperbuzzStatsJsonDecoded;
}
$resultJson = $response->getBody()->getContents();
if ($resultJson) {
$paperbuzzStatsJsonDecoded = @json_decode($resultJson, true);
}
$cache->setEntireCache($paperbuzzStatsJsonDecoded);
return $paperbuzzStatsJsonDecoded;
}
/**
* Get OJS download stats for the article.
*/
public function _getDownloadsJsonDecoded(): array
{
if (!isset($this->_downloadsCache)) {
$cacheManager = CacheManager::getManager();
/** @var FileCache $_downloadsCache */
$this->_downloadsCache = $cacheManager->getCache('paperbuzz-downloads', $this->_article->getId(), array(&$this, '_downloadsCacheMiss'));
}
if (time() - $this->_downloadsCache->getCacheTime() > 60 * 60 * 24) {
// Cache is older than one day, erase it.
$this->_downloadsCache->flush();
}
$cacheContent = $this->_downloadsCache->getContents() ?? [];
return $cacheContent;
}
/**
* Callback to fill cache with data, if empty.
*/
public function _downloadsCacheMiss(FileCache $cache): array
{
// Note: monthly and daily stats needs to be separated into different calls, because
// we need daily stats only for the first 30 days of the publication.
// Stats per year could be calculated from the montly stats, but we use the extra call for this too.
$downloadStatsByYear = $this->_getDownloadStats(StatisticsHelper::STATISTICS_DIMENSION_YEAR);
$downloadStatsByMonth = $this->_getDownloadStats(StatisticsHelper::STATISTICS_DIMENSION_MONTH);
$downloadStatsByDay = $this->_getDownloadStats(StatisticsHelper::STATISTICS_DIMENSION_DAY);
// Prepare stats data so that they can be overtaken for the custom array format i.e. JSON response.
list($total, $byDay, $byMonth, $byYear) = $this->_prepareDownloadStats($downloadStatsByYear, $downloadStatsByMonth, $downloadStatsByDay);
$downloadsArray = $this->_buildDownloadStatsJsonDecoded($total, $byDay, $byMonth, $byYear);
$cache->setEntireCache($downloadsArray);
return $downloadsArray;
}
/**
* Get download stats for the passed article ID, aggregated by the given time interval.
*/
public function _getDownloadStats(string $timelineInterval): array
{
$context = $this->getRequest()->getContext();
$datePublished = $this->_article->getOriginalPublication()->getData('datePublished');
$dateStart = date('Y-m-d', strtotime($datePublished));
$dateEnd = date('Y-m-d', strtotime('yesterday'));
if ($timelineInterval == StatisticsHelper::STATISTICS_DIMENSION_DAY) {
// Consider only the first 30 days after the article publication
$dateEnd = date('Y-m-d', strtotime('+30 days', strtotime($datePublished)));
}
$filters = [
'dateStart' => $dateStart,
'dateEnd' => $dateEnd,
'contextIds' => [$context->getId()],
'submissionIds' => [$this->_article->getId()],
'assocTypes' => [Application::ASSOC_TYPE_SUBMISSION_FILE]
];
$metricsQB = Services::get('publicationStats')->getQueryBuilder($filters);
$metricsQB = $metricsQB->getSum([$timelineInterval]);
$metricsQB->orderBy($timelineInterval, StatisticsHelper::STATISTICS_ORDER_ASC);
$data = $metricsQB->get()->toArray();
return $data;
}
/**
* Prepare stats to return data in a format
* that can be used to build the statistics JSON response
* for the article page.
*/
public function _prepareDownloadStats(array $statsByYear, array $statsByMonth, array $statsByDay): array
{
$total = 0;
$byYear = [];
$byMonth = [];
$byDay = [];
foreach ($statsByYear as $yearlyData) {
$yearlyData = (array) $yearlyData;
$yearEvent = [];
$yearEvent['count'] = $yearlyData['metric'];
$date = $yearlyData['year'];
$yearEvent['date'] = substr($date, 0, 4);
$byYear[] = $yearEvent;
$total += $yearlyData['metric'];
}
foreach ($statsByMonth as $monthlyData) {
$monthlyData = (array) $monthlyData;
$monthEvent = [];
$monthEvent['count'] = $monthlyData['metric'];
$date = $monthlyData['month'];
$monthEvent['date'] = substr($date, 0, 7);
$byMonth[] = $monthEvent;
}
foreach ($statsByDay as $dailyData) {
$dailyData = (array) $dailyData;
$dayEvent = [];
$dayEvent['count'] = $dailyData['metric'];
$date = $dailyData['day'];
$dayEvent['date'] = $date;
$byDay[] = $dayEvent;
}
return array($total, $byDay, $byMonth, $byYear);
}
/**
* Build article download statistics array ready for JSON response
*/
public function _buildDownloadStatsJsonDecoded(int $total, array $byDay, array $byMonth, array $byYear): array
{
$response = [];
$event = [];
if ($total > 0) {
$event['events'] = null;
$event['events_count'] = $total;
$event['events_count_by_day'] = $byDay;
$event['events_count_by_month'] = $byMonth;
$event['events_count_by_year'] = $byYear;
$event['source']['display_name'] = __('plugins.generic.paperbuzz.sourceName.fileDownloads');
$event['source_id'] = 'fileDownloads';
$response[] = $event;
}
return $response;
}
/**
* Build the required article information for the
* metrics visualization.
*
* @param array $eventsData Decoded JSON result from Paperbuzz
* @param array $downloadData Download stats data ready for JSON encoding
* @return string JSON response
*/
public function _buildRequiredJson(array $eventsData = [], array $downloadData = []): string
{
if (empty($eventsData['altmetrics_sources'])) {
$eventsData['altmetrics_sources'] = [];
}
$allData = array_merge($downloadData, $eventsData['altmetrics_sources']);
$eventsData['altmetrics_sources'] = $allData;
return json_encode($eventsData);
}
}