Commit 8d5ef1b4 authored by Charles Bourdot's avatar Charles Bourdot
Browse files

Changements PHP stan et nouvelles fonctions post GT-OJS

parent 6c844968
Loading
Loading
Loading
Loading
+38 −34
Changes for ArticleImageDataHandler.inc.php: 38 added lines, 34 removed lines.
Original line number Diff line number Diff line
<?php

namespace APP\plugins\generic\xml2html;
/**
 * @file plugins/generic/xml2html/ArticleImageDataHandler.inc.php
 *
 * @brief OJS handler for images of zip galleys: article/zimage/{submissionId}/{galleyId}/{imageName}
 *
 * Extends ArticleHandler to reuse its authorization, its published/preview checks
 * and its subscription and purchase checks.
 */

require_once(__DIR__ . '/ImageUtils.php');
namespace APP\plugins\generic\xml2html;

use APP\core\Request;
use APP\facades\Repo;
use APP\handler\Handler;
use APP\pages\article\ArticleHandler;
use PKP\submission\PKPSubmission;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ArticleImageDataHandler extends Handler
class ArticleImageDataHandler extends ArticleHandler
{
    private $fs;

    public function __construct()
    public function zimage(array $args, Request $request): void
    {
        parent::__construct();
        $this->fs = ImageUtils::buildFileSystem($this);
        $galleyId = (int) ($args[1] ?? 0);
        $imageName = (string) ($args[2] ?? '');

        // The galley may belong to an earlier version of the article
        $user = $request->getUser();
        $canPreview = $user && Repo::submission()->canPreview($user, $this->article);
        $requestedGalley = null;
        foreach ($this->article->getData('publications') as $publication) {
            if ($publication->getData('status') !== PKPSubmission::STATUS_PUBLISHED && !$canPreview) {
                continue;
            }

    public function zimage(array $args, Request $request)
    {
        $submissionId = (int)$args[0];
        $galleyId = (int)$args[1];
        $imgName = $args[2];

        $submission = Repo::submission()->get($submissionId);
        if (!$submission) {
            header('HTTP/1.0 404 Not Found');
            exit;
            foreach ($publication->getData('galleys') as $galley) {
                if ($galley->getId() === $galleyId) {
                    $requestedGalley = $galley;
                }

        $galley = Repo::galley()->get($galleyId);
        if (!$galley) {
            header('HTTP/1.0 404 Not Found');
            exit;
            }

        $file = $galley->getFile();
        if (!$file) {
            header('HTTP/1.0 404 Not Found');
            exit;
        }

        $filename = $file->getData('path');
        $pathInfo = pathinfo($filename);
        $imagePath = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $pathInfo['filename'] . DIRECTORY_SEPARATOR . $imgName;
        $file = $requestedGalley?->getFile();
        if (!$file || $file->getData('mimetype') !== XML2HTMLPlugin::ZIP_MIMETYPE) {
            throw new NotFoundHttpException();
        }
        // userCanViewGalley() reads the galley from the handler
        $this->galley = $requestedGalley;
        if (!$this->userCanViewGalley($request, (string) $this->article->getId(), $requestedGalley->getId())) {
            throw new AccessDeniedHttpException();
        }

        ImageUtils::downloadImage($this->fs, $imagePath, $imgName);
        ImageUtils::sendImage($file->getData('path'), $imageName);
    }
}
+31 −46
Changes for BookImageDataHandler.inc.php: 31 added lines, 46 removed lines.
Original line number Diff line number Diff line
<?php

namespace APP\plugins\generic\xml2html;
/**
 * @file plugins/generic/xml2html/BookImageDataHandler.inc.php
 *
 * @brief OMP handler for images of zip publication format files:
 * catalog/zimage/{submissionId}/{submissionFileBestId}/{imageName}
 */

require_once(__DIR__ . '/ImageUtils.php');
namespace APP\plugins\generic\xml2html;

use APP\core\Application;
use APP\facades\Repo;
use APP\core\Request;
use APP\facades\Repo;
use APP\handler\Handler;
use APP\security\authorization\OmpPublishedSubmissionAccessPolicy;
use PKP\security\authorization\ContextRequiredPolicy;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class BookImageDataHandler extends Handler
{

    private $fs;

    public function __construct()
    {
        parent::__construct();
        $this->fs = ImageUtils::buildFileSystem($this);
    }

    /**
     * Image from zip archive submission file
     * @param array $args
     * @param Request $request
     * @return mixed
     * Same policies as OMP's CatalogBookHandler
     */
    public function zimage(array $args, Request $request)
    public function authorize($request, &$args, $roleAssignments)
    {
        $submissionId = (int)$args[0];
        $pubId = $args[1];
        $imgName = $args[2];

        $submission = Repo::submission()->get($submissionId);
        if (!$submission) {
            header('HTTP/1.0 404 Not Found');
            exit;
        $this->addPolicy(new ContextRequiredPolicy($request));
        $this->addPolicy(new OmpPublishedSubmissionAccessPolicy($request, $args, $roleAssignments));
        return parent::authorize($request, $args, $roleAssignments);
    }

        $pubFormatFiles = Repo::submissionFile()
            ->getCollector()
            ->filterBySubmissionIds([$submission->getId()])
            ->filterByAssoc(Application::ASSOC_TYPE_PUBLICATION_FORMAT)
            ->getMany();

        $publicationFile = NULL;
        foreach ($pubFormatFiles as $file){
            if($file->getBestId() == $pubId) {
                $publicationFile = $file;
    public function zimage(array $args, Request $request): void
    {
        $submission = $this->getAuthorizedContextObject(Application::ASSOC_TYPE_SUBMISSION);
        $submissionFileBestId = $args[1] ?? null;
        $imageName = (string) ($args[2] ?? '');

        $submissionFile = $submissionFileBestId === null
            ? null
            : Repo::submissionFile()->dao->getByBestId($submissionFileBestId, $submission->getId());
        if (!$submissionFile || $submissionFile->getData('mimetype') !== XML2HTMLPlugin::ZIP_MIMETYPE) {
            throw new NotFoundHttpException();
        }
        if (!BookUtils::userCanReadBookFile($request, $submission, $submissionFile)) {
            throw new AccessDeniedHttpException();
        }

        if (!$publicationFile) {
            header('HTTP/1.0 404 Not Found');
            exit;
        ImageUtils::sendImage($submissionFile->getData('path'), $imageName);
    }

        $pathInfo = pathinfo($publicationFile->getData('path'));
        $imagePath = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $pathInfo['filename'] . DIRECTORY_SEPARATOR . $imgName;
        ImageUtils::downloadImage($this->fs, $imagePath, $imgName);

    }


}

BookUtils.php

0 → 100644
+89 −0
Changes for BookUtils.php: 89 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

/**
 * @file plugins/generic/xml2html/BookUtils.php
 *
 * @brief OMP-only helpers: access checks and usage events for books and chapters.
 * Only called from OMP hooks and handlers, as it uses classes and constants that OJS does not have.
 */

namespace APP\plugins\generic\xml2html;

use APP\core\Application;
use APP\facades\Repo;
use APP\monograph\ChapterDAO;
use APP\observers\events\UsageEvent;
use APP\payment\omp\OMPCompletedPaymentDAO;
use APP\publicationFormat\PublicationFormat;
use APP\submission\Submission;
use PKP\core\PKPRequest;
use PKP\db\DAORegistry;
use PKP\submission\PKPSubmission;
use PKP\submissionFile\SubmissionFile;

class BookUtils
{
    /**
     * Mirror the checks of OMP's CatalogBookHandler::download() for a publication format file
     */
    public static function userCanReadBookFile(PKPRequest $request, Submission $submission, SubmissionFile $submissionFile): bool
    {
        $user = $request->getUser();
        if ($user && Repo::submission()->canPreview($user, $submission)) {
            return true;
        }

        if ($submissionFile->getData('assocType') != Application::ASSOC_TYPE_PUBLICATION_FORMAT
            || $submissionFile->getData('submissionId') != $submission->getId()) {
            return false;
        }

        $publicationFormat = null;
        foreach ($submission->getData('publications') as $publication) {
            if ($publication->getData('status') !== PKPSubmission::STATUS_PUBLISHED) {
                continue;
            }
            foreach ($publication->getData('publicationFormats') ?? [] as $format) {
                if ($format->getId() == $submissionFile->getData('assocId')) {
                    $publicationFormat = $format;
                }
            }
        }
        if (!$publicationFormat || !$publicationFormat->getIsAvailable()) {
            return false;
        }

        if (!$user && $request->getContext()->getData('restrictMonographAccess')) {
            return false;
        }

        /** @var OMPCompletedPaymentDAO $completedPaymentDao */
        $completedPaymentDao = DAORegistry::getDAO('OMPCompletedPaymentDAO');
        return $submissionFile->getDirectSalesPrice() === '0'
            || ($user && $completedPaymentDao->hasPaidPurchaseFile($user->getId(), $submissionFile->getId()));
    }

    /**
     * Usage event of the book or chapter landing page, as CatalogBookHandler::book() records it
     */
    public static function recordLandingPageView(PKPRequest $request, Submission $submission, $chapter): void
    {
        if ($chapter) {
            event(new UsageEvent(Application::ASSOC_TYPE_CHAPTER, $request->getContext(), $submission, null, null, $chapter));
        } else {
            event(new UsageEvent(Application::ASSOC_TYPE_SUBMISSION, $request->getContext(), $submission));
        }
    }

    /**
     * Usage event of a publication format file, as CatalogBookHandler::download() records it
     */
    public static function recordFileView(PKPRequest $request, Submission $submission, PublicationFormat $publicationFormat, SubmissionFile $submissionFile): void
    {
        $chapterId = $submissionFile->getData('chapterId');
        /** @var ChapterDAO $chapterDao */
        $chapterDao = DAORegistry::getDAO('ChapterDAO');
        $chapter = $chapterId ? $chapterDao->getChapter((int) $chapterId) : null;
        event(new UsageEvent(Application::ASSOC_TYPE_SUBMISSION_FILE, $request->getContext(), $submission, $publicationFormat, $submissionFile, $chapter));
    }
}
+34 −36
Changes for ImageUtils.php: 34 added lines, 36 removed lines.
Original line number Diff line number Diff line
<?php

/**
 * @file plugins/generic/xml2html/ImageUtils.php
 *
 * @brief Serve images extracted from a zip galley
 */

namespace APP\plugins\generic\xml2html;

use League\Flysystem\Filesystem;
use League\Flysystem\Local\LocalFilesystemAdapter;
use League\Flysystem\UnixVisibility\PortableVisibilityConverter;
use PKP\config\Config;
use PKP\file\FileManager;
use PKP\plugins\Hook;
use APP\handler\Handler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ImageUtils
{
    public static function buildFileSystem(Handler $handler) : Filesystem{
        $umask = Config::getVar('files', 'umask', 0022);
        $adapter = new LocalFilesystemAdapter(
            Config::getVar('files', 'files_dir'),
            PortableVisibilityConverter::fromArray([
                'file' => [
                    'public' => FileManager::FILE_MODE_MASK & ~$umask,
                    'private' => FileManager::FILE_MODE_MASK & ~$umask,
                ],
                'dir' => [
                    'public' => FileManager::DIRECTORY_MODE_MASK & ~$umask,
                    'private' => FileManager::DIRECTORY_MODE_MASK & ~$umask,
                ]
            ]),
            LOCK_EX,
            LocalFilesystemAdapter::DISALLOW_LINKS
        );
    /**
     * Send an image stored next to its zip archive, then end the request
     *
     * @param string $zipPath Path of the zip archive, relative to the files directory
     * @param string $imageName Requested file name, from the URL
     */
    public static function sendImage(string $zipPath, string $imageName): void
    {
        // Only a bare file name of an allowed image type: no directory, no XML source, no HTML cache
        $imageName = basename($imageName);
        $extension = strtolower(pathinfo($imageName, PATHINFO_EXTENSION));
        if (!in_array($extension, XML2HTMLPlugin::IMAGE_EXTENSIONS, true)) {
            throw new NotFoundHttpException();
        }

        Hook::call('File::adapter', [&$adapter, $handler]);
        $pathInfo = pathinfo($zipPath);
        $imagePath = $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '/' . $imageName;

        return new Filesystem($adapter);
        $fs = app()->get('file')->fs;
        if (!$fs->fileExists($imagePath)) {
            throw new NotFoundHttpException();
        }

    public static function downloadImage(Filesystem $fs, string $path, string $name){
        $mimetype = 'application/octet-stream';
        $filesize = $fs->fileSize($path);
        $encodedFilename = urlencode($name);
        $mimetype = $extension === 'svg' ? 'image/svg+xml' : $fs->mimeType($imagePath);
        header("Content-Type: {$mimetype}");
        header("Content-Length: {$filesize}");
        header('Accept-Ranges: none');
        header('Content-Disposition: inline' . ";filename=\"{$encodedFilename}\";filename*=UTF-8''{$encodedFilename}");
        header('Cache-Control: private'); // Workarounds for IE weirdness
        header('Pragma: public');
        fpassthru($fs->readStream($path));
        header('Content-Length: ' . $fs->fileSize($imagePath));
        header('Content-Disposition: inline; filename="' . rawurlencode($imageName) . '"');
        header('X-Content-Type-Options: nosniff');
        // Neutralizes scripts in SVG files opened directly
        header("Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox");
        header('Cache-Control: private');
        fpassthru($fs->readStream($imagePath));
        exit;
    }
}
+3 −2
Changes for README-fr.md: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -197,7 +197,8 @@ Dans le second cas :
 - l'archive est décompressée dans le dossier du zip ;
 - le dossier décompressé est renommé avec l'id unique généré par ojs ;
 - le fichier xml est renommé avec ce même identifiant : `[id]/[id].xml` ; 
 - les urls des images sont de la forme `[idarticle]/zimage/[id1]/[id2][nom_image].[extension]`.
 - le rendu HTML est mis en cache dans ce même dossier sous la forme `[id].[format].[locale].html`, et régénéré quand le zip ou une feuille XSL est modifié ;
 - les urls des images sont de la forme `article/zimage/[idSoumission]/[idGalée]/[image]` (OJS) ou `catalog/zimage/[idSoumission]/[idFichier]/[image]` (OMP). Elles suivent les règles d'accès de la galée (publication, abonnement, achat) ; seuls les fichiers `jpg`, `jpeg`, `png`, `gif`, `svg` et `webp` sont servis.



@@ -254,4 +255,4 @@ Par défaut :

### Mise en forme des contenus (CSS)

– 
Des feuilles de style personnalisées pour la page d'accueil et la vue de lecture peuvent être déposées dans les paramètres du plugin. Elles sont enregistrées dans le dossier public de la revue ou de la presse (`public/journals/[id]/` ou `public/presses/[id]/`).
Loading