xref: /plugin/struct/types/DateTime.php (revision 4a2883e0eebc2f861000d0f0f5ebd1b16e25a258)
1<?php
2namespace dokuwiki\plugin\struct\types;
3
4use dokuwiki\plugin\struct\meta\ValidationException;
5
6class DateTime extends Date {
7
8    protected $config = array(
9        'format' => 'Y/m/d H:i:s',
10        'prefilltoday' => false
11    );
12
13    /**
14     * Return the editor to edit a single value
15     *
16     * @param string $name the form name where this has to be stored
17     * @param string $value the current value
18     * @return string html
19     */
20    public function valueEditor($name, $value) {
21        if($this->config['prefilltoday'] && !$value) {
22            $value = date('Y-m-d H:i:s');
23        }
24        return parent::valueEditor($name, $value);
25    }
26
27    /**
28     * Validate a single value
29     *
30     * This function needs to throw a validation exception when validation fails.
31     * The exception message will be prefixed by the appropriate field on output
32     *
33     * @param string|array $value
34     * @return string
35     * @throws ValidationException
36     */
37    public function validate($value) {
38        list($date, $time) = explode(' ', $value, 2);
39        $date = trim($date);
40        $time = trim($time);
41
42        list($year, $month, $day) = explode('-', $date, 3);
43        if(!checkdate($month, $day, $year)) {
44            throw new ValidationException('invalid datetime format' . "$year, $month, $day");
45        }
46
47        list($h, $m, $s) = explode(':', $time, 3);
48        $h = (int) $h;
49        $m = (int) $m;
50        $s = (int) $s;
51        if($h < 0 || $h > 23 || $m < 0 || $m > 59 || $s < 0 || $s > 59) {
52            throw new ValidationException('invalid datetime format');
53        }
54
55        return sprintf("%d-%02d-%02d %02d:%02d:%02d", $year, $month, $day, $h, $m, $s);
56    }
57
58}
59