xref: /dokuwiki/inc/Parsing/ParserMode/GfmLink.php (revision 74031e463764923581b9204cebc0fc3f34ce881f)
1e89aeebdSAndreas Gohr<?php
2e89aeebdSAndreas Gohr
3e89aeebdSAndreas Gohrnamespace dokuwiki\Parsing\ParserMode;
4e89aeebdSAndreas Gohr
5e89aeebdSAndreas Gohruse dokuwiki\Parsing\Handler;
6*74031e46SAndreas Gohruse dokuwiki\Parsing\Helpers\Escape;
71e28e406SAndreas Gohruse dokuwiki\Parsing\Helpers\Link;
81e28e406SAndreas Gohruse dokuwiki\Parsing\Helpers\Media as MediaHelper;
9e89aeebdSAndreas Gohr
10e89aeebdSAndreas Gohr/**
11e89aeebdSAndreas Gohr * GFM inline link [text](url) with optional title [text](url "title").
12e89aeebdSAndreas Gohr *
133440a8c0SAndreas Gohr * The link text may be either plain text (the common case) or an inline
143440a8c0SAndreas Gohr * image `![alt](imgUrl)` — the Markdown equivalent of DW's
153440a8c0SAndreas Gohr * `[[target|{{imgUrl}}]]`. The image-as-label form emits a single link
163440a8c0SAndreas Gohr * handler call with a media descriptor array in the label slot, reusing
173440a8c0SAndreas Gohr * the same flow that `Internallink` already drives. No new handler
183440a8c0SAndreas Gohr * instructions; renderers (xhtml, odt, metadata, …) already know how to
193440a8c0SAndreas Gohr * render a link whose label is a media descriptor.
203440a8c0SAndreas Gohr *
213440a8c0SAndreas Gohr * Mirrors DW's `Internallink` architecture: a permissive outer pattern
223440a8c0SAndreas Gohr * plus handle-time parsing, rather than encoding every GFM rule at
233440a8c0SAndreas Gohr * pattern level.
243440a8c0SAndreas Gohr *
25e89aeebdSAndreas Gohr * Deliberately not supported (see skip.php for the affected spec examples):
26e89aeebdSAndreas Gohr *
27e89aeebdSAndreas Gohr *   - Reference links [text][id] / [text][] / [foo] — the single-pass
28e89aeebdSAndreas Gohr *     lexer cannot resolve forward references to [foo]: url definitions.
293440a8c0SAndreas Gohr *   - Pointy-bracket destinations [link](<foo bar>) — the simplified
303440a8c0SAndreas Gohr *     pattern will happily match, but handle() produces an internallink
313440a8c0SAndreas Gohr *     with a broken src; spec tests for this stay in skip.php.
323440a8c0SAndreas Gohr *   - Balanced-parens inside URLs [link](foo(bar)) — matches truncate
333440a8c0SAndreas Gohr *     at first `)`, producing odd output; also in skip.php.
34e89aeebdSAndreas Gohr *   - Title HTML attribute — DokuWiki link handler instructions have no
35e89aeebdSAndreas Gohr *     title-attribute slot, and plumbing one through every renderer just
36e89aeebdSAndreas Gohr *     for this is out of scope. The title parses cleanly but is discarded.
373440a8c0SAndreas Gohr *   - Mixed text + image in the label ([prefix ![alt](img) suffix](url))
383440a8c0SAndreas Gohr *     — matches DW's policy: Internallink only converts the label to a
393440a8c0SAndreas Gohr *     media descriptor when it matches `^{{…}}$` exactly.
40e89aeebdSAndreas Gohr */
41e89aeebdSAndreas Gohrclass GfmLink extends AbstractMode
42e89aeebdSAndreas Gohr{
433440a8c0SAndreas Gohr    // Image sub-pattern reused for both the label alternative in the main
443440a8c0SAndreas Gohr    // pattern and the image-as-label detector in handle(). No capture
453440a8c0SAndreas Gohr    // groups here — the lexer wraps user patterns in a capture and
463440a8c0SAndreas Gohr    // additional captures would renumber unpredictably.
473440a8c0SAndreas Gohr    private const IMAGE_SUB = '!\[[^\[\]\n]*\]\([^)\n]+\)';
48e89aeebdSAndreas Gohr
49e89aeebdSAndreas Gohr    /** @inheritdoc */
50e89aeebdSAndreas Gohr    public function getSort()
51e89aeebdSAndreas Gohr    {
52e89aeebdSAndreas Gohr        return 300;
53e89aeebdSAndreas Gohr    }
54e89aeebdSAndreas Gohr
55e89aeebdSAndreas Gohr    /** @inheritdoc */
56e89aeebdSAndreas Gohr    public function connectTo($mode)
57e89aeebdSAndreas Gohr    {
583440a8c0SAndreas Gohr        // Outer shape: `[text-or-image](url)`. Text class forbids brackets
593440a8c0SAndreas Gohr        // and newlines; the image alternative explicitly matches one
603440a8c0SAndreas Gohr        // inline image. URL slot is permissive (`[^)\n]+`) — handle() does
613440a8c0SAndreas Gohr        // URL / title splitting post-entry, mirroring how DW Internallink
623440a8c0SAndreas Gohr        // parses inside `[[...]]`.
633440a8c0SAndreas Gohr        $pattern = '\[(?!\[)(?:[^\[\]\n]+|' . self::IMAGE_SUB . ')\]\([^)\n]+\)';
64e89aeebdSAndreas Gohr        $this->Lexer->addSpecialPattern($pattern, $mode, 'gfm_link');
65e89aeebdSAndreas Gohr    }
66e89aeebdSAndreas Gohr
67e89aeebdSAndreas Gohr    /** @inheritdoc */
68e89aeebdSAndreas Gohr    public function handle($match, $state, $pos, Handler $handler)
69e89aeebdSAndreas Gohr    {
703440a8c0SAndreas Gohr        // Detect image-as-label `[![alt](img)](target)`. Parallels
713440a8c0SAndreas Gohr        // Internallink's `^{{…}}$` check — when the label is exactly an
723440a8c0SAndreas Gohr        // inline image, parse it into a media descriptor; otherwise
733440a8c0SAndreas Gohr        // treat the label as plain text.
743440a8c0SAndreas Gohr        if (preg_match('/^\[(' . self::IMAGE_SUB . ')\]\(([^)\n]+)\)$/', $match, $m)) {
753440a8c0SAndreas Gohr            $label     = $this->parseImageDescriptor($m[1]);
763440a8c0SAndreas Gohr            $targetUrl = $this->extractUrl($m[2]);
773440a8c0SAndreas Gohr        } else {
783440a8c0SAndreas Gohr            // Plain text label can't contain `]`, so the first `](` is
793440a8c0SAndreas Gohr            // the label/target separator.
80e89aeebdSAndreas Gohr            $sep       = strpos($match, '](');
81*74031e46SAndreas Gohr            $label     = Escape::unescapeBackslashes(substr($match, 1, $sep - 1));
823440a8c0SAndreas Gohr            $targetUrl = $this->extractUrl(substr($match, $sep + 2, -1));
833440a8c0SAndreas Gohr        }
84e89aeebdSAndreas Gohr
85*74031e46SAndreas Gohr        // Classify on the raw URL so windowssharelink detection sees the
86*74031e46SAndreas Gohr        // literal `\\host\path` runs intact — GFM's `\\` → `\` collapse
87*74031e46SAndreas Gohr        // would otherwise destroy the share prefix.
881e28e406SAndreas Gohr        [$call, $args] = Link::classify($targetUrl, $label);
89*74031e46SAndreas Gohr        if ($call !== 'windowssharelink') {
90*74031e46SAndreas Gohr            $args[0] = Escape::unescapeBackslashes($args[0]);
91*74031e46SAndreas Gohr        }
923440a8c0SAndreas Gohr        $handler->addCall($call, $args, $pos);
93e89aeebdSAndreas Gohr        return true;
94e89aeebdSAndreas Gohr    }
953440a8c0SAndreas Gohr
963440a8c0SAndreas Gohr    /**
973440a8c0SAndreas Gohr     * Extract the URL from a parenthesized payload: trim surrounding
983440a8c0SAndreas Gohr     * whitespace, then take the first whitespace-delimited token. Any
993440a8c0SAndreas Gohr     * trailing title is discarded (no renderer slot for it).
1003440a8c0SAndreas Gohr     */
1013440a8c0SAndreas Gohr    private function extractUrl(string $inside): string
1023440a8c0SAndreas Gohr    {
1033440a8c0SAndreas Gohr        $inside = trim($inside);
1043440a8c0SAndreas Gohr        return substr($inside, 0, strcspn($inside, " \t\n"));
1053440a8c0SAndreas Gohr    }
1063440a8c0SAndreas Gohr
1073440a8c0SAndreas Gohr    /**
1083440a8c0SAndreas Gohr     * Parse an inline image sub-match `![alt](imgUrl)` into the media
1093440a8c0SAndreas Gohr     * descriptor shape Media::parseMedia() returns, so the link handler
1103440a8c0SAndreas Gohr     * can treat it as a media label identically to `[[page|{{img}}]]`.
1113440a8c0SAndreas Gohr     */
1123440a8c0SAndreas Gohr    private function parseImageDescriptor(string $imageMatch): array
1133440a8c0SAndreas Gohr    {
1143440a8c0SAndreas Gohr        $sep    = strpos($imageMatch, '](');
115*74031e46SAndreas Gohr        $alt    = Escape::unescapeBackslashes(substr($imageMatch, 2, $sep - 2));
116*74031e46SAndreas Gohr        $imgUrl = Escape::unescapeBackslashes($this->extractUrl(substr($imageMatch, $sep + 2, -1)));
1173440a8c0SAndreas Gohr
1181e28e406SAndreas Gohr        $p = MediaHelper::parseParameters($imgUrl);
1193440a8c0SAndreas Gohr        $type = (media_isexternal($p['src']) || link_isinterwiki($p['src']))
1203440a8c0SAndreas Gohr            ? 'externalmedia'
1213440a8c0SAndreas Gohr            : 'internalmedia';
1223440a8c0SAndreas Gohr
1233440a8c0SAndreas Gohr        return [
1243440a8c0SAndreas Gohr            'type'    => $type,
1253440a8c0SAndreas Gohr            'src'     => $p['src'],
1263440a8c0SAndreas Gohr            'title'   => $alt !== '' ? $alt : null,
1273440a8c0SAndreas Gohr            'align'   => $p['align'],
1283440a8c0SAndreas Gohr            'width'   => $p['width'],
1293440a8c0SAndreas Gohr            'height'  => $p['height'],
1303440a8c0SAndreas Gohr            'cache'   => $p['cache'],
1313440a8c0SAndreas Gohr            'linking' => $p['linking'],
1323440a8c0SAndreas Gohr        ];
1333440a8c0SAndreas Gohr    }
134e89aeebdSAndreas Gohr}
135