MDL-59299 filemanager: Display what filetypes are accepted
[moodle.git] / lib / form / filemanager.php
CommitLineData
ae4a98a1 1<?php
56a7bf68 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
6c1fd304 17
56a7bf68 18/**
6c1fd304
RT
19 * FileManager form element
20 *
21 * Contains HTML class for a filemanager form element
56a7bf68 22 *
6c1fd304
RT
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
56a7bf68 26 */
ae4a98a1 27
28global $CFG;
8546def3 29
30require_once('HTML/QuickForm/element.php');
ae4a98a1 31require_once($CFG->dirroot.'/lib/filelib.php');
133fd70b 32require_once($CFG->dirroot.'/repository/lib.php');
344321e1 33require_once('templatable_form_element.php');
8546def3 34
6c1fd304
RT
35/**
36 * Filemanager form element
37 *
38 * FilemaneManager lets user to upload/manage multiple files
39 * @package core_form
40 * @category form
41 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
58b7d48f 42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6c1fd304 43 */
91bda4cd 44class MoodleQuickForm_filemanager extends HTML_QuickForm_element implements templatable {
344321e1
DW
45 use templatable_form_element {
46 export_for_template as export_for_template_base;
47 }
48
6c1fd304 49 /** @var string html for help button, if empty then no help will icon will be dispalyed. */
12f11f23 50 public $_helpbutton = '';
6c1fd304
RT
51
52 /** @var array options provided to initalize filemanager */
67233725
DC
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
68acd115
FM
56 protected $_options = array('mainfile' => '', 'subdirs' => 1, 'maxbytes' => -1, 'maxfiles' => -1,
57 'accepted_types' => '*', 'return_types' => null, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED);
8546def3 58
6c1fd304
RT
59 /**
60 * Constructor
61 *
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
67 */
1a0df553 68 public function __construct($elementName=null, $elementLabel=null, $attributes=null, $options=null) {
56a7bf68 69 global $CFG, $PAGE;
56a7bf68 70
adb7cbb4 71 $options = (array)$options;
72 foreach ($options as $name=>$value) {
73 if (array_key_exists($name, $this->_options)) {
74 $this->_options[$name] = $value;
75 }
b5b188ce 76 }
ad620df3 77 if (!empty($options['maxbytes'])) {
845c2ae1 78 $this->_options['maxbytes'] = get_user_max_upload_file_size($PAGE->context, $CFG->maxbytes, $options['maxbytes']);
45d0b872 79 }
67233725 80 if (empty($options['return_types'])) {
151b0f94 81 $this->_options['return_types'] = (FILE_INTERNAL | FILE_REFERENCE | FILE_CONTROLLED_LINK);
67233725 82 }
c6aa3670 83 $this->_type = 'filemanager';
1a0df553
MG
84 parent::__construct($elementName, $elementLabel, $attributes);
85 }
86
87 /**
88 * Old syntax of class constructor. Deprecated in PHP7.
89 *
90 * @deprecated since Moodle 3.1
91 */
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);
8546def3 95 }
96
de5009f4
MG
97 /**
98 * Called by HTML_QuickForm whenever form event is made on this element
99 *
100 * @param string $event Name of event
101 * @param mixed $arg event arguments
102 * @param object $caller calling object
103 * @return bool
104 */
105 function onQuickFormEvent($event, $arg, &$caller)
106 {
107 switch ($event) {
108 case 'createElement':
109 $caller->setType($arg[0], PARAM_INT);
110 break;
111 }
112 return parent::onQuickFormEvent($event, $arg, $caller);
113 }
114
6c1fd304
RT
115 /**
116 * Sets name of filemanager
117 *
118 * @param string $name name of the filemanager
119 */
8546def3 120 function setName($name) {
121 $this->updateAttributes(array('name'=>$name));
122 }
123
6c1fd304
RT
124 /**
125 * Returns name of filemanager
126 *
127 * @return string
128 */
8546def3 129 function getName() {
130 return $this->getAttribute('name');
131 }
132
6c1fd304
RT
133 /**
134 * Updates filemanager attribute value
58b7d48f 135 *
6c1fd304
RT
136 * @param string $value value to set
137 */
8546def3 138 function setValue($value) {
b933a139 139 $this->updateAttributes(array('value'=>$value));
8546def3 140 }
141
6c1fd304
RT
142 /**
143 * Returns filemanager attribute value
144 *
145 * @return string
146 */
8546def3 147 function getValue() {
b933a139 148 return $this->getAttribute('value');
8546def3 149 }
150
6c1fd304
RT
151 /**
152 * Returns maximum file size which can be uploaded
153 *
154 * @return int
155 */
45d0b872 156 function getMaxbytes() {
157 return $this->_options['maxbytes'];
158 }
159
6c1fd304
RT
160 /**
161 * Sets maximum file size which can be uploaded
162 *
163 * @param int $maxbytes file size
164 */
45d0b872 165 function setMaxbytes($maxbytes) {
845c2ae1
AD
166 global $CFG, $PAGE;
167 $this->_options['maxbytes'] = get_user_max_upload_file_size($PAGE->context, $CFG->maxbytes, $maxbytes);
45d0b872 168 }
169
21e3ea77
FM
170 /**
171 * Returns the maximum size of the area.
172 *
173 * @return int
174 */
175 function getAreamaxbytes() {
176 return $this->_options['areamaxbytes'];
177 }
178
179 /**
180 * Sets the maximum size of the area.
181 *
182 * @param int $areamaxbytes size limit
183 */
184 function setAreamaxbytes($areamaxbytes) {
185 $this->_options['areamaxbytes'] = $areamaxbytes;
186 }
187
6c1fd304
RT
188 /**
189 * Returns true if subdirectoy can be created, else false
190 *
191 * @return bool
192 */
45d0b872 193 function getSubdirs() {
194 return $this->_options['subdirs'];
195 }
196
6c1fd304
RT
197 /**
198 * Set option to create sub directory, while uploading file
199 *
200 * @param bool $allow true if sub directory can be created.
201 */
45d0b872 202 function setSubdirs($allow) {
203 $this->_options['subdirs'] = $allow;
204 }
205
6c1fd304
RT
206 /**
207 * Returns maximum number of files which can be uploaded
208 *
209 * @return int
210 */
4664b66c 211 function getMaxfiles() {
212 return $this->_options['maxfiles'];
213 }
214
6c1fd304
RT
215 /**
216 * Sets maximum number of files which can be uploaded.
217 *
218 * @param int $num number of files
219 */
4664b66c 220 function setMaxfiles($num) {
221 $this->_options['maxfiles'] = $num;
222 }
223
6c1fd304
RT
224 /**
225 * Returns html for help button.
226 *
227 * @return string html for help button
228 */
8546def3 229 function getHelpButton() {
230 return $this->_helpbutton;
231 }
232
6c1fd304
RT
233 /**
234 * Returns type of filemanager element
235 *
236 * @return string
237 */
8546def3 238 function getElementTemplateType() {
239 if ($this->_flagFrozen){
240 return 'nodisplay';
241 } else {
242 return 'default';
243 }
244 }
245
6c1fd304
RT
246 /**
247 * Returns HTML for filemanager form element.
248 *
249 * @return string
250 */
8546def3 251 function toHtml() {
1420162a 252 global $CFG, $USER, $COURSE, $PAGE, $OUTPUT;
b5cb48de 253 require_once("$CFG->dirroot/repository/lib.php");
254
b933a139 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');
258 }
8546def3 259
260 if ($this->_flagFrozen) {
261 return $this->getFrozenHtml();
262 }
263
b5b188ce 264 $id = $this->_attributes['id'];
265 $elname = $this->_attributes['name'];
266 $subdirs = $this->_options['subdirs'];
a83ad946 267 $maxbytes = $this->_options['maxbytes'];
b933a139 268 $draftitemid = $this->getValue();
99eaca9d 269 $accepted_types = $this->_options['accepted_types'];
8546def3 270
b933a139 271 if (empty($draftitemid)) {
8546def3 272 // no existing area info provided - let's use fresh new draft area
273 require_once("$CFG->libdir/filelib.php");
edc0c493 274 $this->setValue(file_get_unused_draft_itemid());
b933a139 275 $draftitemid = $this->getValue();
8546def3 276 }
277
99eaca9d 278 $client_id = uniqid();
4bb7f787 279
133fd70b 280 // filemanager options
6bdfef5d 281 $options = new stdClass();
56a7bf68 282 $options->mainfile = $this->_options['mainfile'];
8a3e6a56 283 $options->maxbytes = $this->_options['maxbytes'];
56a7bf68 284 $options->maxfiles = $this->getMaxfiles();
285 $options->client_id = $client_id;
286 $options->itemid = $draftitemid;
be4487f4 287 $options->subdirs = $this->_options['subdirs'];
56a7bf68 288 $options->target = $id;
4d2ee4c2 289 $options->accepted_types = $accepted_types;
67233725 290 $options->return_types = $this->_options['return_types'];
4d2ee4c2 291 $options->context = $PAGE->context;
21e3ea77 292 $options->areamaxbytes = $this->_options['areamaxbytes'];
56a7bf68 293
294 $html = $this->_getTabs();
906e7d89
MG
295 $fm = new form_filemanager($options);
296 $output = $PAGE->get_renderer('core', 'files');
297 $html .= $output->render($fm);
4d2ee4c2 298
de5009f4 299 $html .= html_writer::empty_tag('input', array('value' => $draftitemid, 'name' => $elname, 'type' => 'hidden'));
f0e23170 300 // label element needs 'for' attribute work
de5009f4 301 $html .= html_writer::empty_tag('input', array('value' => '', 'id' => 'id_'.$elname, 'type' => 'hidden'));
f0e23170 302
320889c0
JO
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);
309 }
310
56a7bf68 311 return $html;
8546def3 312 }
91bda4cd
DW
313
314 public function export_for_template(renderer_base $output) {
344321e1 315 $context = $this->export_for_template_base($output);
91bda4cd
DW
316 $context['html'] = $this->toHtml();
317 return $context;
318 }
1661204a
DM
319
320 /**
321 * Check that all files have the allowed type.
322 *
323 * @param array $value Draft item id with the uploaded files.
324 * @return string|null Validation error message or null.
325 */
326 public function validateSubmitValue($value) {
327
328 $filetypesutil = new \core_form\filetypes_util();
329 $whitelist = $filetypesutil->normalize_file_types($this->_options['accepted_types']);
330
331 if (empty($whitelist) || $whitelist === ['*']) {
332 // Any file type is allowed, nothing to check here.
333 return;
334 }
335
336 $draftfiles = file_get_drafarea_files($value);
337 $wrongfiles = array();
338
339 if (empty($draftfiles)) {
340 // No file uploaded, nothing to check here.
341 return;
342 }
343
344 foreach ($draftfiles->list as $file) {
345 if (!$filetypesutil->is_allowed_file_type($file->filename, $whitelist)) {
346 $wrongfiles[] = $file->filename;
347 }
348 }
349
350 if ($wrongfiles) {
351 $a = array(
352 'whitelist' => implode(', ', $whitelist),
353 'wrongfiles' => implode(', ', $wrongfiles),
354 );
355 return get_string('err_wrongfileextension', 'core_form', $a);
356 }
357
358 return;
359 }
8546def3 360}
64f93798 361
64f93798
PS
362/**
363 * Data structure representing a file manager.
364 *
6c1fd304
RT
365 * This class defines the data structure for file mnager
366 *
367 * @package core_form
64f93798
PS
368 * @copyright 2010 Dongsheng Cai
369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6c1fd304 370 * @todo do not use this abstraction (skodak)
64f93798 371 */
906e7d89 372class form_filemanager implements renderable {
6c1fd304 373 /** @var stdClass $options options for filemanager */
64f93798 374 public $options;
6c1fd304
RT
375
376 /**
377 * Constructor
378 *
379 * @param stdClass $options options for filemanager
906e7d89
MG
380 * default options are:
381 * maxbytes=>-1,
68acd115 382 * areamaxbytes => FILE_AREA_MAX_BYTES_UNLIMITED,
906e7d89
MG
383 * maxfiles=>-1,
384 * itemid=>0,
385 * subdirs=>false,
386 * client_id=>uniqid(),
387 * acepted_types=>'*',
388 * return_types=>FILE_INTERNAL,
e709ddd2
MG
389 * context=>$PAGE->context,
390 * author=>fullname($USER),
391 * licenses=>array build from $CFG->licenses,
392 * defaultlicense=>$CFG->sitedefaultlicense
6c1fd304 393 */
64f93798
PS
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,
68acd115 399 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
64f93798
PS
400 'maxfiles'=>-1,
401 'itemid'=>0,
402 'subdirs'=>0,
403 'client_id'=>uniqid(),
404 'accepted_types'=>'*',
405 'return_types'=>FILE_INTERNAL,
e709ddd2
MG
406 'context'=>$PAGE->context,
407 'author'=>fullname($USER),
408 'licenses'=>array()
64f93798 409 );
e709ddd2
MG
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;
417 }
418 }
419 if (!empty($CFG->sitedefaultlicense)) {
420 $defaults['defaultlicense'] = $CFG->sitedefaultlicense;
421 }
64f93798 422 foreach ($defaults as $key=>$value) {
a0dc7da9
PN
423 // Using !isset() prevents us from overwriting falsey values with defaults (as empty() did).
424 if (!isset($options->$key)) {
64f93798
PS
425 $options->$key = $value;
426 }
427 }
428
429 $fs = get_file_storage();
430
431 // initilise options, getting files in root path
432 $this->options = file_get_drafarea_files($options->itemid, '/');
433
434 // calculate file count
b0c6dc1c 435 $usercontext = context_user::instance($USER->id);
64f93798
PS
436 $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id', false);
437 $filecount = count($files);
438 $this->options->filecount = $filecount;
439
440 // copying other options
441 foreach ($options as $name=>$value) {
442 $this->options->$name = $value;
443 }
444
906e7d89
MG
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;
451 }
452 if (!empty($this->options->maxbytes) && $this->options->maxbytes > 0) {
453 $maxbytes = $this->options->maxbytes;
454 }
845c2ae1 455 $this->options->maxbytes = get_user_max_upload_file_size($context, $CFG->maxbytes, $coursebytes, $maxbytes);
906e7d89 456
0398bbe6
VZ
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);
460
64f93798 461 // building file picker options
6bdfef5d 462 $params = new stdClass();
64f93798
PS
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;
470 }
64f93798 471
906e7d89
MG
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,
68acd115 480 'areamaxbytes' => $this->options->areamaxbytes,
906e7d89
MG
481 'maxfiles'=>$this->options->maxfiles,
482 'ctx_id'=>$PAGE->context->id, // TODO ?
483 'course'=>$PAGE->course->id, // TODO ?
484 'sesskey'=>sesskey(),
485 ));
adce0230 486 }
64f93798 487}