1<?php
2
3use dokuwiki\plugin\xref\Grok;
4
5/**
6 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author     Andreas Gohr <andi@splitbrain.org>
8 */
9class syntax_plugin_xref extends DokuWiki_Syntax_Plugin
10{
11
12    /** @inheritdoc */
13    public function getType()
14    {
15        return 'substition';
16    }
17
18    /** @inheritdoc */
19    public function getPType()
20    {
21        return 'normal';
22    }
23
24    /** @inheritdoc */
25    public function getSort()
26    {
27        return 150;
28    }
29
30    /** @inheritdoc */
31    public function connectTo($mode)
32    {
33        $this->Lexer->addSpecialPattern('\[\[xref>.+?\]\]', $mode, 'plugin_xref');
34    }
35
36    /** @inheritdoc */
37    public function handle($match, $state, $pos, Doku_Handler $handler)
38    {
39        $match = trim(substr($match, 7, -2));
40
41        list($reference, $name) = explode('|', $match, 2);
42        list($reference, $anchor) = explode('#', $reference, 2);
43        if (!$name) $name = $reference;
44        if ($anchor) $reference = "#" . $anchor;
45
46        return array($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        list($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}
85