1<?php 2 3namespace dokuwiki\plugin\struct\types; 4 5use dokuwiki\plugin\struct\meta\ValidationException; 6 7class Url extends Text 8{ 9 10 protected $config = array( 11 'autoscheme' => 'https', 12 'prefix' => '', 13 'postfix' => '', 14 'fixedtitle' => '', 15 'autoshorten' => true, 16 ); 17 18 /** 19 * The final string should be an URL 20 * 21 * @param string $rawvalue 22 * @return int|string|void 23 */ 24 public function validate($rawvalue) 25 { 26 $rawvalue = parent::validate($rawvalue); 27 28 $url = $this->buildURL($rawvalue); 29 30 $schemes = getSchemes(); 31 $regex = '^(' . join('|', $schemes) . '):\/\/.+'; 32 if (!preg_match("/$regex/i", $url)) { 33 throw new ValidationException('Url invalid', $url); 34 } 35 36 return $rawvalue; 37 } 38 39 /** 40 * @param string $value 41 * @param \Doku_Renderer $R 42 * @param string $mode 43 * @return bool 44 */ 45 public function renderValue($value, \Doku_Renderer $R, $mode) 46 { 47 $url = $this->buildURL($value); 48 $title = $this->generateTitle($url); 49 $R->externallink($url, $title); 50 return true; 51 } 52 53 /** 54 * Make a label for the link 55 * 56 * @param $url 57 * @return string 58 */ 59 protected function generateTitle($url) { 60 if($this->config['fixedtitle']) return $this->config['fixedtitle']; 61 if(!$this->config['autoshorten']) return $url; 62 63 $parsed = parse_url($url); 64 65 $title = $parsed['host']; 66 $title = preg_replace('/^www\./i', '', $title); 67 if(isset($parsed['path']) && $parsed['path'] === '/') { 68 unset($parsed['path']); 69 } 70 if( 71 isset($parsed['path']) || 72 isset($parsed['query']) || 73 isset($parsed['fragment']) 74 ) { 75 $title .= '/…'; 76 } 77 return $title; 78 } 79 80 /** 81 * Creates the full URL and applies the autoscheme if needed 82 * 83 * @param string $value 84 * @return string 85 */ 86 protected function buildURL($value) 87 { 88 $url = $this->config['prefix'] . trim($value) . $this->config['postfix']; 89 90 if (!preg_match('/\w+:\/\//', $url)) { 91 $url = $this->config['autoscheme'] . '://' . $url; 92 } 93 94 return $url; 95 } 96} 97