xref: /template/sprintdoc/svg.php (revision c24a2e1e525f015b644fce07c8c5eba21a6c1621)
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
93    /**
94     * SVG constructor
95     */
96    public function __construct() {
97        global $INPUT;
98
99        $svg = cleanID($INPUT->str('svg'));
100        if(blank($svg)) $this->abort(404);
101
102        // try local file first
103        $file = self::IMGDIR . $svg;
104        if(!file_exists($file)) {
105            // try media file
106            $file = mediaFN($svg);
107            if(file_exists($file)) {
108                // media files are ACL protected
109                if(auth_quickaclcheck($svg) < AUTH_READ) $this->abort(403);
110            } else {
111                // get it from material design icons
112                $file = getCacheName($svg, '.svg');
113                io_download(self::CDNBASE . $svg, $file);
114            }
115
116        }
117        // check if media exists
118        if(!file_exists($file)) $this->abort(404);
119
120        $this->file = $file;
121    }
122
123    /**
124     * Generate and output
125     */
126    public function out() {
127        $file = $this->file;
128        $params = $this->getParameters();
129
130        header('Content-Type: image/svg+xml');
131        $cachekey = md5($file . serialize($params));
132        $cache = new \cache($cachekey, '.svg');
133        $cache->_event = 'SVG_CACHE';
134
135        http_cached($cache->cache, $cache->useCache(array('files' => array($file, __FILE__))));
136        http_cached_finish($cache->cache, $this->generateSVG($file, $params));
137    }
138
139    /**
140     * Generate a new SVG based on the input file and the parameters
141     *
142     * @param string $file the SVG file to load
143     * @param array $params the parameters as returned by getParameters()
144     * @return string the new XML contents
145     */
146    protected function generateSVG($file, $params) {
147        /** @var SvgNode $xml */
148        $xml = simplexml_load_file($file, SvgNode::class);
149        $xml->addStyle($this->makeStyle($params));
150        $this->createBackground($xml);
151        $xml->groupChildren();
152
153        return $xml->asXML();
154    }
155
156    /**
157     * Get the supported parameters from request
158     *
159     * @return array
160     */
161    protected function getParameters() {
162        global $INPUT;
163
164        $params = array(
165            's' => $this->fixColor($INPUT->str('s')),
166            'f' => $this->fixColor($INPUT->str('f')),
167            'b' => $this->fixColor($INPUT->str('b')),
168            'sh' => $this->fixColor($INPUT->str('sh')),
169            'fh' => $this->fixColor($INPUT->str('fh')),
170            'bh' => $this->fixColor($INPUT->str('bh')),
171        );
172
173        return $params;
174    }
175
176    /**
177     * Generate a style setting from the input variables
178     *
179     * @param array $params associative array with the given parameters
180     * @return string
181     */
182    protected function makeStyle($params) {
183        $element = 'path'; // FIXME configurable?
184
185        if(empty($params['b'])) {
186            $params['b'] = $this->fixColor('00000000');
187        }
188
189        $style = 'g rect.' . self::BACKGROUNDCLASS . '{fill:' . $params['b'] . ';}';
190
191        if($params['bh']) {
192            $style .= 'g:hover rect.' . self::BACKGROUNDCLASS . '{fill:' . $params['bh'] . ';}';
193        }
194
195        if($params['s'] || $params['f']) {
196            $style .= 'g ' . $element . '{';
197            if($params['s']) $style .= 'stroke:' . $params['s'] . ';';
198            if($params['f']) $style .= 'fill:' . $params['f'] . ';';
199            $style .= '}';
200        }
201
202        if($params['sh'] || $params['fh']) {
203            $style .= 'g:hover ' . $element . '{';
204            if($params['sh']) $style .= 'stroke:' . $params['sh'] . ';';
205            if($params['fh']) $style .= 'fill:' . $params['fh'] . ';';
206            $style .= '}';
207        }
208
209        return $style;
210    }
211
212    /**
213     * Takes a hexadecimal color string in the following forms:
214     *
215     * RGB
216     * RRGGBB
217     * RRGGBBAA
218     *
219     * Converts it to rgba() form
220     *
221     * @param string $color
222     * @return string
223     */
224    protected function fixColor($color) {
225        if(preg_match('/^([0-9a-f])([0-9a-f])([0-9a-f])$/i', $color, $m)) {
226            $r = hexdec($m[1] . $m[1]);
227            $g = hexdec($m[2] . $m[2]);
228            $b = hexdec($m[3] . $m[3]);
229            $a = hexdec('ff');
230        } elseif(preg_match('/^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i', $color, $m)) {
231            $r = hexdec($m[1]);
232            $g = hexdec($m[2]);
233            $b = hexdec($m[3]);
234            if(isset($m[4])) {
235                $a = hexdec($m[4]);
236            } else {
237                $a = hexdec('ff');
238            }
239        } else {
240            return '';
241        }
242
243        return "rgba($r,$g,$b,$a)";
244    }
245
246    /**
247     * sets a rectangular background of the size of the svg/this itself
248     *
249     * @param SvgNode $g
250     * @return SvgNode
251     */
252    protected function createBackground(SvgNode $g) {
253        $rect = $g->prependChild('rect');
254        $rect->addAttribute('class', self::BACKGROUNDCLASS);
255
256        $rect->addAttribute('x', '0');
257        $rect->addAttribute('y', '0');
258        $rect->addAttribute('height', '100%');
259        $rect->addAttribute('width', '100%');
260        return $rect;
261    }
262
263    /**
264     * Abort processing with given status code
265     *
266     * @param int $status
267     */
268    protected function abort($status) {
269        http_status($status);
270        exit;
271    }
272
273}
274
275// main
276$svg = new SVG();
277$svg->out();
278
279