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