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