Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  
  18  /**
  19   * Group of date and time input element
  20   *
  21   * Contains class for a group of elements used to input a date and time.
  22   *
  23   * @package   core_form
  24   * @copyright 2006 Jamie Pratt <me@jamiep.org>
  25   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26   */
  27  
  28  global $CFG;
  29  require_once($CFG->libdir . '/form/group.php');
  30  require_once($CFG->libdir . '/formslib.php');
  31  
  32  /**
  33   * Element used to input a date and time.
  34   *
  35   * Class for a group of elements used to input a date and time.
  36   *
  37   * @package   core_form
  38   * @category  form
  39   * @copyright 2006 Jamie Pratt <me@jamiep.org>
  40   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  41   */
  42  class MoodleQuickForm_date_time_selector extends MoodleQuickForm_group {
  43  
  44      /**
  45       * Options for the element.
  46       *
  47       * startyear => int start of range of years that can be selected
  48       * stopyear => int last year that can be selected
  49       * defaulttime => default time value if the field is currently not set
  50       * timezone => int|float|string (optional) timezone modifier used for edge case only.
  51       *      If not specified, then date is caclulated based on current user timezone.
  52       *      Note: dst will be calculated for string timezones only
  53       *      {@link http://docs.moodle.org/dev/Time_API#Timezone}
  54       * step => step to increment minutes by
  55       * optional => if true, show a checkbox beside the date to turn it on (or off)
  56       * @var array
  57       */
  58      protected $_options = array();
  59  
  60      /**
  61       * @var array These complement separators, they are appended to the resultant HTML.
  62       */
  63      protected $_wrap = array('', '');
  64  
  65      /**
  66       * @var null|bool Keeps track of whether the date selector was initialised using createElement
  67       *                or addElement. If true, createElement was used signifying the element has been
  68       *                added to a group - see MDL-39187.
  69       */
  70      protected $_usedcreateelement = true;
  71  
  72      /**
  73       * Class constructor
  74       *
  75       * @param string $elementName Element's name
  76       * @param mixed $elementLabel Label(s) for an element
  77       * @param array $options Options to control the element's display
  78       * @param mixed $attributes Either a typical HTML attribute string or an associative array
  79       */
  80      public function __construct($elementName = null, $elementLabel = null, $options = array(), $attributes = null) {
  81          // Get the calendar type used - see MDL-18375.
  82          $calendartype = \core_calendar\type_factory::get_calendar_instance();
  83          $this->_options = array('startyear' => $calendartype->get_min_year(), 'stopyear' => $calendartype->get_max_year(),
  84              'defaulttime' => 0, 'timezone' => 99, 'step' => 1, 'optional' => false);
  85  
  86          // TODO MDL-52313 Replace with the call to parent::__construct().
  87          HTML_QuickForm_element::__construct($elementName, $elementLabel, $attributes);
  88          $this->_persistantFreeze = true;
  89          $this->_appendName = true;
  90          $this->_type = 'date_time_selector';
  91          // set the options, do not bother setting bogus ones
  92          if (is_array($options)) {
  93              foreach ($options as $name => $value) {
  94                  if (isset($this->_options[$name])) {
  95                      if (is_array($value) && is_array($this->_options[$name])) {
  96                          $this->_options[$name] = @array_merge($this->_options[$name], $value);
  97                      } else {
  98                          $this->_options[$name] = $value;
  99                      }
 100                  }
 101              }
 102          }
 103      }
 104  
 105      /**
 106       * Old syntax of class constructor. Deprecated in PHP7.
 107       *
 108       * @deprecated since Moodle 3.1
 109       */
 110      public function MoodleQuickForm_date_time_selector($elementName = null, $elementLabel = null, $options = array(), $attributes = null) {
 111          debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
 112          self::__construct($elementName, $elementLabel, $options, $attributes);
 113      }
 114  
 115      /**
 116       * This will create date group element constisting of day, month and year.
 117       *
 118       * @access private
 119       */
 120      function _createElements() {
 121          global $OUTPUT;
 122  
 123          // Get the calendar type used - see MDL-18375.
 124          $calendartype = \core_calendar\type_factory::get_calendar_instance();
 125  
 126          for ($i = 0; $i <= 23; $i++) {
 127              $hours[$i] = sprintf("%02d", $i);
 128          }
 129          for ($i = 0; $i < 60; $i += $this->_options['step']) {
 130              $minutes[$i] = sprintf("%02d", $i);
 131          }
 132  
 133          $this->_elements = array();
 134          $dateformat = $calendartype->get_date_order($this->_options['startyear'], $this->_options['stopyear']);
 135          if (right_to_left()) {   // Display time to the right of date, in RTL mode.
 136              $this->_elements[] = $this->createFormElement('select', 'minute', get_string('minute', 'form'),
 137                  $minutes, $this->getAttributes(), true);
 138              $this->_elements[] = $this->createFormElement('select', 'hour', get_string('hour', 'form'),
 139                  $hours, $this->getAttributes(), true);
 140              // Reverse date element (Should be: Day, Month, Year), in RTL mode.
 141              $dateformat = array_reverse($dateformat);
 142          }
 143          foreach ($dateformat as $key => $date) {
 144              // E_STRICT creating elements without forms is nasty because it internally uses $this
 145              $this->_elements[] = $this->createFormElement('select', $key, get_string($key, 'form'), $date, $this->getAttributes(), true);
 146          }
 147          if (!right_to_left()) {   // Display time to the left of date, in LTR mode.
 148              $this->_elements[] = $this->createFormElement('select', 'hour', get_string('hour', 'form'), $hours,
 149                  $this->getAttributes(), true);
 150              $this->_elements[] = $this->createFormElement('select', 'minute', get_string('minute', 'form'), $minutes,
 151                  $this->getAttributes(), true);
 152          }
 153          // The YUI2 calendar only supports the gregorian calendar type so only display the calendar image if this is being used.
 154          if ($calendartype->get_name() === 'gregorian') {
 155              $image = $OUTPUT->pix_icon('i/calendar', get_string('calendar', 'calendar'), 'moodle');
 156              $this->_elements[] = $this->createFormElement('link', 'calendar',
 157                      null, '#', $image);
 158          }
 159          // If optional we add a checkbox which the user can use to turn if on
 160          if ($this->_options['optional']) {
 161              $this->_elements[] = $this->createFormElement('checkbox', 'enabled', null, get_string('enable'), $this->getAttributes(), true);
 162          }
 163          foreach ($this->_elements as $element){
 164              if (method_exists($element, 'setHiddenLabel')){
 165                  $element->setHiddenLabel(true);
 166              }
 167          }
 168  
 169      }
 170  
 171      /**
 172       * Called by HTML_QuickForm whenever form event is made on this element
 173       *
 174       * @param string $event Name of event
 175       * @param mixed $arg event arguments
 176       * @param object $caller calling object
 177       * @return bool
 178       */
 179      function onQuickFormEvent($event, $arg, &$caller) {
 180          $this->setMoodleForm($caller);
 181          switch ($event) {
 182              case 'updateValue':
 183                  // Constant values override both default and submitted ones
 184                  // default values are overriden by submitted.
 185                  $value = $this->_findValue($caller->_constantValues);
 186                  if (null === $value) {
 187                      // If no boxes were checked, then there is no value in the array
 188                      // yet we don't want to display default value in this case.
 189                      if ($caller->isSubmitted() && !$caller->is_new_repeat($this->getName())) {
 190                          $value = $this->_findValue($caller->_submitValues);
 191                      } else {
 192                          $value = $this->_findValue($caller->_defaultValues);
 193                      }
 194                  }
 195                  $requestvalue=$value;
 196                  if ($value == 0 || $value === '') {
 197                      $value = $this->_options['defaulttime'];
 198                      if (!$value) {
 199                          $value = time();
 200                      }
 201                  }
 202                  if (!is_array($value)) {
 203                      $calendartype = \core_calendar\type_factory::get_calendar_instance();
 204                      $currentdate = $calendartype->timestamp_to_date_array($value, $this->_options['timezone']);
 205                      // Round minutes to the previous multiple of step.
 206                      $currentdate['minutes'] -= $currentdate['minutes'] % $this->_options['step'];
 207                      $value = array(
 208                          'minute' => $currentdate['minutes'],
 209                          'hour' => $currentdate['hours'],
 210                          'day' => $currentdate['mday'],
 211                          'month' => $currentdate['mon'],
 212                          'year' => $currentdate['year']);
 213                      // If optional, default to off, unless a date was provided.
 214                      if ($this->_options['optional']) {
 215                          $value['enabled'] = $requestvalue != 0;
 216                      }
 217                  } else {
 218                      $value['enabled'] = isset($value['enabled']);
 219                  }
 220                  if (null !== $value) {
 221                      $this->setValue($value);
 222                  }
 223                  break;
 224              case 'createElement':
 225                  if (isset($arg[2]['optional']) && $arg[2]['optional']) {
 226                      // When using the function addElement, rather than createElement, we still
 227                      // enter this case, making this check necessary.
 228                      if ($this->_usedcreateelement) {
 229                          $caller->disabledIf($arg[0] . '[day]', $arg[0] . '[enabled]');
 230                          $caller->disabledIf($arg[0] . '[month]', $arg[0] . '[enabled]');
 231                          $caller->disabledIf($arg[0] . '[year]', $arg[0] . '[enabled]');
 232                          $caller->disabledIf($arg[0] . '[hour]', $arg[0] . '[enabled]');
 233                          $caller->disabledIf($arg[0] . '[minute]', $arg[0] . '[enabled]');
 234                      } else {
 235                          $caller->disabledIf($arg[0], $arg[0] . '[enabled]');
 236                      }
 237                  }
 238                  return parent::onQuickFormEvent($event, $arg, $caller);
 239                  break;
 240              case 'addElement':
 241                  $this->_usedcreateelement = false;
 242                  return parent::onQuickFormEvent($event, $arg, $caller);
 243                  break;
 244              default:
 245                  return parent::onQuickFormEvent($event, $arg, $caller);
 246          }
 247      }
 248  
 249      /**
 250       * Returns HTML for advchecbox form element.
 251       *
 252       * @return string
 253       */
 254      function toHtml() {
 255          include_once('HTML/QuickForm/Renderer/Default.php');
 256          $renderer = new HTML_QuickForm_Renderer_Default();
 257          $renderer->setElementTemplate('{element}');
 258          parent::accept($renderer);
 259  
 260          $html = $this->_wrap[0];
 261          if ($this->_usedcreateelement) {
 262              $html .= html_writer::tag('span', $renderer->toHtml(), array('class' => 'fdate_time_selector'));
 263          } else {
 264              $html .= $renderer->toHtml();
 265          }
 266          $html .= $this->_wrap[1];
 267  
 268          return $html;
 269      }
 270  
 271      /**
 272       * Accepts a renderer
 273       *
 274       * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
 275       * @param bool $required Whether a group is required
 276       * @param string $error An error message associated with a group
 277       */
 278      function accept(&$renderer, $required = false, $error = null) {
 279          form_init_date_js();
 280          $renderer->renderElement($this, $required, $error);
 281      }
 282  
 283      /**
 284       * Export for template
 285       *
 286       * @param renderer_base $output
 287       * @return array|stdClass
 288       */
 289      public function export_for_template(renderer_base $output) {
 290          form_init_date_js();
 291          return parent::export_for_template($output);
 292      }
 293  
 294      /**
 295       * Output a timestamp. Give it the name of the group.
 296       *
 297       * @param array $submitValues values submitted.
 298       * @param bool $assoc specifies if returned array is associative
 299       * @return array
 300       */
 301      function exportValue(&$submitValues, $assoc = false) {
 302          $valuearray = array();
 303          foreach ($this->_elements as $element){
 304              $thisexport = $element->exportValue($submitValues[$this->getName()], true);
 305              if ($thisexport!=null){
 306                  $valuearray += $thisexport;
 307              }
 308          }
 309          if (count($valuearray)){
 310              if($this->_options['optional']) {
 311                  // If checkbox is on, the value is zero, so go no further
 312                  if(empty($valuearray['enabled'])) {
 313                      return $this->_prepareValue(0, $assoc);
 314                  }
 315              }
 316              // Get the calendar type used - see MDL-18375.
 317              $calendartype = \core_calendar\type_factory::get_calendar_instance();
 318              $gregoriandate = $calendartype->convert_to_gregorian($valuearray['year'],
 319                                                                   $valuearray['month'],
 320                                                                   $valuearray['day'],
 321                                                                   $valuearray['hour'],
 322                                                                   $valuearray['minute']);
 323              $value = make_timestamp($gregoriandate['year'],
 324                                                        $gregoriandate['month'],
 325                                                        $gregoriandate['day'],
 326                                                        $gregoriandate['hour'],
 327                                                        $gregoriandate['minute'],
 328                                                        0,
 329                                                        $this->_options['timezone'],
 330                                                        true);
 331  
 332              return $this->_prepareValue($value, $assoc);
 333          } else {
 334              return null;
 335          }
 336      }
 337  }