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