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