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