Commit 83884c9d authored by Jérôme Chauveau's avatar Jérôme Chauveau
Browse files

Premier jet pour gestion d'archives au format zip.

parent 5143eb73
Loading
Loading
Loading
Loading
+40
Changes for ImageDataHandler.inc.php: 40 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -2,10 +2,16 @@

import('pages.article.ArticleHandler');


class ImageDataHandler extends ArticleHandler
{


    /**
     * @param array $args
     * @param Request $request
     * @return mixed
     */
    public function image(array $args, Request $request)
    {
        $fileId = $args[1];
@@ -36,4 +42,38 @@ class ImageDataHandler extends ArticleHandler
        return Services::get('file')->download($submissionFile->getData('path'), $filename);
    }

    /**
     * Image from zip archive submission file
     * @param array $args
     * @param Request $request
     * @return mixed
     */
    public function zimage(array $args, Request $request)
    {

        import('lib.pkp.classes.submission.SubmissionFile');
        $imgName = $args[1];
        $dependentFilesIterator = Services::get('submissionFile')->getMany([
            'submissionIds' => [$this->article->getId()],
            'fileStages' => [SUBMISSION_FILE_SUBMISSION],
        ]);

        $submissionFile = null;
        $result = iterator_to_array($dependentFilesIterator);
        if(sizeof($result) != 1) {
            $request->getDispatcher()->handle404();
        }
        else {
            $submissionFile = $result[0];
            $filename = Services::get('file')
                ->formatFilename($submissionFile->getData('path'), $submissionFile->getLocalizedData('path'));
            $pathInfo = pathinfo($filename);
            $imagePath = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $pathInfo['filename'] . DIRECTORY_SEPARATOR . $imgName;
            return Services::get('file')->download($imagePath, $imgName);

        }

    }


}
+12
Changes for README.md: 12 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -22,3 +22,15 @@ Activer le plugin depuis la section *admin > website > plugins* d'OJS

Éditer ou remplacer le fichier *2html.xsl*. La tranformation fournie (issue de https://github.com/ncbi/JATSPreviewStylesheets/blob/master/xslt/main/jats-html.xsl) prend du XML JATS en entrée.


## Notes techniques

Le plugin peut gérer 2 cas d'utilisation pour les fichiers soumis :
1. upload d'un fichier xml + upload une à une des images associées à l'article 
2. upload d'une archive au format zip contenant le fichier xml + les images associées

Dans le second cas :
 - l'archive est dézippé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 rennomé avec ce même identifiant : `[id]/[id].xml`
 
+119 −4
Changes for XML2HTMLPlugin.php: 119 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -7,6 +7,8 @@
 */

import('lib.pkp.classes.plugins.GenericPlugin');
import('lib.pkp.classes.file.PrivateFileManager');
import('lib.pkp.classes.file.FileManager');

class XML2HTMLPlugin extends GenericPlugin
{
@@ -20,6 +22,7 @@ class XML2HTMLPlugin extends GenericPlugin
            HookRegistry::register('Templates::Article::Main', array($this, 'xml2html'));
            HookRegistry::register('TemplateManager::display', array($this, 'xml2htmlImports'));
            HookRegistry::register('LoadHandler', array($this, 'loadImageHandler'));
            HookRegistry::register('SubmissionFile::add', array($this, 'uploadHandler'));
        }

        return $success;
@@ -96,22 +99,36 @@ class XML2HTMLPlugin extends GenericPlugin
        $fileMgr = new PrivateFileManager();
        $filesDir = $fileMgr->getBasePath() . DIRECTORY_SEPARATOR;
        $xmlFilePath = NULL;
        $imgFiles = [];
        $submissionFile = null;
        $fileManager = new FileManager();
        $zipMode = FALSE;//true if submission file in a zip archive
        while ($sf = $resultFactory->next()) {
            $fileId = $sf->getData("fileId");
            $file = Services::get('file')->get($fileId);
            $filePath = $file->path;

            $submissionFileExtension = $fileManager->parseFileExtension($filePath);
            if($submissionFileExtension == 'zip'){
                $zipMode = TRUE;
                $fileInfo = pathinfo($filePath);
                $xmlFilePath =
                    $filesDir . $fileInfo['dirname'] . DIRECTORY_SEPARATOR . $fileInfo['filename'] . DIRECTORY_SEPARATOR . $fileInfo['filename'] .'.xml';
                //$output .= "<div>".$xmlFilePath."</div>";
                //return false;
                break;
            }
            else {
                $mimeType = $file->mimetype;
                if ($mimeType == 'text/xml') {
                    $xmlFilePath = $filesDir . $filePath;
                    $submissionFile = $sf;
                }
            }
        }


        if (is_null($xmlFilePath)) {
            $output .= "<div>error / todo</div>";
            $output .= "<div>error / todo ".$xmlFilePath."</div>";
            return false;
        }

@@ -128,13 +145,81 @@ class XML2HTMLPlugin extends GenericPlugin
        $proc = new XSLTProcessor;
        $proc->importStyleSheet($xsl); // attach the xsl rules

        $html = $this->resolveImagePaths($proc->transformToXML($xml), $submissionFile);
        $html = $zipMode
            ? $this->resolveZipImagePaths($proc->transformToXML($xml), $submissionId, $xmlFilePath)
            : $this->resolveImagePaths($proc->transformToXML($xml), $submissionFile);
        $output .=  $html;

        return false;

    }

    function uploadHandler($hookName, $params){
        //PKPSubmissionFileHandler::add
        //$submissionFile = Services::get('submissionFile')->add($submissionFile, $request);
        //$request = $params[1];
        //$submission = $request->getContext(ASSOC_TYPE_SUBMISSION);
        /**@var $submissionFile SubmissionFile**/
        $submissionFile = $params[0];
        //var_dump($request);
        $path = $submissionFile->getData('path');
        $fileManager = new FileManager();
        $submissionFileExtension = $fileManager->parseFileExtension($path);
        if($submissionFileExtension == 'zip'){
            $fileMgr = new PrivateFileManager();
            $filesDir = $fileMgr->getBasePath() . DIRECTORY_SEPARATOR;
            $zip = new ZipArchive;
            $zipPath = $filesDir . $path;
            if ($zip->open($zipPath) === TRUE) {
                $zipPathParts = pathinfo($zipPath);
                $archiveFolderName = NULL;
                if($zip->numFiles > 0) {//gets zip top folder name
                    $fileName = $zip->getNameIndex(0);
                    $fileInfo = pathinfo($fileName);
                    $archiveFolderName = $fileInfo["dirname"];
                }
                else {
                    throw new \Exception("Bad zip Submission file.");
                }
                $zip->extractTo($zipPathParts['dirname']);
                rename(
                    $zipPathParts['dirname'] . DIRECTORY_SEPARATOR . $archiveFolderName,
                    $zipPathParts['dirname'] . DIRECTORY_SEPARATOR . $zipPathParts['filename']);
                $zip->close();

                $files = scandir($zipPathParts['dirname'] . DIRECTORY_SEPARATOR . $zipPathParts['filename']);
                foreach ($files as $file) {
                    $extension = $fileManager->parseFileExtension($file);
                    if($extension == 'xml'){
                        $basePath = $zipPathParts['dirname'] . DIRECTORY_SEPARATOR . $zipPathParts['filename'] . '/';
                        rename(
                             $basePath. $file,
                            $basePath . $zipPathParts['filename'] . '.xml'
                            );
                    }
                    //var_dump($file);
                    //var_dump($extension);
                    //$submissionDir = Services::get('submissionFile')->getSubmissionDir($request->getContext()->getId(), $submission->getId());
                }



//                $submissionDir = Services::get('submissionFile')->getSubmissionDir($request->getContext()->getId(), $submission->getId());
//                $fileId = Services::get('file')->add(
//                    $_FILES['file']['tmp_name'],
//                    $submissionDir . '/' . uniqid() . '.' . $extension
//                );


            } else {
                echo 'échec';
            }
        }
        else
            throw new \Exception('Submission file must be a zip one.');

    }

    /**
     * @param $hookName string
     * @param $args array
@@ -144,7 +229,7 @@ class XML2HTMLPlugin extends GenericPlugin
        $page = $args[0];
        $op = $args[1];

        if ($page == 'article' && $op == 'image') {
        if ($page == 'article' && ($op == 'image' || $op == 'zimage')) {
            define('HANDLER_CLASS', 'ImageDataHandler');
            import('plugins.generic.xml2html.ImageDataHandler');
        }
@@ -200,6 +285,36 @@ class XML2HTMLPlugin extends GenericPlugin

    }

    function resolveZipImagePaths(string $htmlString, int $submissionId, string $xmlFilePath) {
        $pathInfo = pathinfo($xmlFilePath);
        $extractedZipPath = $pathInfo['dirname'];
        $files = scandir($extractedZipPath);
        foreach ($files as $file){
            $mt = mime_content_type($file);
            if($mt == 'image/jpeg' || $mt == 'image/png'){
                $request = $this->getRequest();
                $filePath = $request->url(
                    null, 'article',
                    'zimage',
                    array(
                        $submissionId,
                        //$dependentFile->getData('assocId'),
                        $file
                    )
                );


                $pattern = preg_quote(rawurlencode($file));
                $htmlString = preg_replace(
                    '/([Ss][Rr][Cc]|[Hh][Rr][Ee][Ff]|[Dd][Aa][Tt][Aa])\s*=\s*"([^"]*' . $pattern . ')"/',
                    '\1="' . $filePath . '"',
                    $htmlString);

            }
        }
        return $htmlString;
    }


}