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