Merge branch 'MDL-81073' of https://github.com/paulholden/moodle
[moodle.git] / lib / form / filepicker.php
blob8fee6b48acaf48c8dcd245a0937bd899ed710903
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 * Filepicker form element
21 * Contains HTML class for a single filepicker 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/button.php");
31 require_once($CFG->dirroot.'/repository/lib.php');
32 require_once('templatable_form_element.php');
34 /**
35 * Filepicker form element
37 * HTML class for a single filepicker element (based on button)
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_filepicker extends HTML_QuickForm_input implements templatable {
45 use templatable_form_element {
46 export_for_template as export_for_template_base;
48 /** @var string html for help button, if empty then no help will icon will be dispalyed. */
49 public $_helpbutton = '';
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);
57 /**
58 * Constructor
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
66 public function __construct($elementName=null, $elementLabel=null, $attributes=null, $options=null) {
67 global $CFG, $PAGE;
69 $options = (array)$options;
70 foreach ($options as $name=>$value) {
71 if (array_key_exists($name, $this->_options)) {
72 $this->_options[$name] = $value;
75 if (empty($options['return_types'])) {
76 $this->_options['return_types'] = FILE_INTERNAL;
78 $fpmaxbytes = 0;
79 if (!empty($options['maxbytes'])) {
80 $fpmaxbytes = $options['maxbytes'];
82 $coursemaxbytes = 0;
83 if (!empty($PAGE->course->maxbytes)) {
84 $coursemaxbytes = $PAGE->course->maxbytes;
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);
91 /**
92 * Old syntax of class constructor. Deprecated in PHP7.
94 * @deprecated since Moodle 3.1
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);
102 * Returns html for help button.
104 * @return string html for help button
106 function getHelpButton() {
107 return $this->_helpbutton;
111 * Returns type of filepicker element
113 * @return string
115 function getElementTemplateType() {
116 if ($this->_flagFrozen){
117 return 'nodisplay';
118 } else {
119 return 'default';
124 * Returns HTML for filepicker form element.
126 * @return string
128 function toHtml() {
129 global $CFG, $COURSE, $USER, $PAGE, $OUTPUT;
130 $id = $this->_attributes['id'];
131 $elname = $this->_attributes['name'];
133 if ($this->_flagFrozen) {
134 return $this->getFrozenHtml();
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);
142 if ($COURSE->id == SITEID) {
143 $context = context_system::instance();
144 } else {
145 $context = context_course::instance($COURSE->id);
148 $client_id = uniqid();
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;
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"/>';
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);
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(),
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>';
187 if (!empty($args->accepted_types) && $args->accepted_types != '*') {
188 $html .= html_writer::tag('p', get_string('filesofthesetypes', 'form'));
189 $util = new \core_form\filetypes_util();
190 $filetypedescriptions = $util->describe_file_types($args->accepted_types);
191 $html .= $OUTPUT->render_from_template('core_form/filetypes-descriptions', $filetypedescriptions);
194 return $html;
198 * export uploaded file
200 * @param array $submitValues values submitted.
201 * @param bool $assoc specifies if returned array is associative
202 * @return array
204 function exportValue(&$submitValues, $assoc = false) {
205 global $USER;
207 $draftitemid = $this->_findValue($submitValues);
208 if (null === $draftitemid) {
209 $draftitemid = $this->getValue();
212 // make sure max one file is present and it is not too big
213 if (!is_null($draftitemid)) {
214 $fs = get_file_storage();
215 $usercontext = context_user::instance($USER->id);
216 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id DESC', false)) {
217 $file = array_shift($files);
218 if ($this->_options['maxbytes']
219 and $this->_options['maxbytes'] !== USER_CAN_IGNORE_FILE_SIZE_LIMITS
220 and $file->get_filesize() > $this->_options['maxbytes']) {
222 // bad luck, somebody tries to sneak in oversized file
223 $file->delete();
225 foreach ($files as $file) {
226 // only one file expected
227 $file->delete();
232 return $this->_prepareValue($draftitemid, true);
235 public function export_for_template(renderer_base $output) {
236 $context = $this->export_for_template_base($output);
237 $context['html'] = $this->toHtml();
238 return $context;
242 * Check that the file has the allowed type.
244 * @param array $value Draft item id with the uploaded files.
245 * @return string|null Validation error message or null.
247 public function validateSubmitValue($value) {
249 $filetypesutil = new \core_form\filetypes_util();
250 $allowlist = $filetypesutil->normalize_file_types($this->_options['accepted_types']);
252 if (empty($allowlist) || $allowlist === ['*']) {
253 // Any file type is allowed, nothing to check here.
254 return;
257 $draftfiles = file_get_drafarea_files($value);
258 $wrongfiles = array();
260 if (empty($draftfiles)) {
261 // No file uploaded, nothing to check here.
262 return;
265 foreach ($draftfiles->list as $file) {
266 if (!$filetypesutil->is_allowed_file_type($file->filename, $allowlist)) {
267 $wrongfiles[] = $file->filename;
271 if ($wrongfiles) {
272 $a = array(
273 'allowlist' => implode(', ', $allowlist),
274 'wrongfiles' => implode(', ', $wrongfiles),
276 return get_string('err_wrongfileextension', 'core_form', $a);
279 return;