Skip to content

Commit

Permalink
updates for OJS 3.2
Browse files Browse the repository at this point in the history
  • Loading branch information
RBoelter committed Nov 13, 2020
1 parent 86624ae commit 312e53e
Show file tree
Hide file tree
Showing 6 changed files with 822 additions and 95 deletions.
674 changes: 674 additions & 0 deletions LICENSE

Large diffs are not rendered by default.

113 changes: 47 additions & 66 deletions MostViewedHandler.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@

import('lib.pkp.classes.scheduledTask.ScheduledTask');

/**
* @file plugins/generic/mostViewed/MostViewedHandler.inc.php
*
* Copyright (c) 2014-2020 Simon Fraser University
* Copyright (c) 2003-2020 John Willinsky
* Copyright (c) 2020 Ronny Bölter, Leibniz Institute for Psychology (ZPID)
*
* Distributed under the GNU GPL v3. For full terms see the file LICENSE.
*
* @class MostViewedHandler
* @ingroup plugins_generic_mostViewed
*
* @brief Class for cron job functions.
*/
class MostViewedHandler extends ScheduledTask
{
/**
Expand All @@ -14,6 +28,8 @@ public function getName()


/**
* This function is called via cron job or acron plugin.
*
* @copydoc ScheduledTask::executeActions()
*/
public function executeActions()
Expand All @@ -35,13 +51,13 @@ public function executeActions()
$settings = $plugin->getSetting($context->getId(), 'settings');
if ($settings) {
$settings = json_decode($settings, true);
if (intval($settings['days']) > 0) {
if (key_exists('days', $settings) && is_int($settings['days']) && intval($settings['days']) > 0) {
$mostReadDays = intval($settings['days']);
}
if (intval($settings['amount']) > 0) {
if (key_exists('amount', $settings) && is_int($settings['amount']) && intval($settings['amount']) > 0) {
$amount = intval($settings['amount']);
}
if (intval($settings['years']) > 0) {
if (key_exists('years', $settings) && is_int($settings['years']) && intval($settings['years']) > 0) {
$maxYearsBack = intval($settings['years']);
} else {
$maxYearsBack = null;
Expand All @@ -53,40 +69,51 @@ public function executeActions()
return true;
}

public function saveMetricsToPluginSettings($plugin, $contextId, $mostReadDays = 30, $range = 5, $date = null)
/**
* Saves the metrics to plugin settings to keep the page load as fast as possible.
* This function is called when saving the plugin settings and daily via cron job/acron plugin.
*
* @param $plugin
* @param $contextId
* @param int $mostReadDays
* @param int $range
* @param null $maxYearsBack
*/
public function saveMetricsToPluginSettings($plugin, $contextId, $mostReadDays = 30, $range = 5, $maxYearsBack = null)
{
if ($date != null && intval($date) > 0) {
if ($maxYearsBack != null && intval($maxYearsBack) > 0) {
$dateTime = new DateTime('now');
$date = $dateTime->modify('-'.$date.' year')->format('Y');
}
$versionString = DAORegistry::getDAO('VersionDAO')->getCurrentVersion()->getVersionString();
$articles = null;
if ($versionString && preg_match('/^3\.2/', $versionString) == 1) {
$articles = $this->getMetrics_3_2($contextId, $mostReadDays, $range, $date);
} else {
if ($versionString && preg_match('/^3\.1/', $versionString) == 1) {
$articles = $this->getMetrics_3_1($contextId, $mostReadDays, $range, $date);
}
$maxYearsBack = $dateTime->modify('-'.$maxYearsBack.' year')->format('Y');
}
$articles = $this->getMetrics($contextId, $mostReadDays, $range, $maxYearsBack);
if ($articles != null) {
$plugin->updateSetting($contextId, 'articles', json_encode($articles));
}
}

private function getMetrics_3_2($contextId, $mostReadDays, $range, $date)
/**
* This function gets the current metrics from the metrics table and sorts them depending on the settings of the plugin
*
* @param $contextId
* @param $mostReadDays
* @param $range
* @param $maxYearsBack
* @return array
*/
private function getMetrics($contextId, $mostReadDays, $range, $maxYearsBack)
{
$dayString = "-".$mostReadDays." days";
$range = $range + 1;
$daysAgo = date('Y-m-d', strtotime($dayString));
$dateStart = date('Y-m-d', strtotime($dayString));
$currentDate = date('Y-m-d');
$topSubmissions = Services::get('stats')->getOrderedObjects(
STATISTICS_DIMENSION_SUBMISSION_ID,
STATISTICS_ORDER_DESC,
[
'contextIds' => [$contextId],
'dateEnd' => $currentDate,
'dateStart' => $daysAgo,
'count' => $date ? null : $range,
'dateStart' => $dateStart,
'count' => $maxYearsBack ? null : $range,
'offset' => 0,
]
);
Expand All @@ -97,7 +124,7 @@ private function getMetrics_3_2($contextId, $mostReadDays, $range, $date)
$submissionService = Services::get('submission');
$submission = $submissionService->get($submissionId);
if ($submission) {
if ($date && $submission->getDatePublished() < $date) {
if ($maxYearsBack && $submission->getDatePublished() < $maxYearsBack) {
continue;
}
$articles[$submissionId]['articleId'] = $submissionId;
Expand All @@ -114,50 +141,4 @@ private function getMetrics_3_2($contextId, $mostReadDays, $range, $date)
return $articles;
}

/**
* @param $contextId
* @param $mostReadDays
* @param $range
* @param $date
* @return array
*/
private function getMetrics_3_1($contextId, $mostReadDays, $range, $date)
{
$publishedArticleDao = DAORegistry::getDAO('PublishedArticleDAO');
$dayString = "-".$mostReadDays." days";
$daysAgo = date('Ymd', strtotime($dayString));
$currentDate = date('Ymd');
$filter = array(
STATISTICS_DIMENSION_CONTEXT_ID => $contextId,
);
$filter[STATISTICS_DIMENSION_DAY]['from'] = $daysAgo;
$filter[STATISTICS_DIMENSION_DAY]['to'] = $currentDate;
$orderBy = array(STATISTICS_METRIC => STATISTICS_ORDER_DESC);
$column = array(STATISTICS_DIMENSION_SUBMISSION_ID);
import('lib.pkp.classes.db.DBResultRange');
$dbResultRange = new DBResultRange($date ? null : $range + 1);
$metricsDao =& DAORegistry::getDAO('MetricsDAO');
$result = $metricsDao->getMetrics(OJS_METRIC_TYPE_COUNTER, $column, $filter, $orderBy, $dbResultRange);
$articles = array();
$cc = 0;
foreach ($result as $resultRecord) {
$submissionId = $resultRecord[STATISTICS_DIMENSION_SUBMISSION_ID];
$article = $publishedArticleDao->getById($submissionId);
if ($article) {
if ($date && $article->getDatePublished() < $date) {
continue;
}
$articles[$submissionId]['articleId'] = $article->getBestArticleId();
$articles[$submissionId]['articleTitle'] = $article->getLocalizedTitle($article->getLocale());
$articles[$submissionId]['articleSubtitle'] = $article->getLocalizedSubtitle($article->getLocale());
$articles[$submissionId]['articleAuthor'] = $article->getAuthorString();
$articles[$submissionId]['metric'] = $resultRecord[STATISTICS_METRIC];
if (++$cc >= $range) {
break;
}
}
}

return $articles;
}
}
35 changes: 29 additions & 6 deletions MostViewedPlugin.inc.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
<?php
import('lib.pkp.classes.plugins.GenericPlugin');

/**
* @file plugins/generic/mostViewed/MostViewedPlugin.inc.php
*
* Copyright (c) 2014-2020 Simon Fraser University
* Copyright (c) 2003-2020 John Willinsky
* Copyright (c) 2020 Ronny Bölter, Leibniz Institute for Psychology (ZPID)
*
* Distributed under the GNU GPL v3. For full terms see the file LICENSE.
*
* @class MostViewedPlugin
* @ingroup plugins_generic_mostViewed
*
* @brief Class for plugin and handler registration
*/
class MostViewedPlugin extends GenericPlugin
{
/**
Expand All @@ -27,7 +41,7 @@ public function getDescription()
* @param null $mainContextId
* @return bool
*/
public function register($category, $path, $mainContextId = NULL)
public function register($category, $path, $mainContextId = null)
{
$success = parent::register($category, $path);
HookRegistry::register('AcronPlugin::parseCronTab', array($this, 'callbackParseCronTab'));
Expand All @@ -36,10 +50,11 @@ public function register($category, $path, $mainContextId = NULL)
$templateMgr = TemplateManager::getManager($request);
$templateMgr->addStyleSheet(
'mostViewedArticles',
$request->getBaseUrl() . '/' . $this->getPluginPath() . '/css/mostViewed.css'
$request->getBaseUrl().'/'.$this->getPluginPath().'/css/mostViewed.css'
);
HookRegistry::register('Templates::Index::journal', array($this, 'mostViewedContent'));
}

return $success;
}

Expand All @@ -53,14 +68,17 @@ public function mostViewedContent($hookName, $args)
$smarty =& $args[1];
$output =& $args[2];
$request = Application::get()->getRequest();
$contextId = $request->getContext()->getId();
$context = $request->getContext();
$contextId = ($context && $context->getId()) ? $context->getId() : CONTEXT_SITE;
$smarty->assign('mostReadArticles', json_decode($this->getSetting($contextId, 'articles'), true));
$settings = json_decode($this->getSetting($contextId, 'settings'), true);
if ($settings) {
if ($settings['title'])
if ($settings['title']) {
$smarty->assign('mostReadHeadline', $settings['title']);
if ($settings['position'])
}
if ($settings['position']) {
$smarty->assign('mostReadPosition', $settings['position']);
}
}
$output .= $smarty->fetch($this->getTemplateResource('mostViewed.tpl'));
}
Expand All @@ -75,6 +93,7 @@ public function getActions($request, $verb)
{
$router = $request->getRouter();
import('lib.pkp.classes.linkAction.request.AjaxModal');

return array_merge(
$this->getEnabled() ? array(
new LinkAction(
Expand Down Expand Up @@ -105,14 +124,17 @@ public function manage($args, $request)
$form = new MostViewedSettingsForm($this);
if (!$request->getUserVar('save')) {
$form->initData();

return new JSONMessage(true, $form->fetch($request));
}
$form->readInputData();
if ($form->validate()) {
$form->execute();

return new JSONMessage(true);
}
}

return parent::manage($args, $request);
}

Expand All @@ -126,8 +148,9 @@ function callbackParseCronTab($hookName, $args)
{
if ($this->getEnabled() || !Config::getVar('general', 'installed')) {
$taskFilesPath =& $args[0]; // Reference needed.
$taskFilesPath[] = $this->getPluginPath() . DIRECTORY_SEPARATOR . 'scheduledTasksAutoStage.xml';
$taskFilesPath[] = $this->getPluginPath().DIRECTORY_SEPARATOR.'scheduledTasksAutoStage.xml';
}

return false;
}
}
30 changes: 29 additions & 1 deletion MostViewedSettingsForm.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,27 @@

import('lib.pkp.classes.form.Form');


/**
* @file plugins/generic/mostViewed/MostViewedSettingsForm.inc.php
*
* Copyright (c) 2014-2020 Simon Fraser University
* Copyright (c) 2003-2020 John Willinsky
* Copyright (c) 2020 Ronny Bölter, Leibniz Institute for Psychology (ZPID)
*
* Distributed under the GNU GPL v3. For full terms see the file LICENSE.
*
* @class MostViewedSettingsForm
* @ingroup plugins_generic_mostViewed
*
* @brief Class for MostViewed Plugin settings implementation
*/
class MostViewedSettingsForm extends Form
{
public $plugin;

/**
* @copydoc Form::__construct
*/
public function __construct($plugin)
{
parent::__construct($plugin->getTemplateResource('settings.tpl'));
Expand All @@ -15,6 +31,9 @@ public function __construct($plugin)
$this->addCheck(new FormValidatorCSRF($this));
}

/**
* @copydoc Form::initData
*/
public function initData()
{
$contextId = Application::get()->getRequest()->getContext()->getId();
Expand All @@ -30,12 +49,18 @@ public function initData()
parent::initData();
}

/**
* @copydoc Form::readInputData
*/
public function readInputData()
{
$this->readUserVars(['mostViewedTitle', 'mostViewedDays', 'mostViewedAmount', 'mostViewedYears', 'mostViewedPosition']);
parent::readInputData();
}

/**
* @copydoc Form::fetch
*/
public function fetch($request, $template = null, $display = false)
{
$templateMgr = TemplateManager::getManager($request);
Expand All @@ -44,6 +69,9 @@ public function fetch($request, $template = null, $display = false)
return parent::fetch($request, $template, $display);
}

/**
* @copydoc Form::execute
*/
public function execute(...$functionArgs)
{
$contextId = Application::get()->getRequest()->getContext()->getId();
Expand Down
17 changes: 12 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
# mostViewed [![Build Status](https://travis-ci.org/RBoelter/mostViewed.svg?branch=master)](https://travis-ci.org/RBoelter/mostViewed)
# mostViewed
[![Build Status](https://travis-ci.org/RBoelter/mostViewed.svg?branch=master)](https://travis-ci.org/RBoelter/mostViewed)
![GitHub release (latest by date including pre-releases)](https://img.shields.io/github/v/release/RBoelter/mostViewed?include_prereleases&label=latest%20release)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/RBoelter/mostViewed)
![GitHub](https://img.shields.io/github/license/RBoelter/mostViewed)
[![OJS-Version](https://img.shields.io/badge/pkp--ojs-3.2--x-brightgreen)](https://github.com/pkp/ojs/tree/stable-3_2_1)
![GitHub All Releases](https://img.shields.io/github/downloads/RBoelter/mostViewed/total)

## Installation
Install the plugin via plugin gallery
### Installation
Install the Plugin via Plugin Gallery (`Settings->Website->Plugins->Plugin Gallery`) or download the release matching your OJS Version
and install via `Settings->Website->Plugins->Upload A New Plugin`.

## Settings
### Settings
Go to the plugin settings and fill in the required fields:

![Settings](https://user-images.githubusercontent.com/7657717/77321369-6506ba00-6d12-11ea-96ce-a71448a49bc0.PNG "Settings")

The journal should now display the most viewed articles on its index page.
The journal should now display the most viewed articles on its index page.
Loading

0 comments on commit 312e53e

Please sign in to comment.