Commit 75072e24 authored by Bourdot's avatar Bourdot
Browse files

Landing page (métadonnées source) : <head> alimenté par les métadonnées du fichier importé

parent f3f2e0ee
Loading
Loading
Loading
Loading
+106 −8
Changes for XML2HTMLPlugin.php: 106 added lines, 8 removed lines.
Original line number Diff line number Diff line
@@ -280,28 +280,126 @@ class XML2HTMLPlugin extends GenericPlugin
        $templateMgr->assign('cssSideViewUrl', $this->getCssFileUrl($this->getRequest(), 'cssSideViewFile'));
        $templateMgr->assign('footerTemplate', $this->getTemplateResource('footer.tpl'));
        $templateMgr->assign('loadThemeStyles', (bool) $this->getSetting($context->getId(), 'loadThemeStyles'));

        // source metadata replace the matching OJS <meta> tags of the <head>
        $sourceMetas = [];
        if ($this->getSetting($context->getId(), 'metadataSource') === 'tei') {
            try {
                $sourceMetas = $this->getSourceMetas($filePath);
            } catch (\Throwable $e) {
                error_log('XML2HTMLPlugin metas error: ' . $e->getMessage());
            }
        }
        $sourceTitle = '';
        foreach ($sourceMetas as $meta) {
            if ($meta['name'] === 'citation_title') {
                $sourceTitle = $meta['content'];
                break;
            }
        }
        $templateMgr->assign('sourceTitle', $sourceTitle);
        if (!isset($templateMgr->registered_plugins['modifier']['xml2html_source_metas'])) {
            $templateMgr->registerPlugin('modifier', 'xml2html_source_metas', fn (string $header) => self::mergeSourceMetas($header, $sourceMetas));
        }

        $templateMgr->display($this->getTemplateResource($template));
    }

    /**
     * @brief HTML of a zip galley: transformed on first request, then cached next to the zip.
     * The cache is rebuilt when the zip or a stylesheet is newer than it.
     * @brief Metadata of the zip galley's XML, from the format's *-metas2html.xsl, cached next to the HTML
     * @return array<array{name: string, content: string, lang: string}>
     * @throws \Exception
     */
    private function getHtml(string $filePath, int $submissionId, int $galleyId, string $op): string
    private function getSourceMetas(string $filePath): array
    {
        $format = $this->getFormat();
        $metasFile = preg_replace('/\.html$/', '.metas.xml', XML2HTMLPlugin::getHTMLPathFromZipPath($filePath, $format));
        if (!$this->isCacheFresh($metasFile, $filePath, $format)) {
            $xmlFilePath = XML2HTMLPlugin::unzipXMLArchive($filePath);
            $transformed = XML2HTMLPlugin::transformMetas($xmlFilePath, $format);
            if (!$transformed) {
                throw new \Exception("Metadata transformation failed for {$filePath}");
            }
            file_put_contents($metasFile, $transformed, LOCK_EX);
        }

        $doc = new DOMDocument();
        if (!$doc->load($metasFile)) {
            throw new \Exception("Unreadable metadata file {$metasFile}");
        }
        $metas = [];
        foreach ($doc->getElementsByTagName('meta') as $meta) {
            $metas[] = [
                'name' => $meta->getAttribute('name'),
                'content' => $meta->getAttribute('content'),
                'lang' => $meta->getAttributeNS('http://www.w3.org/XML/1998/namespace', 'lang'),
            ];
        }
        return $metas;
    }

    // OJS <meta> tags that describe a source one and go with it
    private const RELATED_METAS = [
        'citation_author' => ['citation_author_institution', 'citation_author_orcid', 'citation_author_email'],
        'DC.Title' => ['DC.Title.Alternative'],
    ];

    /**
     * @brief Remove from the OJS header the <meta> tags given by the source, then append the source's.
     * The tags the source does not give (URLs, ISSN…) are kept.
     */
    private static function mergeSourceMetas(string $header, array $metas): string
    {
        if (!$metas) {
            return $header;
        }
        $names = array_unique(array_column($metas, 'name'));
        foreach ($names as $name) {
            $names = array_merge($names, self::RELATED_METAS[$name] ?? []);
        }
        $header = preg_replace_callback('/<meta\s+name="([^"]+)"[^>]*>[ \t]*\R?/i', function ($match) use ($names) {
            return in_array($match[1], $names, true) ? '' : $match[0];
        }, $header);

        foreach ($metas as $meta) {
            $header .= "\n" . '<meta name="' . htmlspecialchars($meta['name']) . '" content="' . htmlspecialchars($meta['content']) . '"'
                . ($meta['lang'] !== '' ? ' xml:lang="' . htmlspecialchars($meta['lang']) . '"' : '')
                . '/>';
        }
        return $header;
    }

    /**
     * @brief Sources format from settings, JATS by default
     */
    private function getFormat(): string
    {
        //get sources format from settings
        $format = $this->getSetting($this->getRequest()->getContext()->getId(), 'format');
        if (!in_array($format, ['JATS', 'TEI'])) {
            $format = 'JATS';//default value is JATS
        return in_array($format, ['JATS', 'TEI']) ? $format : 'JATS';
    }

        $htmlFile = XML2HTMLPlugin::getHTMLPathFromZipPath($filePath, $format);
    /**
     * @brief A cache file is fresh when it is newer than the zip and the format's stylesheets
     */
    private function isCacheFresh(string $cacheFile, string $filePath, string $format): bool
    {
        $fileMgr = new PrivateFileManager();
        $xslMtimes = array_map('filemtime', glob(dirname(__FILE__) . '/xsl/' . strtolower($format) . '/*.xsl') ?: []);
        $sourcesMtime = max(filemtime($fileMgr->getBasePath() . DIRECTORY_SEPARATOR . $filePath), ...($xslMtimes ?: [0]));
        return is_file($cacheFile) && filemtime($cacheFile) >= $sourcesMtime;
    }

    /**
     * @brief HTML of a zip galley: transformed on first request, then cached next to the zip.
     * The cache is rebuilt when the zip or a stylesheet is newer than it.
     * @throws \Exception
     */
    private function getHtml(string $filePath, int $submissionId, int $galleyId, string $op): string
    {
        $format = $this->getFormat();
        $htmlFile = XML2HTMLPlugin::getHTMLPathFromZipPath($filePath, $format);
        //make transfo only if html does not exist or is outdated
        if (is_file($htmlFile) && filemtime($htmlFile) >= $sourcesMtime) {
        if ($this->isCacheFresh($htmlFile, $filePath, $format)) {
            return file_get_contents($htmlFile);
        }

+4 −2
Changes for templates/LandingPage.tpl: 4 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,7 @@
 * @uses $text string HTML rendering of the galley
 * @uses $assetsPath string URL of the plugin's resources directory
 * @uses $cssLandingPageUrl string|null URL of the journal's custom CSS
 * @uses $sourceTitle string title of the source when $metadataSource is 'tei', empty otherwise
 *
 * @hook Templates::Article::Footer::PageFooter []
 *}
@@ -18,10 +19,11 @@
	<meta charset="{$defaultCharset|escape}">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>
		{$publication->getLocalizedFullTitle(null, 'html')|strip_tags}
		{if $sourceTitle}{$sourceTitle|escape}{else}{$publication->getLocalizedFullTitle(null, 'html')|strip_tags}{/if}
		{if $currentContext}| {$currentContext->getLocalizedName()|escape}{/if}
	</title>
	{load_header context="frontend"}
	{capture assign="frontendHeader"}{load_header context="frontend"}{/capture}
	{$frontendHeader|xml2html_source_metas}
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
	{if $loadThemeStyles}
		{load_stylesheet context="frontend"}
+3 −2
Changes for templates/LandingPageBook.tpl: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -10,10 +10,11 @@
	<meta charset="{$defaultCharset|escape}">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>
		{$pageTitle|strip_tags}
		{if $sourceTitle}{$sourceTitle|escape}{else}{$pageTitle|strip_tags}{/if}
		{if $currentContext}| {$currentContext->getLocalizedName()|escape}{/if}
	</title>
	{load_header context="frontend"}
	{capture assign="frontendHeader"}{load_header context="frontend"}{/capture}
	{$frontendHeader|xml2html_source_metas}
	{if $loadThemeStyles}
		{load_stylesheet context="frontend"}
	{/if}
+206 −14
Changes for xsl/jats/jats-metas2html.xsl: 206 added lines, 14 removed lines.
Original line number Diff line number Diff line
<?xml version="1.0"?>

<!-- Métadonnées de la source pour le <head> de la landing page (mode « métadonnées source ») :
     liste <metas><meta name content xml:lang/></metas> lue par XML2HTMLPlugin::getSourceMetas() -->
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xlink="http://www.w3.org/1999/xlink"
                xmlns:mml="http://www.w3.org/1998/Math/MathML"
                xmlns:xs="http://www.w3.org/1999/XSL/Transform"
                xmlns:xsl-="http://www.w3.org/1999/XSL/Transform"
                exclude-result-prefixes="xlink mml">
                exclude-result-prefixes="xlink">


    <xsl:output method="html" encoding="UTF-8" indent="no"/>
    <xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="yes"/>

    <xsl:strip-space elements="*"/>

    <xsl:variable name="journal" select="/article/front/journal-meta"/>
    <xsl:variable name="meta" select="/article/front/article-meta"/>
    <xsl:variable name="language">
        <xsl:call-template name="lang">
            <xsl:with-param name="ident" select="/article/@xml:lang"/>
        </xsl:call-template>
    </xsl:variable>

    <xsl:template match="/">
        <meta name="DC.title" content="{//article-title}"/>
        <meta name="DC.creator" content="{//contrib[@contrib-type='aut']//surname}"/>
        <meta name="DC.date" content="{//pub-date/year}"/>
        <meta name="DC.type" content="Text"/>
        <meta name="DC.format" content="text/html"/>
        <meta name="DC.language" content="{article/@xml:lang}"/>
        <meta name="DC.type" content="{article/@article-type}"/>
        <meta name="DC.rights" content="{//permissions/license/license-p}"/>
        <metas>
            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_journal_title'"/>
                <xsl:with-param name="content" select="($journal/journal-title-group/journal-title | $journal/journal-title)[1]"/>
            </xsl:call-template>
            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_issn'"/>
                <xsl:with-param name="content" select="($journal/issn[@pub-type='epub' or @publication-format='electronic'] | $journal/issn)[1]"/>
            </xsl:call-template>
            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_publisher DC.Publisher'"/>
                <xsl:with-param name="content" select="$journal/publisher/publisher-name[1]"/>
            </xsl:call-template>

            <xsl:variable name="title">
                <xsl:value-of select="normalize-space($meta/title-group/article-title)"/>
                <xsl:if test="normalize-space($meta/title-group/subtitle[1])">
                    <xsl:text> : </xsl:text>
                    <xsl:value-of select="normalize-space($meta/title-group/subtitle[1])"/>
                </xsl:if>
            </xsl:variable>
            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_title DC.Title'"/>
                <xsl:with-param name="content" select="$title"/>
            </xsl:call-template>
            <xsl:for-each select="$meta/title-group/trans-title-group">
                <xsl:call-template name="meta">
                    <xsl:with-param name="names" select="'DC.Title.Alternative'"/>
                    <xsl:with-param name="content" select="trans-title"/>
                    <xsl:with-param name="lang" select="@xml:lang"/>
                </xsl:call-template>
            </xsl:for-each>

            <xsl:variable name="authors" select="$meta/contrib-group/contrib[@contrib-type='author' or @contrib-type='aut']"/>
            <xsl:for-each select="$authors">
                <xsl:call-template name="meta">
                    <xsl:with-param name="names" select="'citation_author'"/>
                    <xsl:with-param name="content">
                        <xsl:apply-templates select="(name | string-name | collab)[1]" mode="name"/>
                    </xsl:with-param>
                </xsl:call-template>
                <xsl:for-each select="aff | /article//aff[@id = current()/xref[@ref-type='aff']/@rid]">
                    <xsl:call-template name="meta">
                        <xsl:with-param name="names" select="'citation_author_institution'"/>
                        <xsl:with-param name="content">
                            <xsl:choose>
                                <xsl:when test="institution">
                                    <xsl:for-each select="institution">
                                        <xsl:if test="position() > 1">, </xsl:if>
                                        <xsl:value-of select="."/>
                                    </xsl:for-each>
                                </xsl:when>
                                <xsl:otherwise>
                                    <xsl:for-each select="node()[not(self::label)]">
                                        <xsl:value-of select="."/>
                                    </xsl:for-each>
                                </xsl:otherwise>
                            </xsl:choose>
                        </xsl:with-param>
                    </xsl:call-template>
                </xsl:for-each>
                <xsl:call-template name="meta">
                    <xsl:with-param name="names" select="'citation_author_orcid'"/>
                    <xsl:with-param name="content" select="contrib-id[@contrib-id-type='orcid'][1]"/>
                </xsl:call-template>
            </xsl:for-each>
            <xsl:for-each select="$authors">
                <xsl:call-template name="meta">
                    <xsl:with-param name="names" select="'DC.Creator.PersonalName'"/>
                    <xsl:with-param name="content">
                        <xsl:apply-templates select="(name | string-name | collab)[1]" mode="name"/>
                    </xsl:with-param>
                </xsl:call-template>
            </xsl:for-each>

            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_language DC.Language'"/>
                <xsl:with-param name="content" select="$language"/>
            </xsl:call-template>

            <xsl:variable name="pubDate" select="($meta/pub-date[@pub-type='epub' or @publication-format='electronic' or @date-type='pub'] | $meta/pub-date)[year][1]"/>
            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_date DC.Date.issued'"/>
                <xsl:with-param name="content">
                    <xsl:value-of select="$pubDate/year"/>
                    <xsl:if test="$pubDate/month">
                        <xsl:value-of select="concat('/', format-number($pubDate/month, '00'))"/>
                        <xsl:if test="$pubDate/day">
                            <xsl:value-of select="concat('/', format-number($pubDate/day, '00'))"/>
                        </xsl:if>
                    </xsl:if>
                </xsl:with-param>
            </xsl:call-template>

            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_volume DC.Source.Volume'"/>
                <xsl:with-param name="content" select="$meta/volume[1]"/>
            </xsl:call-template>
            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_issue DC.Source.Issue'"/>
                <xsl:with-param name="content" select="$meta/issue[1]"/>
            </xsl:call-template>
            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_firstpage'"/>
                <xsl:with-param name="content" select="$meta/fpage"/>
            </xsl:call-template>
            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_lastpage'"/>
                <xsl:with-param name="content" select="$meta/lpage"/>
            </xsl:call-template>

            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'citation_doi DC.Identifier.DOI'"/>
                <xsl:with-param name="content" select="$meta/article-id[@pub-id-type='doi'][1]"/>
            </xsl:call-template>

            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'DC.Rights'"/>
                <xsl:with-param name="content" select="$meta/permissions/copyright-statement"/>
            </xsl:call-template>
            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="'DC.Rights'"/>
                <xsl:with-param name="content" select="($meta/permissions/license/@xlink:href | $meta/permissions/license/license-p)[1]"/>
            </xsl:call-template>

            <xsl:for-each select="$meta/abstract[not(@abstract-type)] | $meta/trans-abstract">
                <xsl:call-template name="meta">
                    <xsl:with-param name="names">
                        <xsl:if test="self::abstract">citation_abstract </xsl:if>
                        <xsl:text>DC.Description</xsl:text>
                    </xsl:with-param>
                    <xsl:with-param name="content">
                        <xsl:for-each select="*[not(self::title)] | text()">
                            <xsl:value-of select="concat(., ' ')"/>
                        </xsl:for-each>
                    </xsl:with-param>
                    <xsl:with-param name="lang" select="(@xml:lang | /article/@xml:lang)[last()]"/>
                </xsl:call-template>
            </xsl:for-each>

            <xsl:for-each select="$meta/kwd-group/kwd">
                <xsl:call-template name="meta">
                    <xsl:with-param name="names" select="'citation_keywords DC.Subject'"/>
                    <xsl:with-param name="content" select="."/>
                    <xsl:with-param name="lang" select="(/article/@xml:lang | ../@xml:lang)[last()]"/>
                </xsl:call-template>
            </xsl:for-each>
        </metas>
    </xsl:template>

    <xsl:template match="name" mode="name">
        <xsl:value-of select="normalize-space(concat(given-names, ' ', surname))"/>
    </xsl:template>

    <xsl:template match="string-name | collab" mode="name">
        <xsl:value-of select="normalize-space(.)"/>
    </xsl:template>

    <!-- une balise <meta> par nom de la liste $names (séparés par des espaces), rien si le contenu est vide -->
    <xsl:template name="meta">
        <xsl:param name="names"/>
        <xsl:param name="content"/>
        <xsl:param name="lang"/>
        <xsl:variable name="value" select="normalize-space($content)"/>
        <xsl:variable name="list" select="normalize-space($names)"/>
        <xsl:if test="$value != '' and $list != ''">
            <xsl:variable name="name">
                <xsl:choose>
                    <xsl:when test="contains($list, ' ')"><xsl:value-of select="substring-before($list, ' ')"/></xsl:when>
                    <xsl:otherwise><xsl:value-of select="$list"/></xsl:otherwise>
                </xsl:choose>
            </xsl:variable>
            <meta name="{$name}" content="{$value}">
                <xsl:if test="$lang">
                    <xsl:attribute name="xml:lang">
                        <xsl:call-template name="lang">
                            <xsl:with-param name="ident" select="$lang"/>
                        </xsl:call-template>
                    </xsl:attribute>
                </xsl:if>
            </meta>
            <xsl:call-template name="meta">
                <xsl:with-param name="names" select="substring-after($list, ' ')"/>
                <xsl:with-param name="content" select="$value"/>
                <xsl:with-param name="lang" select="$lang"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>

    <!-- fr-FR → fr -->
    <xsl:template name="lang">
        <xsl:param name="ident"/>
        <xsl:choose>
            <xsl:when test="contains($ident, '-')"><xsl:value-of select="substring-before($ident, '-')"/></xsl:when>
            <xsl:otherwise><xsl:value-of select="$ident"/></xsl:otherwise>
        </xsl:choose>
    </xsl:template>

</xsl:stylesheet>
+171 −14

File changed.

Preview size limit exceeded, changes collapsed.