Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

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

   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   * Duration form element
  20   *
  21   * Contains class to create length of time for element.
  22   *
  23   * @package   core_form
  24   * @copyright 2009 Tim Hunt
  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  require_once($CFG->libdir . '/form/text.php');
  32  
  33  /**
  34   * Duration element
  35   *
  36   * HTML class for a length of time. For example, 30 minutes of 4 days. The
  37   * values returned to PHP is the duration in seconds (an int rounded to the nearest second).
  38   *
  39   * @package   core_form
  40   * @category  form
  41   * @copyright 2009 Tim Hunt
  42   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  43   */
  44  class MoodleQuickForm_duration extends MoodleQuickForm_group {
  45      /**
  46       * Control the field names for form elements
  47       * optional => if true, show a checkbox beside the element to turn it on (or off)
  48       * defaultunit => which unit is default when the form is blank (default Minutes).
  49       * @var array
  50       */
  51      protected $_options = ['optional' => false, 'defaultunit' => MINSECS];
  52  
  53      /** @var array associative array of time units (days, hours, minutes, seconds) */
  54      private $_units = null;
  55  
  56     /**
  57      * constructor
  58      *
  59      * @param ?string $elementName Element's name
  60      * @param mixed $elementLabel Label(s) for an element
  61      * @param array $options Options to control the element's display. Recognised values are
  62      *      'optional' => true/false - whether to display an 'enabled' checkbox next to the element.
  63      *      'defaultunit' => 1|MINSECS|HOURSECS|DAYSECS|WEEKSECS - the default unit to display when
  64      *              the time is blank. If not specified, minutes is used.
  65      *      'units' => array containing some or all of 1, MINSECS, HOURSECS, DAYSECS and WEEKSECS
  66      *              which unit choices to offer.
  67      * @param mixed $attributes Either a typical HTML attribute string or an associative array
  68      */
  69      public function __construct($elementName = null, $elementLabel = null,
  70              $options = [], $attributes = null) {
  71          parent::__construct($elementName, $elementLabel, $attributes);
  72          $this->_persistantFreeze = true;
  73          $this->_appendName = true;
  74          $this->_type = 'duration';
  75  
  76          // Set the options, do not bother setting bogus ones
  77          if (!is_array($options)) {
  78              $options = [];
  79          }
  80          $this->_options['optional'] = !empty($options['optional']);
  81          if (isset($options['defaultunit'])) {
  82              if (!array_key_exists($options['defaultunit'], $this->get_units())) {
  83                  throw new coding_exception($options['defaultunit'] .
  84                          ' is not a recognised unit in MoodleQuickForm_duration.');
  85              }
  86              $this->_options['defaultunit'] = $options['defaultunit'];
  87          }
  88          if (isset($options['units'])) {
  89              if (!is_array($options['units'])) {
  90                  throw new coding_exception(
  91                          'When creating a duration form field, units option must be an array.');
  92              }
  93              // Validate and register requested units.
  94              $availableunits = $this->get_units();
  95              $displayunits = [];
  96              foreach ($options['units'] as $requestedunit) {
  97                  if (!isset($availableunits[$requestedunit])) {
  98                      throw new coding_exception($requestedunit .
  99                              ' is not a recognised unit in MoodleQuickForm_duration.');
 100                  }
 101                  $displayunits[$requestedunit] = $availableunits[$requestedunit];
 102              }
 103              krsort($displayunits, SORT_NUMERIC);
 104              $this->_options['units'] = $displayunits;
 105          }
 106      }
 107  
 108      /**
 109       * Old syntax of class constructor. Deprecated in PHP7.
 110       *
 111       * @deprecated since Moodle 3.1
 112       */
 113      public function MoodleQuickForm_duration($elementName = null, $elementLabel = null,
 114              $options = [], $attributes = null) {
 115          debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
 116          self::__construct($elementName, $elementLabel, $options, $attributes);
 117      }
 118  
 119      /**
 120       * Returns time associative array of unit length.
 121       *
 122       * @return array unit length in seconds => string unit name.
 123       */
 124      public function get_units() {
 125          if (is_null($this->_units)) {
 126              $this->_units = [
 127                  WEEKSECS => get_string('weeks'),
 128                  DAYSECS => get_string('days'),
 129                  HOURSECS => get_string('hours'),
 130                  MINSECS => get_string('minutes'),
 131                  1 => get_string('seconds'),
 132              ];
 133          }
 134          return $this->_units;
 135      }
 136  
 137      /**
 138       * Get the units to be used for this field.
 139       *
 140       * The ones specified in the options passed to the constructor, or all by default.
 141       *
 142       * @return array number of seconds => lang string.
 143       */
 144      protected function get_units_used() {
 145          if (!empty($this->_options['units'])) {
 146              return $this->_options['units'];
 147          } else {
 148              return $this->get_units();
 149          }
 150      }
 151  
 152      /**
 153       * Converts seconds to the best possible time unit. for example
 154       * 1800 -> [30, MINSECS] = 30 minutes.
 155       *
 156       * @param int $seconds an amout of time in seconds.
 157       * @return array associative array ($number => $unit)
 158       */
 159      public function seconds_to_unit($seconds) {
 160          if ($seconds == 0) {
 161              return [0, $this->_options['defaultunit']];
 162          }
 163          foreach ($this->get_units_used() as $unit => $notused) {
 164              if (fmod($seconds, $unit) == 0) {
 165                  return [$seconds / $unit, $unit];
 166              }
 167          }
 168          return [$seconds, 1];
 169      }
 170  
 171      /**
 172       * Override of standard quickforms method to create this element.
 173       */
 174      function _createElements() {
 175          $attributes = $this->getAttributes();
 176          if (is_null($attributes)) {
 177              $attributes = [];
 178          }
 179          if (!isset($attributes['size'])) {
 180              $attributes['size'] = 3;
 181          }
 182          $this->_elements = [];
 183          // E_STRICT creating elements without forms is nasty because it internally uses $this
 184          $number = $this->createFormElement('text', 'number',
 185                  get_string('time', 'form'), $attributes, true);
 186          $number->set_force_ltr(true);
 187          $this->_elements[] = $number;
 188          unset($attributes['size']);
 189          $this->_elements[] = $this->createFormElement('select', 'timeunit',
 190                  get_string('timeunit', 'form'), $this->get_units_used(), $attributes, true);
 191          // If optional we add a checkbox which the user can use to turn if on
 192          if($this->_options['optional']) {
 193              $this->_elements[] = $this->createFormElement('checkbox', 'enabled', null,
 194                      get_string('enable'), $this->getAttributes(), true);
 195          }
 196          foreach ($this->_elements as $element){
 197              if (method_exists($element, 'setHiddenLabel')){
 198                  $element->setHiddenLabel(true);
 199              }
 200          }
 201      }
 202  
 203      /**
 204       * Called by HTML_QuickForm whenever form event is made on this element
 205       *
 206       * @param string $event Name of event
 207       * @param mixed $arg event arguments
 208       * @param MoodleQuickForm $caller calling object
 209       * @return bool
 210       */
 211      function onQuickFormEvent($event, $arg, &$caller) {
 212          $this->setMoodleForm($caller);
 213          switch ($event) {
 214              case 'updateValue':
 215                  // constant values override both default and submitted ones
 216                  // default values are overriden by submitted
 217                  $value = $this->_findValue($caller->_constantValues);
 218                  if (null === $value) {
 219                      // if no boxes were checked, then there is no value in the array
 220                      // yet we don't want to display default value in this case
 221                      if ($caller->isSubmitted() && !$caller->is_new_repeat($this->getName())) {
 222                          $value = $this->_findValue($caller->_submitValues);
 223                      } else {
 224                          $value = $this->_findValue($caller->_defaultValues);
 225                      }
 226                  }
 227                  if (!is_array($value)) {
 228                      list($number, $unit) = $this->seconds_to_unit($value);
 229                      $value = ['number' => $number, 'timeunit' => $unit];
 230                      // If optional, default to off, unless a date was provided
 231                      if ($this->_options['optional']) {
 232                          $value['enabled'] = $number != 0;
 233                      }
 234                  } else {
 235                      $value['enabled'] = isset($value['enabled']);
 236                  }
 237                  if (null !== $value){
 238                      $this->setValue($value);
 239                  }
 240                  break;
 241  
 242              case 'createElement':
 243                  if (!empty($arg[2]['optional'])) {
 244                      $caller->disabledIf($arg[0], $arg[0] . '[enabled]');
 245                  }
 246                  $caller->setType($arg[0] . '[number]', PARAM_FLOAT);
 247                  return parent::onQuickFormEvent($event, $arg, $caller);
 248  
 249              default:
 250                  return parent::onQuickFormEvent($event, $arg, $caller);
 251          }
 252      }
 253  
 254      /**
 255       * Returns HTML for advchecbox form element.
 256       *
 257       * @return string
 258       */
 259      function toHtml() {
 260          include_once('HTML/QuickForm/Renderer/Default.php');
 261          $renderer = new HTML_QuickForm_Renderer_Default();
 262          $renderer->setElementTemplate('{element}');
 263          parent::accept($renderer);
 264          return $renderer->toHtml();
 265      }
 266  
 267      /**
 268       * Accepts a renderer
 269       *
 270       * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
 271       * @param bool $required Whether a group is required
 272       * @param ?string $error An error message associated with a group
 273       */
 274      function accept(&$renderer, $required = false, $error = null) {
 275          $renderer->renderElement($this, $required, $error);
 276      }
 277  
 278      /**
 279       * Output a timestamp. Give it the name of the group.
 280       * Override of standard quickforms method.
 281       *
 282       * @param  array $submitValues
 283       * @param  bool  $assoc  whether to return the value as associative array
 284       * @return array field name => value. The value is the time interval in seconds.
 285       */
 286      function exportValue(&$submitValues, $assoc = false) {
 287          // Get the values from all the child elements.
 288          $valuearray = [];
 289          foreach ($this->_elements as $element) {
 290              $thisexport = $element->exportValue($submitValues[$this->getName()], true);
 291              if (!is_null($thisexport)) {
 292                  $valuearray += $thisexport;
 293              }
 294          }
 295  
 296          // Convert the value to an integer number of seconds.
 297          if (empty($valuearray)) {
 298              return null;
 299          }
 300          if ($this->_options['optional'] && empty($valuearray['enabled'])) {
 301              return $this->_prepareValue(0, $assoc);
 302          }
 303          return $this->_prepareValue(
 304                  (int) round($valuearray['number'] * $valuearray['timeunit']), $assoc);
 305      }
 306  }