MDL-60061 mod_scorm: add support for drag/drop events
[moodle.git] / lib / form / filemanager.php
blob71686d01b67092900951367fca5fc1c178733f70
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.
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/>.
18 /**
19 * FileManager form element
21 * Contains HTML class for a filemanager form element
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
28 global $CFG;
30 require_once('HTML/QuickForm/element.php');
31 require_once($CFG->dirroot.'/lib/filelib.php');
32 require_once($CFG->dirroot.'/repository/lib.php');
33 require_once('templatable_form_element.php');
35 /**
36 * Filemanager form element
38 * FilemaneManager lets user to upload/manage multiple files
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
44 class MoodleQuickForm_filemanager extends HTML_QuickForm_element implements templatable {
45 use templatable_form_element {
46 export_for_template as export_for_template_base;
49 /** @var string html for help button, if empty then no help will icon will be dispalyed. */
50 public $_helpbutton = '';
52 /** @var array options provided to initalize filemanager */
53 // PHP doesn't support 'key' => $value1 | $value2 in class definition
54 // We cannot do $_options = array('return_types'=> FILE_INTERNAL | FILE_REFERENCE);
55 // So I have to set null here, and do it in constructor
56 protected $_options = array('mainfile' => '', 'subdirs' => 1, 'maxbytes' => -1, 'maxfiles' => -1,
57 'accepted_types' => '*', 'return_types' => null, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED);
59 /**
60 * Constructor
62 * @param string $elementName (optional) name of the filemanager
63 * @param string $elementLabel (optional) filemanager label
64 * @param array $attributes (optional) Either a typical HTML attribute string
65 * or an associative array
66 * @param array $options set of options to initalize filemanager
68 public function __construct($elementName=null, $elementLabel=null, $attributes=null, $options=null) {
69 global $CFG, $PAGE;
71 $options = (array)$options;
72 foreach ($options as $name=>$value) {
73 if (array_key_exists($name, $this->_options)) {
74 $this->_options[$name] = $value;
77 if (!empty($options['maxbytes'])) {
78 $this->_options['maxbytes'] = get_user_max_upload_file_size($PAGE->context, $CFG->maxbytes, $options['maxbytes']);
80 if (empty($options['return_types'])) {
81 $this->_options['return_types'] = (FILE_INTERNAL | FILE_REFERENCE | FILE_CONTROLLED_LINK);
83 $this->_type = 'filemanager';
84 parent::__construct($elementName, $elementLabel, $attributes);
87 /**
88 * Old syntax of class constructor. Deprecated in PHP7.
90 * @deprecated since Moodle 3.1
92 public function MoodleQuickForm_filemanager($elementName=null, $elementLabel=null, $attributes=null, $options=null) {
93 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
94 self::__construct($elementName, $elementLabel, $attributes, $options);
97 /**
98 * Called by HTML_QuickForm whenever form event is made on this element
100 * @param string $event Name of event
101 * @param mixed $arg event arguments
102 * @param object $caller calling object
103 * @return bool
105 function onQuickFormEvent($event, $arg, &$caller)
107 switch ($event) {
108 case 'createElement':
109 $caller->setType($arg[0], PARAM_INT);
110 break;
112 return parent::onQuickFormEvent($event, $arg, $caller);
116 * Sets name of filemanager
118 * @param string $name name of the filemanager
120 function setName($name) {
121 $this->updateAttributes(array('name'=>$name));
125 * Returns name of filemanager
127 * @return string
129 function getName() {
130 return $this->getAttribute('name');
134 * Updates filemanager attribute value
136 * @param string $value value to set
138 function setValue($value) {
139 $this->updateAttributes(array('value'=>$value));
143 * Returns filemanager attribute value
145 * @return string
147 function getValue() {
148 return $this->getAttribute('value');
152 * Returns maximum file size which can be uploaded
154 * @return int
156 function getMaxbytes() {
157 return $this->_options['maxbytes'];
161 * Sets maximum file size which can be uploaded
163 * @param int $maxbytes file size
165 function setMaxbytes($maxbytes) {
166 global $CFG, $PAGE;
167 $this->_options['maxbytes'] = get_user_max_upload_file_size($PAGE->context, $CFG->maxbytes, $maxbytes);
171 * Returns the maximum size of the area.
173 * @return int
175 function getAreamaxbytes() {
176 return $this->_options['areamaxbytes'];
180 * Sets the maximum size of the area.
182 * @param int $areamaxbytes size limit
184 function setAreamaxbytes($areamaxbytes) {
185 $this->_options['areamaxbytes'] = $areamaxbytes;
189 * Returns true if subdirectoy can be created, else false
191 * @return bool
193 function getSubdirs() {
194 return $this->_options['subdirs'];
198 * Set option to create sub directory, while uploading file
200 * @param bool $allow true if sub directory can be created.
202 function setSubdirs($allow) {
203 $this->_options['subdirs'] = $allow;
207 * Returns maximum number of files which can be uploaded
209 * @return int
211 function getMaxfiles() {
212 return $this->_options['maxfiles'];
216 * Sets maximum number of files which can be uploaded.
218 * @param int $num number of files
220 function setMaxfiles($num) {
221 $this->_options['maxfiles'] = $num;
225 * Returns html for help button.
227 * @return string html for help button
229 function getHelpButton() {
230 return $this->_helpbutton;
234 * Returns type of filemanager element
236 * @return string
238 function getElementTemplateType() {
239 if ($this->_flagFrozen){
240 return 'nodisplay';
241 } else {
242 return 'default';
247 * Returns HTML for filemanager form element.
249 * @return string
251 function toHtml() {
252 global $CFG, $USER, $COURSE, $PAGE, $OUTPUT;
253 require_once("$CFG->dirroot/repository/lib.php");
255 // security - never ever allow guest/not logged in user to upload anything or use this element!
256 if (isguestuser() or !isloggedin()) {
257 print_error('noguest');
260 if ($this->_flagFrozen) {
261 return $this->getFrozenHtml();
264 $id = $this->_attributes['id'];
265 $elname = $this->_attributes['name'];
266 $subdirs = $this->_options['subdirs'];
267 $maxbytes = $this->_options['maxbytes'];
268 $draftitemid = $this->getValue();
269 $accepted_types = $this->_options['accepted_types'];
271 if (empty($draftitemid)) {
272 // no existing area info provided - let's use fresh new draft area
273 require_once("$CFG->libdir/filelib.php");
274 $this->setValue(file_get_unused_draft_itemid());
275 $draftitemid = $this->getValue();
278 $client_id = uniqid();
280 // filemanager options
281 $options = new stdClass();
282 $options->mainfile = $this->_options['mainfile'];
283 $options->maxbytes = $this->_options['maxbytes'];
284 $options->maxfiles = $this->getMaxfiles();
285 $options->client_id = $client_id;
286 $options->itemid = $draftitemid;
287 $options->subdirs = $this->_options['subdirs'];
288 $options->target = $id;
289 $options->accepted_types = $accepted_types;
290 $options->return_types = $this->_options['return_types'];
291 $options->context = $PAGE->context;
292 $options->areamaxbytes = $this->_options['areamaxbytes'];
294 $html = $this->_getTabs();
295 $fm = new form_filemanager($options);
296 $output = $PAGE->get_renderer('core', 'files');
297 $html .= $output->render($fm);
299 $html .= html_writer::empty_tag('input', array('value' => $draftitemid, 'name' => $elname, 'type' => 'hidden'));
300 // label element needs 'for' attribute work
301 $html .= html_writer::empty_tag('input', array('value' => '', 'id' => 'id_'.$elname, 'type' => 'hidden'));
303 if (!empty($options->accepted_types) && $options->accepted_types != '*') {
304 $html .= html_writer::tag('p', get_string('filesofthesetypes', 'form'));
305 $util = new \core_form\filetypes_util();
306 $filetypes = $options->accepted_types;
307 $filetypedescriptions = $util->describe_file_types($filetypes);
308 $html .= $OUTPUT->render_from_template('core_form/filetypes-descriptions', $filetypedescriptions);
311 return $html;
314 public function export_for_template(renderer_base $output) {
315 $context = $this->export_for_template_base($output);
316 $context['html'] = $this->toHtml();
317 return $context;
321 * Check that all files have the allowed type.
323 * @param array $value Draft item id with the uploaded files.
324 * @return string|null Validation error message or null.
326 public function validateSubmitValue($value) {
328 $filetypesutil = new \core_form\filetypes_util();
329 $whitelist = $filetypesutil->normalize_file_types($this->_options['accepted_types']);
331 if (empty($whitelist) || $whitelist === ['*']) {
332 // Any file type is allowed, nothing to check here.
333 return;
336 $draftfiles = file_get_drafarea_files($value);
337 $wrongfiles = array();
339 if (empty($draftfiles)) {
340 // No file uploaded, nothing to check here.
341 return;
344 foreach ($draftfiles->list as $file) {
345 if (!$filetypesutil->is_allowed_file_type($file->filename, $whitelist)) {
346 $wrongfiles[] = $file->filename;
350 if ($wrongfiles) {
351 $a = array(
352 'whitelist' => implode(', ', $whitelist),
353 'wrongfiles' => implode(', ', $wrongfiles),
355 return get_string('err_wrongfileextension', 'core_form', $a);
358 return;
363 * Data structure representing a file manager.
365 * This class defines the data structure for file mnager
367 * @package core_form
368 * @copyright 2010 Dongsheng Cai
369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
370 * @todo do not use this abstraction (skodak)
372 class form_filemanager implements renderable {
373 /** @var stdClass $options options for filemanager */
374 public $options;
377 * Constructor
379 * @param stdClass $options options for filemanager
380 * default options are:
381 * maxbytes=>-1,
382 * areamaxbytes => FILE_AREA_MAX_BYTES_UNLIMITED,
383 * maxfiles=>-1,
384 * itemid=>0,
385 * subdirs=>false,
386 * client_id=>uniqid(),
387 * acepted_types=>'*',
388 * return_types=>FILE_INTERNAL,
389 * context=>$PAGE->context,
390 * author=>fullname($USER),
391 * licenses=>array build from $CFG->licenses,
392 * defaultlicense=>$CFG->sitedefaultlicense
394 public function __construct(stdClass $options) {
395 global $CFG, $USER, $PAGE;
396 require_once($CFG->dirroot. '/repository/lib.php');
397 $defaults = array(
398 'maxbytes'=>-1,
399 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
400 'maxfiles'=>-1,
401 'itemid'=>0,
402 'subdirs'=>0,
403 'client_id'=>uniqid(),
404 'accepted_types'=>'*',
405 'return_types'=>FILE_INTERNAL,
406 'context'=>$PAGE->context,
407 'author'=>fullname($USER),
408 'licenses'=>array()
410 if (!empty($CFG->licenses)) {
411 $array = explode(',', $CFG->licenses);
412 foreach ($array as $license) {
413 $l = new stdClass();
414 $l->shortname = $license;
415 $l->fullname = get_string($license, 'license');
416 $defaults['licenses'][] = $l;
419 if (!empty($CFG->sitedefaultlicense)) {
420 $defaults['defaultlicense'] = $CFG->sitedefaultlicense;
422 foreach ($defaults as $key=>$value) {
423 // Using !isset() prevents us from overwriting falsey values with defaults (as empty() did).
424 if (!isset($options->$key)) {
425 $options->$key = $value;
429 $fs = get_file_storage();
431 // initilise options, getting files in root path
432 $this->options = file_get_drafarea_files($options->itemid, '/');
434 // calculate file count
435 $usercontext = context_user::instance($USER->id);
436 $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id', false);
437 $filecount = count($files);
438 $this->options->filecount = $filecount;
440 // copying other options
441 foreach ($options as $name=>$value) {
442 $this->options->$name = $value;
445 // calculate the maximum file size as minimum from what is specified in filepicker options,
446 // course options, global configuration and php settings
447 $coursebytes = $maxbytes = 0;
448 list($context, $course, $cm) = get_context_info_array($this->options->context->id);
449 if (is_object($course)) {
450 $coursebytes = $course->maxbytes;
452 if (!empty($this->options->maxbytes) && $this->options->maxbytes > 0) {
453 $maxbytes = $this->options->maxbytes;
455 $this->options->maxbytes = get_user_max_upload_file_size($context, $CFG->maxbytes, $coursebytes, $maxbytes);
457 $this->options->userprefs = array();
458 $this->options->userprefs['recentviewmode'] = get_user_preferences('filemanager_recentviewmode', '');
459 user_preference_allow_ajax_update('filemanager_recentviewmode', PARAM_INT);
461 // building file picker options
462 $params = new stdClass();
463 $params->accepted_types = $options->accepted_types;
464 $params->return_types = $options->return_types;
465 $params->context = $options->context;
466 $params->env = 'filemanager';
467 $params->disable_types = !empty($options->disable_types)?$options->disable_types:array();
468 $filepicker_options = initialise_filepicker($params);
469 $this->options->filepicker = $filepicker_options;
472 public function get_nonjsurl() {
473 global $PAGE;
474 return new moodle_url('/repository/draftfiles_manager.php', array(
475 'env'=>'filemanager',
476 'action'=>'browse',
477 'itemid'=>$this->options->itemid,
478 'subdirs'=>$this->options->subdirs,
479 'maxbytes'=>$this->options->maxbytes,
480 'areamaxbytes' => $this->options->areamaxbytes,
481 'maxfiles'=>$this->options->maxfiles,
482 'ctx_id'=>$PAGE->context->id, // TODO ?
483 'course'=>$PAGE->course->id, // TODO ?
484 'sesskey'=>sesskey(),