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 { 61 if ($this->config['fixedtitle']) return $this->config['fixedtitle']; 62 if (!$this->config['autoshorten']) return $url; 63 64 $parsed = parse_url($url); 65 66 $title = $parsed['host']; 67 $title = preg_replace('/^www\./i', '', $title); 68 if (isset($parsed['path']) && $parsed['path'] === '/') { 69 unset($parsed['path']); 70 } 71 if ( 72 isset($parsed['path']) || 73 isset($parsed['query']) || 74 isset($parsed['fragment']) 75 ) { 76 $title .= '/…'; 77 } 78 return $title; 79 } 80 81 /** 82 * Creates the full URL and applies the autoscheme if needed 83 * 84 * @param string $value 85 * @return string 86 */ 87 protected function buildURL($value) 88 { 89 $url = $this->config['prefix'] . trim($value) . $this->config['postfix']; 90 91 if (!preg_match('/\w+:\/\//', $url)) { 92 $url = $this->config['autoscheme'] . '://' . $url; 93 } 94 95 return $url; 96 } 97} 98