xref: /plugin/struct/types/Date.php (revision 7234bfb14e712ff548d9266ef32fdcc8eaf2d04e)
1<?php
2
3namespace dokuwiki\plugin\struct\types;
4
5use dokuwiki\plugin\struct\meta\ValidationException;
6
7class Date extends AbstractBaseType
8{
9    protected $config = ['format' => 'Y/m/d', 'prefilltoday' => false, 'pastonly' => false, 'futureonly' => false];
10
11    /**
12     * Output the stored data
13     *
14     * @param string|int $value the value stored in the database
15     * @param \Doku_Renderer $R the renderer currently used to render the data
16     * @param string $mode The mode the output is rendered in (eg. XHTML)
17     * @return bool true if $mode could be satisfied
18     */
19    public function renderValue($value, \Doku_Renderer $R, $mode)
20    {
21        $date = date_create($value);
22        if ($date !== false) {
23            $out = date_format($date, $this->config['format']);
24        } else {
25            $out = '';
26        }
27
28        $R->cdata($out);
29        return true;
30    }
31
32    /**
33     * Return the editor to edit a single value
34     *
35     * @param string $name the form name where this has to be stored
36     * @param string $rawvalue the current value
37     * @param string $htmlID
38     *
39     * @return string html
40     */
41    public function valueEditor($name, $rawvalue, $htmlID)
42    {
43        if ($this->config['prefilltoday'] && !$rawvalue) {
44            $rawvalue = date('Y-m-d');
45        }
46
47        $params = [
48            'name' => $name,
49            'value' => $rawvalue,
50            'class' => 'struct_date',
51            'type' => 'date',
52            // HTML5 date picker
53            'id' => $htmlID,
54        ];
55        $attributes = buildAttributes($params, true);
56        return "<input $attributes />";
57    }
58
59    /**
60     * Validate a single value
61     *
62     * This function needs to throw a validation exception when validation fails.
63     * The exception message will be prefixed by the appropriate field on output
64     *
65     * @param string|int $rawvalue
66     * @return int|string
67     * @throws ValidationException
68     */
69    public function validate($rawvalue)
70    {
71        $rawvalue = parent::validate($rawvalue);
72        [$rawvalue] = explode(' ', $rawvalue, 2); // strip off time if there is any
73
74        [$year, $month, $day] = explode('-', $rawvalue, 3);
75        if (!checkdate((int)$month, (int)$day, (int)$year)) {
76            throw new ValidationException('invalid date format');
77        }
78        if ($this->config['pastonly'] && strtotime($rawvalue) > time()) {
79            throw new ValidationException('pastonly');
80        }
81        if ($this->config['futureonly'] && strtotime($rawvalue) < time()) {
82            throw new ValidationException('futureonly');
83        }
84        return sprintf('%d-%02d-%02d', $year, $month, $day);
85    }
86}
87