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 'type' => 'date', // HTML5 date picker 52 'id' => $htmlID, 53 ); 54 $attributes = buildAttributes($params, true); 55 return "<input $attributes />"; 56 } 57 58 /** 59 * Validate a single value 60 * 61 * This function needs to throw a validation exception when validation fails. 62 * The exception message will be prefixed by the appropriate field on output 63 * 64 * @param string|int $rawvalue 65 * @return int|string 66 * @throws ValidationException 67 */ 68 public function validate($rawvalue) { 69 $rawvalue = parent::validate($rawvalue); 70 list($rawvalue) = explode(' ', $rawvalue, 2); // strip off time if there is any 71 72 list($year, $month, $day) = explode('-', $rawvalue, 3); 73 if(!checkdate((int) $month, (int) $day, (int) $year)) { 74 throw new ValidationException('invalid date format'); 75 } 76 return sprintf('%d-%02d-%02d', $year, $month, $day); 77 } 78 79} 80