xref: /plugin/diagrams/syntax/embed.php (revision 8c8c70074e1156a58dbfd89fe9e41e3dd346fb54)
1<?php
2
3/**
4 * DokuWiki Plugin diagrams (Syntax Component)
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author  Innovakom + CosmoCode <dokuwiki@cosmocode.de>
8 */
9class syntax_plugin_diagrams_embed extends \dokuwiki\Extension\SyntaxPlugin
10{
11    /** @inheritDoc */
12    public function getType()
13    {
14        return 'substition';
15    }
16
17    /** @inheritDoc */
18    public function getPType()
19    {
20        return 'block';
21    }
22
23    /** @inheritDoc */
24    public function getSort()
25    {
26        return 319;
27    }
28
29    /** @inheritDoc */
30    public function connectTo($mode)
31    {
32        // FIXME only allow this when enabled in config
33        $this->Lexer->addSpecialPattern('<diagram(?: .*)?>.*?(?:</diagram>)', $mode, 'plugin_diagrams_embed');
34    }
35
36    /** @inheritDoc */
37    public function handle($match, $state, $pos, Doku_Handler $handler)
38    {
39        [$open, $rest] = sexplode('>', $match, 2);
40        $params = substr($open, 9);
41        $svg = substr($rest, 0, -10);
42
43        $data = [
44            'svg' => $svg,
45            'align' => '',
46            'width' => '',
47            'height' => '',
48            'pos' => $pos,
49            'len' => strlen($match),
50        ];
51
52        if (preg_match('/\b(left|right|center)\b/', $params, $matches)) {
53            $data['align'] = $matches[1];
54        }
55        if (preg_match('/\b(\d+)x(\d+)\b/', $params, $matches)) {
56            $data['width'] = (int)$matches[1];
57            $data['height'] = (int)$matches[2];
58        }
59
60        return $data;
61    }
62
63    /** @inheritDoc */
64    public function render($format, Doku_Renderer $renderer, $data)
65    {
66        if ($format !== 'xhtml') return false;
67
68        // FIXME currently insecure!
69        // maybe use https://github.com/darylldoyle/svg-sanitizer
70
71        $style = '';
72        if ($data['width']) $style .= 'width: ' . $data['width'] . 'px; ';
73        if ($data['height']) $style .= 'height: ' . $data['height'] . 'px; ';
74
75        $tag = '<div class="plugin_diagrams_inline media%s" style="%s">%s</divobject>';
76        $renderer->doc .= sprintf($tag, $data['align'], $style, $data['svg']);
77
78        return true;
79    }
80}
81
82