1<?php 2 3use dokuwiki\Logger; 4use dokuwiki\plugin\diagrams\Diagrams; 5use enshrined\svgSanitize\Sanitizer; 6 7/** 8 * DokuWiki Plugin diagrams (Syntax Component) 9 * 10 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html 11 * @author Innovakom + CosmoCode <dokuwiki@cosmocode.de> 12 */ 13class syntax_plugin_diagrams_embed extends \dokuwiki\Extension\SyntaxPlugin 14{ 15 /** @inheritDoc */ 16 public function getType() 17 { 18 return 'substition'; 19 } 20 21 /** @inheritDoc */ 22 public function getPType() 23 { 24 return 'block'; 25 } 26 27 /** @inheritDoc */ 28 public function getSort() 29 { 30 return 319; 31 } 32 33 /** @inheritDoc */ 34 public function connectTo($mode) 35 { 36 // only register if embed mode is enabled 37 if(!$this->getConf('mode') & Diagrams::MODE_EMBED) return; 38 39 // auto load sanitizer 40 require_once __DIR__ . '/../vendor/autoload.php'; 41 $this->Lexer->addSpecialPattern('<diagram(?: .*)?>.*?(?:</diagram>)', $mode, 'plugin_diagrams_embed'); 42 } 43 44 /** @inheritDoc */ 45 public function handle($match, $state, $pos, Doku_Handler $handler) 46 { 47 [$open, $rest] = sexplode('>', $match, 2); 48 $params = substr($open, 9); 49 $svg = substr($rest, 0, -10); 50 51 /** @var helper_plugin_diagrams $helper */ 52 $helper = plugin_load('helper', 'diagrams'); 53 if(!$helper->isDiagram($svg)) return false; 54 55 // sanitize svg 56 $sanitizer = new Sanitizer(); 57 $svg = $sanitizer->sanitize($svg); 58 59 if(!$svg) { 60 global $ID; 61 Logger::debug('diagrams: invalid SVG on '.$ID, $sanitizer->getXmlIssues()); 62 return false; 63 } 64 65 $data = [ 66 'svg' => $svg, 67 'align' => '', 68 'width' => '', 69 'height' => '', 70 'pos' => $pos, 71 'len' => strlen($match), 72 ]; 73 74 if (preg_match('/\b(left|right|center)\b/', $params, $matches)) { 75 $data['align'] = $matches[1]; 76 } 77 if (preg_match('/\b(\d+)x(\d+)\b/', $params, $matches)) { 78 $data['width'] = (int)$matches[1]; 79 $data['height'] = (int)$matches[2]; 80 } 81 82 return $data; 83 } 84 85 /** @inheritDoc */ 86 public function render($format, Doku_Renderer $renderer, $data) 87 { 88 if ($format !== 'xhtml') return false; 89 if(!$data) return false; 90 91 $style = ''; 92 if($data['width'] && $data['height']) { 93 $style .= 'width: ' . $data['width'] . 'px; '; 94 $style .= 'height: ' . $data['height'] . 'px; '; 95 $class = 'fixedSize'; 96 } else { 97 $class = 'autoSize'; 98 } 99 100 $attr = [ 101 'class' => "plugin_diagrams_embed $class media" . $data['align'], 102 'style' => $style, 103 'data-pos' => $data['pos'], 104 'data-len' => $data['len'], 105 ]; 106 107 $tag = '<div %s>%s</div>'; 108 $renderer->doc .= sprintf($tag, buildAttributes($attr), $data['svg']); 109 110 return true; 111 } 112} 113 114