xref: /plugin/struct/types/Date.php (revision 48801f6d7d7ad3c56a635066943b271f49b9264e)
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     * @param string $htmlID
39     *
40     * @return string html
41     */
42    public function valueEditor($name, $rawvalue, $htmlID) {
43        if($this->config['prefilltoday'] && !$rawvalue) {
44            $rawvalue = date('Y-m-d');
45        }
46
47        $params = array(
48            'name' => $name,
49            'value' => $rawvalue,
50            'class' => 'struct_date',
51            'id' => $htmlID,
52        );
53        $attributes = buildAttributes($params, true);
54        return "<input $attributes />";
55    }
56
57    /**
58     * Validate a single value
59     *
60     * This function needs to throw a validation exception when validation fails.
61     * The exception message will be prefixed by the appropriate field on output
62     *
63     * @param string|int $rawvalue
64     * @return int|string
65     * @throws ValidationException
66     */
67    public function validate($rawvalue) {
68        $rawvalue = parent::validate($rawvalue);
69        list($rawvalue) = explode(' ', $rawvalue, 2); // strip off time if there is any
70
71        list($year, $month, $day) = explode('-', $rawvalue, 3);
72        if(!checkdate((int) $month, (int) $day, (int) $year)) {
73            throw new ValidationException('invalid date format');
74        }
75        return sprintf('%d-%02d-%02d', $year, $month, $day);
76    }
77
78}
79