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        'fixedtitle' => '',
14        'autoshorten' => true,
15    );
16
17    /**
18     * The final string should be an URL
19     *
20     * @param string $rawvalue
21     * @return int|string|void
22     */
23    public function validate($rawvalue)
24    {
25        $rawvalue = parent::validate($rawvalue);
26
27        $url = $this->buildURL($rawvalue);
28
29        $schemes = getSchemes();
30        $regex = '^(' . join('|', $schemes) . '):\/\/.+';
31        if (!preg_match("/$regex/i", $url)) {
32            throw new ValidationException('Url invalid', $url);
33        }
34
35        return $rawvalue;
36    }
37
38    /**
39     * @param string $value
40     * @param \Doku_Renderer $R
41     * @param string $mode
42     * @return bool
43     */
44    public function renderValue($value, \Doku_Renderer $R, $mode)
45    {
46        $url = $this->buildURL($value);
47        $title = $this->generateTitle($url);
48        $R->externallink($url, $title);
49        return true;
50    }
51
52    /**
53     * Make a label for the link
54     *
55     * @param $url
56     * @return string
57     */
58    protected function generateTitle($url)
59    {
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