xref: /template/sprintdoc/svg.php (revision 6c61749bf2a1268695f9fe689d24c6c675880110)
1<?php
2
3namespace dokuwiki\template\sprintdoc;
4
5if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__) . '/../../../');
6require_once(DOKU_INC . 'inc/init.php');
7
8/**
9 * Custom XML node that allows prepending
10 */
11class SvgNode extends \SimpleXMLElement {
12    /**
13     * @param string $name Name of the new node
14     * @param null|string $value
15     * @return SvgNode
16     */
17    public function prependChild($name, $value = null) {
18        $dom = dom_import_simplexml($this);
19
20        $new = $dom->insertBefore(
21            $dom->ownerDocument->createElement($name, $value),
22            $dom->firstChild
23        );
24
25        return simplexml_import_dom($new, get_class($this));
26    }
27
28    /**
29     * @param \SimpleXMLElement $node the node to be added
30     * @return \SimpleXMLElement
31     */
32    public function appendNode(\SimpleXMLElement $node) {
33        $dom = dom_import_simplexml($this);
34        $domNode = dom_import_simplexml($node);
35
36        $newNode = $dom->appendChild($domNode);
37        return simplexml_import_dom($newNode, get_class($this));
38    }
39
40    /**
41     * @param \SimpleXMLElement $node the child to remove
42     * @return \SimpleXMLElement
43     */
44    public function removeChild(\SimpleXMLElement $node) {
45        $dom = dom_import_simplexml($node);
46        $dom->parentNode->removeChild($dom);
47        return $node;
48    }
49
50    /**
51     * Wraps all elements of $this in a `<g>` tag
52     *
53     * @return SvgNode
54     */
55    public function groupChildren() {
56        $dom = dom_import_simplexml($this);
57
58        $g = $dom->ownerDocument->createElement('g');
59        while($dom->childNodes->length > 0) {
60            $child = $dom->childNodes->item(0);
61            $dom->removeChild($child);
62            $g->appendChild($child);
63        }
64        $g = $dom->appendChild($g);
65
66        return simplexml_import_dom($g, get_class($this));
67    }
68
69    /**
70     * Add new style definitions to this element
71     * @param string $style
72     */
73    public function addStyle($style) {
74        $defs = $this->defs;
75        if(!$defs) {
76            $defs = $this->prependChild('defs');
77        }
78        $defs->addChild('style', $style);
79    }
80}
81
82/**
83 * Manage SVG recoloring
84 */
85class SVG {
86
87    const IMGDIR = __DIR__ . '/img/';
88    const BACKGROUNDCLASS = 'sprintdoc-background';
89    const CDNBASE = 'https://cdn.rawgit.com/Templarian/MaterialDesign/master/icons/svg/';
90
91    protected $file;
92    protected $replacements;
93
94    /**
95     * SVG constructor
96     */
97    public function __construct() {
98        global $INPUT;
99
100        $svg = cleanID($INPUT->str('svg'));
101        if(blank($svg)) $this->abort(404);
102
103        // try local file first
104        $file = self::IMGDIR . $svg;
105        if(!file_exists($file)) {
106            // try media file
107            $file = mediaFN($svg);
108            if(file_exists($file)) {
109                // media files are ACL protected
110                if(auth_quickaclcheck($svg) < AUTH_READ) $this->abort(403);
111            } else {
112                // get it from material design icons
113                $file = getCacheName($svg, '.svg');
114                io_download(self::CDNBASE . $svg, $file);
115            }
116
117        }
118        // check if media exists
119        if(!file_exists($file)) $this->abort(404);
120
121        $this->file = $file;
122    }
123
124    /**
125     * Generate and output
126     */
127    public function out() {
128        $file = $this->file;
129        $params = $this->getParameters();
130
131        header('Content-Type: image/svg+xml');
132        $cachekey = md5($file . serialize($params) . filemtime(__FILE__));
133        $cache = new \cache($cachekey, '.svg');
134        $cache->_event = 'SVG_CACHE';
135
136        http_cached($cache->cache, $cache->useCache(array('files' => array($file, __FILE__))));
137        if($params['e']) {
138            $content = $this->embedSVG($file);
139        } else {
140            $content = $this->generateSVG($file, $params);
141        }
142        http_cached_finish($cache->cache, $content);
143    }
144
145    /**
146     * Generate a new SVG based on the input file and the parameters
147     *
148     * @param string $file the SVG file to load
149     * @param array $params the parameters as returned by getParameters()
150     * @return string the new XML contents
151     */
152    protected function generateSVG($file, $params) {
153        /** @var SvgNode $xml */
154        $xml = simplexml_load_file($file, SvgNode::class);
155        $xml->addStyle($this->makeStyle($params));
156        $this->createBackground($xml);
157        $xml->groupChildren();
158
159        return $xml->asXML();
160    }
161
162    /**
163     * Return the absolute minimum path definition for direct embedding
164     *
165     * No styles will be applied. They have to be done in CSS
166     *
167     * @param string $file the SVG file to load
168     * @return string the new XML contents
169     */
170    protected function embedSVG($file) {
171        /** @var SvgNode $xml */
172        $xml = simplexml_load_file($file, SvgNode::class);
173
174        $def = hsc((string) $xml->path['d']);
175        $w = hsc($xml['width']);
176        $h = hsc($xml['height']);
177        $v = hsc($xml['viewBox']);
178
179        return "<svg width=\"$w\" height=\"$h\" viewBox=\"$v\"><path d=\"$def\" /></svg>";
180    }
181
182    /**
183     * Get the supported parameters from request
184     *
185     * @return array
186     */
187    protected function getParameters() {
188        global $INPUT;
189
190        $params = array(
191            'e' => $INPUT->bool('e', false),
192            's' => $this->fixColor($INPUT->str('s')),
193            'f' => $this->fixColor($INPUT->str('f')),
194            'b' => $this->fixColor($INPUT->str('b')),
195            'sh' => $this->fixColor($INPUT->str('sh')),
196            'fh' => $this->fixColor($INPUT->str('fh')),
197            'bh' => $this->fixColor($INPUT->str('bh')),
198        );
199
200        return $params;
201    }
202
203    /**
204     * Generate a style setting from the input variables
205     *
206     * @param array $params associative array with the given parameters
207     * @return string
208     */
209    protected function makeStyle($params) {
210        $element = 'path'; // FIXME configurable?
211
212        if(empty($params['b'])) {
213            $params['b'] = $this->fixColor('00000000');
214        }
215
216        $style = 'g rect.' . self::BACKGROUNDCLASS . '{fill:' . $params['b'] . ';}';
217
218        if($params['bh']) {
219            $style .= 'g:hover rect.' . self::BACKGROUNDCLASS . '{fill:' . $params['bh'] . ';}';
220        }
221
222        if($params['s'] || $params['f']) {
223            $style .= 'g ' . $element . '{';
224            if($params['s']) $style .= 'stroke:' . $params['s'] . ';';
225            if($params['f']) $style .= 'fill:' . $params['f'] . ';';
226            $style .= '}';
227        }
228
229        if($params['sh'] || $params['fh']) {
230            $style .= 'g:hover ' . $element . '{';
231            if($params['sh']) $style .= 'stroke:' . $params['sh'] . ';';
232            if($params['fh']) $style .= 'fill:' . $params['fh'] . ';';
233            $style .= '}';
234        }
235
236        return $style;
237    }
238
239    /**
240     * Takes a hexadecimal color string in the following forms:
241     *
242     * RGB
243     * RRGGBB
244     * RRGGBBAA
245     *
246     * Converts it to rgba() form.
247     *
248     * Alternatively takes a replacement name from the current template's style.ini
249     *
250     * @param string $color
251     * @return string
252     */
253    protected function fixColor($color, $ini = true) {
254
255        if(preg_match('/^([0-9a-f])([0-9a-f])([0-9a-f])$/i', $color, $m)) {
256            $r = hexdec($m[1] . $m[1]);
257            $g = hexdec($m[2] . $m[2]);
258            $b = hexdec($m[3] . $m[3]);
259            $a = hexdec('ff');
260        } elseif(preg_match('/^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i', $color, $m)) {
261            $r = hexdec($m[1]);
262            $g = hexdec($m[2]);
263            $b = hexdec($m[3]);
264            if(isset($m[4])) {
265                $a = hexdec($m[4]);
266            } else {
267                $a = hexdec('ff');
268            }
269        } else {
270            if($ini) {
271                if(!$this->replacements) $this->initReplacements();
272                if(isset($this->replacements[$color])) {
273                    return $this->replacements[$color];
274                }
275            }
276            return '';
277        }
278
279        return "rgba($r,$g,$b,$a)";
280    }
281
282    /**
283     * sets a rectangular background of the size of the svg/this itself
284     *
285     * @param SvgNode $g
286     * @return SvgNode
287     */
288    protected function createBackground(SvgNode $g) {
289        $rect = $g->prependChild('rect');
290        $rect->addAttribute('class', self::BACKGROUNDCLASS);
291
292        $rect->addAttribute('x', '0');
293        $rect->addAttribute('y', '0');
294        $rect->addAttribute('height', '100%');
295        $rect->addAttribute('width', '100%');
296        return $rect;
297    }
298
299    /**
300     * Abort processing with given status code
301     *
302     * @param int $status
303     */
304    protected function abort($status) {
305        http_status($status);
306        exit;
307    }
308
309    /**
310     * Initialize the available replacement patterns
311     *
312     * Loads the style.ini from the template (and various local locations)
313     * via a core function only available through some hack.
314     */
315    protected function initReplacements() {
316        global $conf;
317        define('SIMPLE_TEST', 1); // hacky shit
318        include DOKU_INC . 'lib/exe/css.php';
319        $ini = css_styleini($conf['tpl']);
320        $this->replacements = $ini['replacements'];
321    }
322}
323
324// main
325$svg = new SVG();
326$svg->out();
327
328
329