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