xref: /template/sprintdoc/svg.php (revision e988c1764f4920566863c1a4f3a4e50ab39cfe63)
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        global $conf;
129        $file = $this->file;
130        $params = $this->getParameters();
131
132        header('Content-Type: image/svg+xml');
133        $cachekey = md5($file . serialize($params) . $conf['template'] . filemtime(__FILE__));
134        $cache = new \cache($cachekey, '.svg');
135        $cache->_event = 'SVG_CACHE';
136
137        http_cached($cache->cache, $cache->useCache(array('files' => array($file, __FILE__))));
138        if($params['e']) {
139            $content = $this->embedSVG($file);
140        } else {
141            $content = $this->generateSVG($file, $params);
142        }
143        http_cached_finish($cache->cache, $content);
144    }
145
146    /**
147     * Generate a new SVG based on the input file and the parameters
148     *
149     * @param string $file the SVG file to load
150     * @param array $params the parameters as returned by getParameters()
151     * @return string the new XML contents
152     */
153    protected function generateSVG($file, $params) {
154        /** @var SvgNode $xml */
155        $xml = simplexml_load_file($file, SvgNode::class);
156        $xml->addStyle($this->makeStyle($params));
157        $this->createBackground($xml);
158        $xml->groupChildren();
159
160        return $xml->asXML();
161    }
162
163    /**
164     * Return the absolute minimum path definition for direct embedding
165     *
166     * No styles will be applied. They have to be done in CSS
167     *
168     * @param string $file the SVG file to load
169     * @return string the new XML contents
170     */
171    protected function embedSVG($file) {
172        /** @var SvgNode $xml */
173        $xml = simplexml_load_file($file, SvgNode::class);
174
175        $def = hsc((string) $xml->path['d']);
176        $w = hsc($xml['width']);
177        $h = hsc($xml['height']);
178        $v = hsc($xml['viewBox']);
179
180        return "<svg width=\"$w\" height=\"$h\" viewBox=\"$v\"><path d=\"$def\" /></svg>";
181    }
182
183    /**
184     * Get the supported parameters from request
185     *
186     * @return array
187     */
188    protected function getParameters() {
189        global $INPUT;
190
191        $params = array(
192            'e' => $INPUT->bool('e', false),
193            's' => $this->fixColor($INPUT->str('s')),
194            'f' => $this->fixColor($INPUT->str('f')),
195            'b' => $this->fixColor($INPUT->str('b')),
196            'sh' => $this->fixColor($INPUT->str('sh')),
197            'fh' => $this->fixColor($INPUT->str('fh')),
198            'bh' => $this->fixColor($INPUT->str('bh')),
199        );
200
201        return $params;
202    }
203
204    /**
205     * Generate a style setting from the input variables
206     *
207     * @param array $params associative array with the given parameters
208     * @return string
209     */
210    protected function makeStyle($params) {
211        $element = 'path'; // FIXME configurable?
212
213        if(empty($params['b'])) {
214            $params['b'] = $this->fixColor('00000000');
215        }
216
217        $style = 'g rect.' . self::BACKGROUNDCLASS . '{fill:' . $params['b'] . ';}';
218
219        if($params['bh']) {
220            $style .= 'g:hover rect.' . self::BACKGROUNDCLASS . '{fill:' . $params['bh'] . ';}';
221        }
222
223        if($params['s'] || $params['f']) {
224            $style .= 'g ' . $element . '{';
225            if($params['s']) $style .= 'stroke:' . $params['s'] . ';';
226            if($params['f']) $style .= 'fill:' . $params['f'] . ';';
227            $style .= '}';
228        }
229
230        if($params['sh'] || $params['fh']) {
231            $style .= 'g:hover ' . $element . '{';
232            if($params['sh']) $style .= 'stroke:' . $params['sh'] . ';';
233            if($params['fh']) $style .= 'fill:' . $params['fh'] . ';';
234            $style .= '}';
235        }
236
237        return $style;
238    }
239
240    /**
241     * Takes a hexadecimal color string in the following forms:
242     *
243     * RGB
244     * RRGGBB
245     * RRGGBBAA
246     *
247     * Converts it to rgba() form.
248     *
249     * Alternatively takes a replacement name from the current template's style.ini
250     *
251     * @param string $color
252     * @return string
253     */
254    protected function fixColor($color) {
255        if($color === '') return '';
256        if(preg_match('/^([0-9a-f])([0-9a-f])([0-9a-f])$/i', $color, $m)) {
257            $r = hexdec($m[1] . $m[1]);
258            $g = hexdec($m[2] . $m[2]);
259            $b = hexdec($m[3] . $m[3]);
260            $a = hexdec('ff');
261        } elseif(preg_match('/^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i', $color, $m)) {
262            $r = hexdec($m[1]);
263            $g = hexdec($m[2]);
264            $b = hexdec($m[3]);
265            if(isset($m[4])) {
266                $a = hexdec($m[4]);
267            } else {
268                $a = hexdec('ff');
269            }
270        } else {
271            if(is_null($this->replacements)) $this->initReplacements();
272            if(isset($this->replacements[$color])) {
273                return $this->replacements[$color];
274            }
275            return '';
276        }
277
278        return "rgba($r,$g,$b,$a)";
279    }
280
281    /**
282     * sets a rectangular background of the size of the svg/this itself
283     *
284     * @param SvgNode $g
285     * @return SvgNode
286     */
287    protected function createBackground(SvgNode $g) {
288        $rect = $g->prependChild('rect');
289        $rect->addAttribute('class', self::BACKGROUNDCLASS);
290
291        $rect->addAttribute('x', '0');
292        $rect->addAttribute('y', '0');
293        $rect->addAttribute('height', '100%');
294        $rect->addAttribute('width', '100%');
295        return $rect;
296    }
297
298    /**
299     * Abort processing with given status code
300     *
301     * @param int $status
302     */
303    protected function abort($status) {
304        http_status($status);
305        exit;
306    }
307
308    /**
309     * Initialize the available replacement patterns
310     *
311     * Loads the style.ini from the template (and various local locations)
312     * via a core function only available through some hack.
313     */
314    protected function initReplacements() {
315        global $conf;
316        define('SIMPLE_TEST', 1); // hacky shit
317        include DOKU_INC . 'lib/exe/css.php';
318        $ini = css_styleini($conf['template']);
319        $this->replacements = $ini['replacements'];
320    }
321}
322
323// main
324$svg = new SVG();
325$svg->out();
326
327
328