Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 39 and 402]

   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   * Filepicker form element
  20   *
  21   * Contains HTML class for a single filepicker form element
  22   *
  23   * @package   core_form
  24   * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
  25   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26   */
  27  
  28  global $CFG;
  29  
  30  require_once("HTML/QuickForm/button.php");
  31  require_once($CFG->dirroot.'/repository/lib.php');
  32  require_once ('templatable_form_element.php');
  33  
  34  /**
  35   * Filepicker form element
  36   *
  37   * HTML class for a single filepicker element (based on button)
  38   *
  39   * @package   core_form
  40   * @category  form
  41   * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
  42   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  43   */
  44  class MoodleQuickForm_filepicker extends HTML_QuickForm_input implements templatable {
  45      use templatable_form_element {
  46          export_for_template as export_for_template_base;
  47      }
  48      /** @var string html for help button, if empty then no help will icon will be dispalyed. */
  49      public $_helpbutton = '';
  50  
  51      /** @var array options provided to initalize filemanager */
  52      // PHP doesn't support 'key' => $value1 | $value2 in class definition
  53      // We cannot do $_options = array('return_types'=> FILE_INTERNAL | FILE_REFERENCE);
  54      // So I have to set null here, and do it in constructor
  55      protected $_options    = array('maxbytes'=>0, 'accepted_types'=>'*', 'return_types'=>null);
  56  
  57      /**
  58       * Constructor
  59       *
  60       * @param string $elementName (optional) name of the filepicker
  61       * @param string $elementLabel (optional) filepicker label
  62       * @param array $attributes (optional) Either a typical HTML attribute string
  63       *              or an associative array
  64       * @param array $options set of options to initalize filepicker
  65       */
  66      public function __construct($elementName=null, $elementLabel=null, $attributes=null, $options=null) {
  67          global $CFG, $PAGE;
  68  
  69          $options = (array)$options;
  70          foreach ($options as $name=>$value) {
  71              if (array_key_exists($name, $this->_options)) {
  72                  $this->_options[$name] = $value;
  73              }
  74          }
  75          if (empty($options['return_types'])) {
  76              $this->_options['return_types'] = FILE_INTERNAL;
  77          }
  78          $fpmaxbytes = 0;
  79          if (!empty($options['maxbytes'])) {
  80              $fpmaxbytes = $options['maxbytes'];
  81          }
  82          $coursemaxbytes = 0;
  83          if (!empty($PAGE->course->maxbytes)) {
  84              $coursemaxbytes = $PAGE->course->maxbytes;
  85          }
  86          $this->_options['maxbytes'] = get_user_max_upload_file_size($PAGE->context, $CFG->maxbytes, $coursemaxbytes, $fpmaxbytes);
  87          $this->_type = 'filepicker';
  88          parent::__construct($elementName, $elementLabel, $attributes);
  89      }
  90  
  91      /**
  92       * Old syntax of class constructor. Deprecated in PHP7.
  93       *
  94       * @deprecated since Moodle 3.1
  95       */
  96      public function MoodleQuickForm_filepicker($elementName=null, $elementLabel=null, $attributes=null, $options=null) {
  97          debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
  98          self::__construct($elementName, $elementLabel, $attributes, $options);
  99      }
 100  
 101      /**
 102       * Returns html for help button.
 103       *
 104       * @return string html for help button
 105       */
 106      function getHelpButton() {
 107          return $this->_helpbutton;
 108      }
 109  
 110      /**
 111       * Returns type of filepicker element
 112       *
 113       * @return string
 114       */
 115      function getElementTemplateType() {
 116          if ($this->_flagFrozen){
 117              return 'nodisplay';
 118          } else {
 119              return 'default';
 120          }
 121      }
 122  
 123      /**
 124       * Returns HTML for filepicker form element.
 125       *
 126       * @return string
 127       */
 128      function toHtml() {
 129          global $CFG, $COURSE, $USER, $PAGE, $OUTPUT;
 130          $id     = $this->_attributes['id'];
 131          $elname = $this->_attributes['name'];
 132  
 133          if ($this->_flagFrozen) {
 134              return $this->getFrozenHtml();
 135          }
 136          if (!$draftitemid = (int)$this->getValue()) {
 137              // no existing area info provided - let's use fresh new draft area
 138              $draftitemid = file_get_unused_draft_itemid();
 139              $this->setValue($draftitemid);
 140          }
 141  
 142          if ($COURSE->id == SITEID) {
 143              $context = context_system::instance();
 144          } else {
 145              $context = context_course::instance($COURSE->id);
 146          }
 147  
 148          $client_id = uniqid();
 149  
 150          $args = new stdClass();
 151          // need these three to filter repositories list
 152          $args->accepted_types = $this->_options['accepted_types']?$this->_options['accepted_types']:'*';
 153          $args->return_types = $this->_options['return_types'];
 154          $args->itemid = $draftitemid;
 155          $args->maxbytes = $this->_options['maxbytes'];
 156          $args->context = $PAGE->context;
 157          $args->buttonname = $elname.'choose';
 158          $args->elementid = $id;
 159  
 160          $html = $this->_getTabs();
 161          $fp = new file_picker($args);
 162          $options = $fp->options;
 163          $options->context = $PAGE->context;
 164          $html .= $OUTPUT->render($fp);
 165          $html .= '<input type="hidden" name="'.$elname.'" id="'.$id.'" value="'.$draftitemid.'" class="filepickerhidden"/>';
 166  
 167          $module = array('name'=>'form_filepicker', 'fullpath'=>'/lib/form/filepicker.js', 'requires'=>array('core_filepicker', 'node', 'node-event-simulate', 'core_dndupload'));
 168          $PAGE->requires->js_init_call('M.form_filepicker.init', array($fp->options), true, $module);
 169  
 170          $nonjsfilepicker = new moodle_url('/repository/draftfiles_manager.php', array(
 171              'env'=>'filepicker',
 172              'action'=>'browse',
 173              'itemid'=>$draftitemid,
 174              'subdirs'=>0,
 175              'maxbytes'=>$options->maxbytes,
 176              'maxfiles'=>1,
 177              'ctx_id'=>$PAGE->context->id,
 178              'course'=>$PAGE->course->id,
 179              'sesskey'=>sesskey(),
 180              ));
 181  
 182          // non js file picker
 183          $html .= '<noscript>';
 184          $html .= "<div><object type='text/html' data='$nonjsfilepicker' height='160' width='600' style='border:1px solid #000'></object></div>";
 185          $html .= '</noscript>';
 186  
 187          if (!empty($options->accepted_types) && $options->accepted_types != '*') {
 188              $html .= html_writer::tag('p', get_string('filesofthesetypes', 'form'));
 189              $util = new \core_form\filetypes_util();
 190              $filetypes = $options->accepted_types;
 191              $filetypedescriptions = $util->describe_file_types($filetypes);
 192              $html .= $OUTPUT->render_from_template('core_form/filetypes-descriptions', $filetypedescriptions);
 193          }
 194  
 195          return $html;
 196      }
 197  
 198      /**
 199       * export uploaded file
 200       *
 201       * @param array $submitValues values submitted.
 202       * @param bool $assoc specifies if returned array is associative
 203       * @return array
 204       */
 205      function exportValue(&$submitValues, $assoc = false) {
 206          global $USER;
 207  
 208          $draftitemid = $this->_findValue($submitValues);
 209          if (null === $draftitemid) {
 210              $draftitemid = $this->getValue();
 211          }
 212  
 213          // make sure max one file is present and it is not too big
 214          if (!is_null($draftitemid)) {
 215              $fs = get_file_storage();
 216              $usercontext = context_user::instance($USER->id);
 217              if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id DESC', false)) {
 218                  $file = array_shift($files);
 219                  if ($this->_options['maxbytes']
 220                      and $this->_options['maxbytes'] !== USER_CAN_IGNORE_FILE_SIZE_LIMITS
 221                      and $file->get_filesize() > $this->_options['maxbytes']) {
 222  
 223                      // bad luck, somebody tries to sneak in oversized file
 224                      $file->delete();
 225                  }
 226                  foreach ($files as $file) {
 227                      // only one file expected
 228                      $file->delete();
 229                  }
 230              }
 231          }
 232  
 233          return $this->_prepareValue($draftitemid, true);
 234      }
 235  
 236      public function export_for_template(renderer_base $output) {
 237          $context = $this->export_for_template_base($output);
 238          $context['html'] = $this->toHtml();
 239          return $context;
 240      }
 241  
 242      /**
 243       * Check that the file has the allowed type.
 244       *
 245       * @param array $value Draft item id with the uploaded files.
 246       * @return string|null Validation error message or null.
 247       */
 248      public function validateSubmitValue($value) {
 249  
 250          $filetypesutil = new \core_form\filetypes_util();
 251          $allowlist = $filetypesutil->normalize_file_types($this->_options['accepted_types']);
 252  
 253          if (empty($allowlist) || $allowlist === ['*']) {
 254              // Any file type is allowed, nothing to check here.
 255              return;
 256          }
 257  
 258          $draftfiles = file_get_drafarea_files($value);
 259          $wrongfiles = array();
 260  
 261          if (empty($draftfiles)) {
 262              // No file uploaded, nothing to check here.
 263              return;
 264          }
 265  
 266          foreach ($draftfiles->list as $file) {
 267              if (!$filetypesutil->is_allowed_file_type($file->filename, $allowlist)) {
 268                  $wrongfiles[] = $file->filename;
 269              }
 270          }
 271  
 272          if ($wrongfiles) {
 273              $a = array(
 274                  'allowlist' => implode(', ', $allowlist),
 275                  'wrongfiles' => implode(', ', $wrongfiles),
 276              );
 277              return get_string('err_wrongfileextension', 'core_form', $a);
 278          }
 279  
 280          return;
 281      }
 282  }