xref: /plugin/struct/types/Url.php (revision 93ca6f4f4326051070b84b0a5019072b884cd2c5)
1<?php
2
3namespace dokuwiki\plugin\struct\types;
4
5use dokuwiki\plugin\struct\meta\ValidationException;
6
7class Url extends Text {
8
9    protected $config = array(
10        'autoscheme' => 'https',
11        'prefix' => '',
12        'postfix' => '',
13    );
14
15    /**
16     * The final string should be an URL
17     *
18     * @param string $rawvalue
19     * @return int|string|void
20     */
21    public function validate($rawvalue) {
22        $rawvalue = parent::validate($rawvalue);
23
24        $url = $this->buildURL($rawvalue);
25
26        $schemes = getSchemes();
27        $regex = '^(' . join('|', $schemes) . '):\/\/.+';
28        if(!preg_match("/$regex/i", $url)) {
29            throw new ValidationException('Url invalid', $url);
30        }
31
32        return $rawvalue;
33    }
34
35    /**
36     * @param string $value
37     * @param \Doku_Renderer $R
38     * @param string $mode
39     * @return bool
40     */
41    public function renderValue($value, \Doku_Renderer $R, $mode) {
42        $url = $this->buildURL($value);
43        $R->externallink($url);
44        return true;
45    }
46
47    /**
48     * Creates the full URL and applies the autoscheme if needed
49     *
50     * @param string $value
51     * @return string
52     */
53    protected function buildURL($value) {
54        $url = $this->config['prefix'] . trim($value) . $this->config['postfix'];
55
56        if(!preg_match('/\w+:\/\//', $url)) {
57            $url = $this->config['autoscheme'] . '://' . $url;
58        }
59
60        return $url;
61    }
62
63}
64