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