Merge branch 'MDL-26120_23' of https://github.com/jacks92/moodle into MOODLE_23_STABLE
[moodle.git] / repository / upload / lib.php
blob72799babe5bd4f2473996c526d89abc46b7ad11d
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * This plugin is used to upload files
21 * @since 2.0
22 * @package repository_upload
23 * @copyright 2010 Dongsheng Cai {@link http://dongsheng.org}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->dirroot . '/repository/lib.php');
28 /**
29 * A repository plugin to allow user uploading files
31 * @since 2.0
32 * @package repository_upload
33 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class repository_upload extends repository {
38 private $mimetypes = array();
40 /**
41 * Print a upload form
42 * @return array
44 public function print_login() {
45 return $this->get_listing();
48 /**
49 * Process uploaded file
50 * @return array|bool
52 public function upload($saveas_filename, $maxbytes) {
53 global $CFG;
55 $types = optional_param_array('accepted_types', '*', PARAM_RAW);
56 $savepath = optional_param('savepath', '/', PARAM_PATH);
57 $itemid = optional_param('itemid', 0, PARAM_INT);
58 $license = optional_param('license', $CFG->sitedefaultlicense, PARAM_TEXT);
59 $author = optional_param('author', '', PARAM_TEXT);
60 $overwriteexisting = optional_param('overwrite', false, PARAM_BOOL);
62 return $this->process_upload($saveas_filename, $maxbytes, $types, $savepath, $itemid, $license, $author, $overwriteexisting);
65 /**
66 * Do the actual processing of the uploaded file
67 * @param string $saveas_filename name to give to the file
68 * @param int $maxbytes maximum file size
69 * @param mixed $types optional array of file extensions that are allowed or '*' for all
70 * @param string $savepath optional path to save the file to
71 * @param int $itemid optional the ID for this item within the file area
72 * @param string $license optional the license to use for this file
73 * @param string $author optional the name of the author of this file
74 * @param bool $overwriteexisting optional user has asked to overwrite the existing file
75 * @return object containing details of the file uploaded
77 public function process_upload($saveas_filename, $maxbytes, $types = '*', $savepath = '/', $itemid = 0, $license = null, $author = '', $overwriteexisting = false) {
78 global $USER, $CFG;
80 if ((is_array($types) and in_array('*', $types)) or $types == '*') {
81 $this->mimetypes = '*';
82 } else {
83 foreach ($types as $type) {
84 $this->mimetypes[] = mimeinfo('type', $type);
88 if ($license == null) {
89 $license = $CFG->sitedefaultlicense;
92 $record = new stdClass();
93 $record->filearea = 'draft';
94 $record->component = 'user';
95 $record->filepath = $savepath;
96 $record->itemid = $itemid;
97 $record->license = $license;
98 $record->author = $author;
100 $context = get_context_instance(CONTEXT_USER, $USER->id);
101 $elname = 'repo_upload_file';
103 $fs = get_file_storage();
104 $sm = get_string_manager();
106 if ($record->filepath !== '/') {
107 $record->filepath = file_correct_filepath($record->filepath);
110 if (!isset($_FILES[$elname])) {
111 throw new moodle_exception('nofile');
113 if (!empty($_FILES[$elname]['error'])) {
114 switch ($_FILES[$elname]['error']) {
115 case UPLOAD_ERR_INI_SIZE:
116 throw new moodle_exception('upload_error_ini_size', 'repository_upload');
117 break;
118 case UPLOAD_ERR_FORM_SIZE:
119 throw new moodle_exception('upload_error_form_size', 'repository_upload');
120 break;
121 case UPLOAD_ERR_PARTIAL:
122 throw new moodle_exception('upload_error_partial', 'repository_upload');
123 break;
124 case UPLOAD_ERR_NO_FILE:
125 throw new moodle_exception('upload_error_no_file', 'repository_upload');
126 break;
127 case UPLOAD_ERR_NO_TMP_DIR:
128 throw new moodle_exception('upload_error_no_tmp_dir', 'repository_upload');
129 break;
130 case UPLOAD_ERR_CANT_WRITE:
131 throw new moodle_exception('upload_error_cant_write', 'repository_upload');
132 break;
133 case UPLOAD_ERR_EXTENSION:
134 throw new moodle_exception('upload_error_extension', 'repository_upload');
135 break;
136 default:
137 throw new moodle_exception('nofile');
141 self::antivir_scan_file($_FILES[$elname]['tmp_name'], $_FILES[$elname]['name'], true);
143 // {@link repository::build_source_field()}
144 $sourcefield = $this->get_file_source_info($_FILES[$elname]['name']);
145 $record->source = self::build_source_field($sourcefield);
147 if (empty($saveas_filename)) {
148 $record->filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
149 } else {
150 $ext = '';
151 $match = array();
152 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
153 if (strpos($filename, '.') === false) {
154 // File has no extension at all - do not add a dot.
155 $record->filename = $saveas_filename;
156 } else {
157 if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
158 if (isset($match[1])) {
159 $ext = $match[1];
162 $ext = !empty($ext) ? $ext : '';
163 if (preg_match('#\.(' . $ext . ')$#i', $saveas_filename)) {
164 // saveas filename contains file extension already
165 $record->filename = $saveas_filename;
166 } else {
167 $record->filename = $saveas_filename . '.' . $ext;
172 // Check the file has some non-null contents - usually an indication that a user has
173 // tried to upload a folder by mistake
174 if (!$this->check_valid_contents($_FILES[$elname]['tmp_name'])) {
175 throw new moodle_exception('upload_error_invalid_file', 'repository_upload', '', $record->filename);
178 if ($this->mimetypes != '*') {
179 // check filetype
180 $filemimetype = file_storage::mimetype($_FILES[$elname]['tmp_name'], $record->filename);
181 if (!in_array($filemimetype, $this->mimetypes)) {
182 throw new moodle_exception('invalidfiletype', 'repository', '', get_mimetype_description(array('filename' => $_FILES[$elname]['name'])));
186 if (empty($record->itemid)) {
187 $record->itemid = 0;
190 if (($maxbytes!==-1) && (filesize($_FILES[$elname]['tmp_name']) > $maxbytes)) {
191 throw new file_exception('maxbytes');
193 $record->contextid = $context->id;
194 $record->userid = $USER->id;
196 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
197 if ($overwriteexisting) {
198 repository::delete_tempfile_from_draft($record->itemid, $record->filepath, $record->filename);
199 } else {
200 $existingfilename = $record->filename;
201 $unused_filename = repository::get_unused_filename($record->itemid, $record->filepath, $record->filename);
202 $record->filename = $unused_filename;
203 $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
204 $event = array();
205 $event['event'] = 'fileexists';
206 $event['newfile'] = new stdClass;
207 $event['newfile']->filepath = $record->filepath;
208 $event['newfile']->filename = $unused_filename;
209 $event['newfile']->url = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $unused_filename)->out(false);
211 $event['existingfile'] = new stdClass;
212 $event['existingfile']->filepath = $record->filepath;
213 $event['existingfile']->filename = $existingfilename;
214 $event['existingfile']->url = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $existingfilename)->out(false);
215 return $event;
219 $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
221 return array(
222 'url'=>moodle_url::make_draftfile_url($record->itemid, $record->filepath, $record->filename)->out(false),
223 'id'=>$record->itemid,
224 'file'=>$record->filename);
229 * Checks the contents of the given file is not completely NULL - this can happen if a
230 * user drags & drops a folder onto a filemanager / filepicker element
231 * @param string $filepath full path (including filename) to file to check
232 * @return true if file has at least one non-null byte within it
234 protected function check_valid_contents($filepath) {
235 $buffersize = 4096;
237 $fp = fopen($filepath, 'r');
238 if (!$fp) {
239 return false; // Cannot read the file - something has gone wrong
241 while (!feof($fp)) {
242 // Read the file 4k at a time
243 $data = fread($fp, $buffersize);
244 if (preg_match('/[^\0]+/', $data)) {
245 fclose($fp);
246 return true; // Return as soon as a non-null byte is found
249 // Entire file is NULL
250 fclose($fp);
251 return false;
255 * Return a upload form
256 * @return array
258 public function get_listing($path = '', $page = '') {
259 global $CFG;
260 $ret = array();
261 $ret['nologin'] = true;
262 $ret['nosearch'] = true;
263 $ret['norefresh'] = true;
264 $ret['list'] = array();
265 $ret['dynload'] = false;
266 $ret['upload'] = array('label'=>get_string('attachment', 'repository'), 'id'=>'repo-form');
267 $ret['allowcaching'] = true; // indicates that result of get_listing() can be cached in filepicker.js
268 return $ret;
272 * supported return types
273 * @return int
275 public function supported_returntypes() {
276 return FILE_INTERNAL;