1<?php
2
3use dokuwiki\Extension\SyntaxPlugin;
4use dokuwiki\Parsing\Handler;
5use dokuwiki\plugin\xref\Grok;
6
7/**
8 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author     Andreas Gohr <andi@splitbrain.org>
10 */
11class syntax_plugin_xref extends SyntaxPlugin
12{
13    /** @inheritdoc */
14    public function getType()
15    {
16        return 'substition';
17    }
18
19    /** @inheritdoc */
20    public function getPType()
21    {
22        return 'normal';
23    }
24
25    /** @inheritdoc */
26    public function getSort()
27    {
28        return 150;
29    }
30
31    /** @inheritdoc */
32    public function connectTo($mode)
33    {
34        $this->Lexer->addSpecialPattern('\[\[xref>.+?\]\]', $mode, 'plugin_xref');
35    }
36
37    /** @inheritdoc */
38    public function handle($match, $state, $pos, Handler $handler)
39    {
40        $match = trim(substr($match, 7, -2));
41
42        // the optional anchor (reference#symbol) is handled by the Heuristics class
43        [$reference, $name] = sexplode('|', $match, 2, '');
44        if (!$name) $name = $reference;
45
46        return [$reference, $name];
47    }
48
49    /** @inheritdoc */
50    public function render($format, Doku_Renderer $R, $data)
51    {
52        global $conf;
53        if ($format != 'xhtml') return false;
54
55        [$reference, $name] = $data;
56        $grok = new Grok($reference, $this->getConf('grokbaseurl'));
57        $count = $grok->getResultCount();
58
59        $link = [
60            'target' => $conf['target']['extern'],
61            'style' => '',
62            'pre' => '',
63            'suf' => '',
64            'more' => '',
65            'class' => 'interwiki plugin_xref',
66            'name' => hsc($name),
67            'url' => $grok->getSearchUrl(),
68            'title' => sprintf($this->getLang('view'), hsc($reference)),
69        ];
70
71        if ($count === false || $count === 0) {
72            $link['title'] = $this->getLang('unknown');
73            $link['class'] .= ' plugin_xref_err';
74        }
75
76        if ($count > 1) {
77            $link['title'] = sprintf($this->getLang('search'), hsc($reference));
78        }
79
80        $R->doc .= $R->_formatLink($link);
81        return true;
82    }
83}
84