xref: /plugin/diagrams/helper.php (revision bead152e993f412918e5df8ca11b1aac1b8d1f5b)
195ed8ca0SAndreas Gohr<?php
298c89536SAndreas Gohr
395ed8ca0SAndreas Gohr/**
495ed8ca0SAndreas Gohr * DokuWiki Plugin diagrams (Helper Component)
595ed8ca0SAndreas Gohr *
695ed8ca0SAndreas Gohr * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
795ed8ca0SAndreas Gohr * @author  Innovakom + CosmoCode <dokuwiki@cosmocode.de>
895ed8ca0SAndreas Gohr */
995ed8ca0SAndreas Gohrclass helper_plugin_diagrams extends \dokuwiki\Extension\Plugin
1095ed8ca0SAndreas Gohr{
1195ed8ca0SAndreas Gohr    /**
125f757686SAndreas Gohr     * Check if the given file is a diagrams.net diagram
135f757686SAndreas Gohr     *
145f757686SAndreas Gohr     * @param string $file
155f757686SAndreas Gohr     * @return bool
165f757686SAndreas Gohr     */
1798c89536SAndreas Gohr    public function isDiagramFile($file)
1898c89536SAndreas Gohr    {
195f757686SAndreas Gohr        $svg = file_get_contents($file, false, null, 0, 500);
205f757686SAndreas Gohr        return $this->isDiagram($svg);
215f757686SAndreas Gohr    }
225f757686SAndreas Gohr
235f757686SAndreas Gohr    /**
2495ed8ca0SAndreas Gohr     * Check if the given SVG is a diagrams.net diagram
2595ed8ca0SAndreas Gohr     *
2695ed8ca0SAndreas Gohr     * This is done by ensuring that the service host is part of the SVG header
2795ed8ca0SAndreas Gohr     *
2895ed8ca0SAndreas Gohr     * @param string $svg The raw SVG data (first 500 bytes are enough)
2995ed8ca0SAndreas Gohr     * @return bool
3095ed8ca0SAndreas Gohr     */
3198c89536SAndreas Gohr    public function isDiagram($svg)
3298c89536SAndreas Gohr    {
3395ed8ca0SAndreas Gohr        $svg = substr($svg, 0, 500); // makes checking a tiny bit faster
34*bead152eSAnna Dabrowska        $svg = preg_replace('/<\?xml.*?>/', '', $svg);
35*bead152eSAnna Dabrowska        $svg = preg_replace('/<!--.*?-->/', '', $svg);
36*bead152eSAnna Dabrowska        $svg = preg_replace('/<!DOCTYPE.*?>/', '', $svg);
3754b7a78aSAndreas Gohr        $svg = ltrim($svg);
3860cf7427SAnna Dabrowska
3954b7a78aSAndreas Gohr        if (empty($svg) || substr($svg, 0, 4) !== '<svg') return false;
4095ed8ca0SAndreas Gohr        $confServiceUrl = $this->getConf('service_url'); // like "https://diagrams.xyz.org/?embed=1&..."
4195ed8ca0SAndreas Gohr        $serviceHost = parse_url($confServiceUrl, PHP_URL_HOST); // Host-Portion of the Url, e.g. "diagrams.xyz.org"
4295ed8ca0SAndreas Gohr        return strpos($svg, 'embed.diagrams.net') || strpos($svg, 'draw.io') || strpos($svg, $serviceHost);
4395ed8ca0SAndreas Gohr    }
4495ed8ca0SAndreas Gohr}
45