1<?php
2
3/**
4 * DokuWiki Plugin diagrams (Helper Component)
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author  Innovakom + CosmoCode <dokuwiki@cosmocode.de>
8 */
9class helper_plugin_diagrams extends \dokuwiki\Extension\Plugin
10{
11    /**
12     * Check if the given file is a diagrams.net diagram
13     *
14     * @param string $file
15     * @return bool
16     */
17    public function isDiagramFile($file)
18    {
19        $svg = file_get_contents($file, false, null, 0, 500);
20        return $this->isDiagram($svg);
21    }
22
23    /**
24     * Check if the given SVG is a diagrams.net diagram
25     *
26     * This is done by ensuring that the service host is part of the SVG header
27     *
28     * @param string $svg The raw SVG data (first 500 bytes are enough)
29     * @return bool
30     */
31    public function isDiagram($svg)
32    {
33        $svg = substr($svg, 0, 500); // makes checking a tiny bit faster
34        $svg = preg_replace('/<\?xml.*?>/', '', $svg);
35        $svg = preg_replace('/<!--.*?-->/', '', $svg);
36        $svg = preg_replace('/<!DOCTYPE.*?>/', '', $svg);
37        $svg = ltrim($svg);
38
39        if (empty($svg) || substr($svg, 0, 4) !== '<svg') return false;
40        $confServiceUrl = $this->getConf('service_url'); // like "https://diagrams.xyz.org/?embed=1&..."
41        $serviceHost = parse_url($confServiceUrl, PHP_URL_HOST); // Host-Portion of the Url, e.g. "diagrams.xyz.org"
42        return strpos($svg, 'embed.diagrams.net') || strpos($svg, 'draw.io') || strpos($svg, $serviceHost);
43    }
44}
45