1<?php 2 3use dokuwiki\plugin\icon\SVG; 4 5/** 6 * DokuWiki Plugin icon (Action Component) 7 * 8 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html 9 * @author Andreas Gohr <gohr@cosmocode.de> 10 */ 11class action_plugin_icon extends \dokuwiki\Extension\ActionPlugin 12{ 13 14 /** @inheritDoc */ 15 public function register(Doku_Event_Handler $controller) 16 { 17 $controller->register_hook('FETCH_MEDIA_STATUS', 'BEFORE', $this, 'handleMediaStatus'); 18 19 } 20 21 /** 22 * @param Doku_Event $event event object by reference 23 * @param mixed $param optional parameter passed when event was registered 24 * @return void 25 */ 26 public function handleMediaStatus(Doku_Event $event, $param) 27 { 28 $d = &$event->data; 29 if(substr($d['media'],0, 5) !== 'icon:') return; 30 31 $parts = explode(':', $d['media']); // we use pseudo namespaces for configuration 32 array_shift($parts); // remove icon prefix 33 if(!$parts) return; // no icon given - return the default 404 34 $icon = array_pop($parts); 35 $icon = basename($icon, '.svg'); 36 $conf = $this->parseConfig($parts); 37 38 try { 39 $svg = new SVG($conf['source'], $icon); 40 $svg->setColor($conf['color']); 41 $svg->setWidth($conf['width']); 42 $svg->setHeight($conf['height']); 43 } catch (\Exception $e) { 44 \dokuwiki\ErrorHandler::logException($e); 45 return; 46 } 47 48 $d['file'] = $svg->getFile(); 49 $d['status'] = 200; 50 $d['statusmessage'] = 'Ok'; 51 } 52 53 /** 54 * Try to figure out what the different pseudo namespaces represent in terms of configuration 55 * 56 * @param string[] $parts 57 * @return array 58 */ 59 protected function parseConfig($parts) { 60 // defaults 61 $conf = [ 62 'source' => 'mdi', 63 'color' => 'currentColor', 64 'width' => 'auto', 65 'height' => '1.2rem', 66 ]; 67 68 // regular expressions to use 69 $regexes = [ 70 'source' => '/^('.join('|', array_keys(SVG::SOURCES)).')$/', 71 'width' => '/^w-(.*)$/', 72 'height' => '/^h-(.*)$/', 73 ]; 74 75 // find the pieces by regex 76 $all = count($parts); 77 for($i=0; $i<$all; $i++) { 78 $part = $parts[$i]; 79 foreach ($regexes as $key => $regex) { 80 if(preg_match($regex, $part, $m)) { 81 $conf[$key] = $m[1]; 82 unset($parts[$i]); 83 continue 2; 84 } 85 } 86 } 87 88 // any remains are the color 89 if(count($parts)) { 90 $conf['color'] = array_shift($parts); 91 } 92 93 return $conf; 94 } 95 96} 97 98