Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new features for 3.4.0 version #24

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 87 additions & 1 deletion HypothesisPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,24 @@

use PKP\plugins\GenericPlugin;
use PKP\plugins\Hook;
use APP\core\Application;
use APP\template\TemplateManager;

class HypothesisPlugin extends GenericPlugin {
/**
* @copydoc Plugin::register()
*/
function register($category, $path, $mainContextId = null) {
if (parent::register($category, $path, $mainContextId)) {
Hook::add('ArticleHandler::download',array(&$this, 'callback'));
Hook::add('ArticleHandler::download', array(&$this, 'callback'));
Hook::add('TemplateManager::display', array(&$this, 'callbackTemplateDisplay'));
Hook::add('TemplateManager::display', [$this, 'addAnnotationNumberViewers']);
Hook::add('LoadHandler', array($this, 'addAnnotationsHandler'));
Hook::add('LoadComponentHandler', array($this, 'setupHypothesisHandler'));
Hook::add('AcronPlugin::parseCronTab', [$this, 'addTasksToCrontab']);

$this->addHandlerURLToJavaScript();

return true;
}
return false;
Expand Down Expand Up @@ -64,6 +73,7 @@ function callbackTemplateDisplay($hookName, $args) {
// template path contains the plugin path, and ends with the tpl file
if ( (strpos($template, $plugin) !== false) && ( (strpos($template, ':'.$submissiontpl, -1 - strlen($submissiontpl)) !== false) || (strpos($template, ':'.$issuetpl, -1 - strlen($issuetpl)) !== false))) {
$templateMgr->registerFilter("output", array($this, 'changePdfjsPath'));
$templateMgr->registerFilter("output", array($this, 'addHypothesisConfig'));
}
return false;
}
Expand All @@ -79,6 +89,82 @@ function changePdfjsPath($output, $templateMgr) {
return $newOutput;
}

/**
* Adds Hypothesis tab configuration so sidebar opens automatically when PDF has annotations
* @param $output string
* @param $templateMgr TemplateManager
* @return $string
*/
public function addHypothesisConfig($output, $templateMgr) {
if (preg_match('/<div[^>]+id="pdfCanvasContainer/', $output, $matches, PREG_OFFSET_CAPTURE)) {
$posMatch = $matches[0][1];
$config = $templateMgr->fetch($this->getTemplateResource('hypothesisConfig.tpl'));

$output = substr_replace($output, $config, $posMatch, 0);
$templateMgr->unregisterFilter('output', array($this, 'addHypothesisConfig'));
}
return $output;
}

public function addAnnotationNumberViewers($hookName, $args) {
$templateMgr = $args[0];
$template = $args[1];
$pagesToInsert = [
'frontend/pages/indexServer.tpl',
'frontend/pages/preprint.tpl',
'frontend/pages/preprints.tpl',
'frontend/pages/sections.tpl',
'frontend/pages/indexJournal.tpl',
'frontend/pages/article.tpl',
'frontend/pages/issue.tpl'
];

if (in_array($template, $pagesToInsert)) {
$request = Application::get()->getRequest();

$jsUrl = $request->getBaseUrl() . '/' . $this->getPluginPath() . '/js/addAnnotationViewers.js';
$styleUrl = $request->getBaseUrl() . '/' . $this->getPluginPath() . '/styles/annotationViewer.css';

$templateMgr->addJavascript('AddAnnotationViewers', $jsUrl, ['contexts' => 'frontend']);
$templateMgr->addStyleSheet('AnnotationViewerStyleSheet', $styleUrl, ['contexts' => 'frontend']);
}

return false;
}

public function addAnnotationsHandler($hookName, $args) {
$page = $args[0];
if ($page == 'annotations') {
define('HANDLER_CLASS', 'APP\plugins\generic\hypothesis\pages\annotations\AnnotationsHandler');
return true;
}
return false;
}

public function setupHypothesisHandler($hookName, $args) {
$component = &$args[0];
if ($component == 'plugins.generic.hypothesis.controllers.HypothesisHandler') {
return true;
}
return false;
}

public function addTasksToCrontab($hookName, $args) {
$taskFilesPath = &$args[0];
$taskFilesPath[] = $this->getPluginPath() . DIRECTORY_SEPARATOR . 'scheduledTasks.xml';
return false;
}

public function addHandlerURLToJavaScript()
{
$request = Application::get()->getRequest();
$templateMgr = TemplateManager::getManager($request);
$handlerUrl = $request->getDispatcher()->url($request, Application::ROUTE_COMPONENT, null, 'plugins.generic.hypothesis.controllers.HypothesisHandler');
$data = ['hypothesisHandlerUrl' => $handlerUrl];

$templateMgr->addJavaScript('HypothesisHandler', 'app = ' . json_encode($data) . ';', ['contexts' => 'frontend', 'inline' => true]);
}

/**
* Get the display name of this plugin
* @return string
Expand Down
22 changes: 22 additions & 0 deletions classes/Annotation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace APP\plugins\generic\hypothesis\classes;

class Annotation {
public $user;
public $dateCreated;
public $target;
public $content;

public function __construct(string $user, string $dateCreated, string $target, string $content) {
$this->user = $user;
$this->dateCreated = $dateCreated;
$this->target = $target;
$this->content = $content;
}

public static function __set_state($dump) {
$obj = new Annotation($dump['user'], $dump['dateCreated'], $dump['target'], $dump['content']);
return $obj;
}
}
23 changes: 23 additions & 0 deletions classes/HypothesisDAO.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace APP\plugins\generic\hypothesis\classes;

use PKP\db\DAO;
use Illuminate\Support\Facades\DB;

class HypothesisDAO extends DAO {
public function getDatePublished($submissionId): string {
$result = DB::table('submissions')
->where('submission_id', $submissionId)
->select('current_publication_id')
->first();
$currentPublicationId = get_object_vars($result)['current_publication_id'];

$result = DB::table('publications')
->where('publication_id', $currentPublicationId)
->select('date_published')
->first();

return get_object_vars($result)['date_published'];
}
}
142 changes: 142 additions & 0 deletions classes/HypothesisHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
<?php

namespace APP\plugins\generic\hypothesis\classes;

use APP\facades\Repo;
use APP\core\Application;
use APP\submission\Submission;
use APP\plugins\generic\hypothesis\classes\Annotation;
use APP\plugins\generic\hypothesis\classes\SubmissionAnnotations;

class HypothesisHelper {
public function getSubmissionsAnnotations($contextId) {
$submissions = Repo::submission()->getCollector()
->filterByContextIds([$contextId])
->filterByStatus([Submission::STATUS_PUBLISHED])
->getMany();

$groupsRequests = $this->getSubmissionsGroupsRequests($submissions, $contextId);
$submissionsAnnotations = [];
foreach ($groupsRequests as $groupRequest) {
$groupResponse = $this->getRequestAnnotations($groupRequest);
if (!is_null($groupResponse) && $groupResponse['total'] > 0) {
$submissionsAnnotations = array_merge(
$submissionsAnnotations,
$this->groupSubmissionsAnnotations($groupResponse, $contextId)
);
}
}

return $submissionsAnnotations;
}

private function getSubmissionsGroupsRequests($submissions, $contextId) {
$requests = [];
$requestPrefix = $currentRequest = "https://hypothes.is/api/search?limit=200&group=__world__";
$maxRequestLength = 4094;

foreach ($submissions as $submission) {
$submissionRequestParams = $this->getSubmissionRequestParams($submission, $contextId);

if(!is_null($submissionRequestParams)) {
if(strlen($currentRequest.$submissionRequestParams) < $maxRequestLength) {
$currentRequest .= $submissionRequestParams;
}
else {
$requests[] = $currentRequest;
$currentRequest = $requestPrefix . $submissionRequestParams;
}
}
}

if ($currentRequest != $requestPrefix) {
$requests[] = $currentRequest;
}

return $requests;
}

private function getSubmissionRequestParams($submission, $contextId) {
$submissionRequestParams = "";
$publication = $submission->getCurrentPublication();

if(is_null($publication))
return null;

$galleys = $publication->getData('galleys');
foreach ($galleys as $galley) {
if ($galley->getFileType() == 'application/pdf') {
$galleyDownloadURL = $this->getGalleyDownloadURL($contextId, $submission, $galley);
if (!is_null($galleyDownloadURL)) {
$submissionRequestParams .= "&uri={$galleyDownloadURL}";
}
}
}

return $submissionRequestParams;
}

private function getRequestAnnotations($requestURL) {
$ch = curl_init($requestURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
if(!$output || substr($output, 1, 8) != '"total":') return null;

return json_decode($output, true);
}

private function groupSubmissionsAnnotations($groupResponse, $contextId) {
$submissionsAnnotations = [];

foreach ($groupResponse['rows'] as $annotationResponse) {
$urlBySlash = explode("/", $annotationResponse['links']['incontext']);
$submissionBestId = $urlBySlash[count($urlBySlash) - 3];
$submissionId = Repo::submission()->getByBestId($submissionBestId, $contextId)->getId();

if(!array_key_exists($submissionId, $submissionsAnnotations)) {
$submissionsAnnotations[$submissionId] = new SubmissionAnnotations($submissionId);
}

$annotation = $this->getAnnotation($annotationResponse);
$submissionsAnnotations[$submissionId]->addAnnotation($annotation);
}

return $submissionsAnnotations;
}

private function getAnnotation($annotationResponse): Annotation {
$user = substr($annotationResponse['user'], 5, strlen($annotationResponse['user']) - 17);
$dateCreated = $annotationResponse['created'];
$content = $annotationResponse['text'];

$target = "";
if(isset($annotationResponse['target'][0]['selector'])) {
foreach ($annotationResponse['target'][0]['selector'] as $selector) {
if($selector['type'] == 'TextQuoteSelector') {
$target = $selector['exact'];
break;
}
}
}

return new Annotation($user, $dateCreated, $target, $content);
}

public function getGalleyDownloadURL($contextId, $submission, $galley) {
$request = Application::get()->getRequest();
$indexUrl = $request->getIndexUrl();
$context = Application::getContextDAO()->getById($contextId);
$contextPath = $context->getPath();
$submissionType = (Application::getName() == 'ojs2' ? 'article' : 'preprint');

$submissionFile = $galley->getFile();
if(is_null($submissionFile))
return null;

$submissionBestId = $submission->getBestId();
$galleyBestId = $galley->getBestGalleyId();
$fileId = $submissionFile->getId();

return $indexUrl . "/$contextPath/$submissionType/download/$submissionBestId/$galleyBestId/$fileId";
}
}
26 changes: 26 additions & 0 deletions classes/SubmissionAnnotations.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace APP\plugins\generic\hypothesis\classes;

use APP\plugins\generic\hypothesis\classes\Annotation;

class SubmissionAnnotations {
public $submissionId;
public $submission;
public $annotations;

public function __construct(int $submissionId) {
$this->submissionId = $submissionId;
$this->annotations = [];
}

public static function __set_state($dump) {
$obj = new SubmissionAnnotations($dump['submissionId']);
$obj->annotations = $dump['annotations'];
return $obj;
}

public function addAnnotation(Annotation $annotation) {
$this->annotations[] = $annotation;
}
}
36 changes: 36 additions & 0 deletions classes/tasks/UpdateAnnotationsCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace APP\plugins\generic\hypothesis\classes\tasks;

use PKP\scheduledTask\ScheduledTask;
use APP\core\Services;
use PKP\cache\CacheManager;
use APP\plugins\generic\hypothesis\classes\HypothesisHelper;

class UpdateAnnotationsCache extends ScheduledTask {

public function executeActions() {
$contextIds = Services::get('context')->getIds([
'isEnabled' => true,
]);

foreach ($contextIds as $contextId) {
$cacheManager = CacheManager::getManager();
$cache = $cacheManager->getFileCache(
$contextId,
'submissions_annotations',
[$this, 'cacheDismiss']
);

$cache->flush();
$hypothesisHelper = new HypothesisHelper();
$cache->setEntireCache($hypothesisHelper->getSubmissionsAnnotations($contextId));
}

return true;
}

function cacheDismiss() {
return null;
}
}
Loading