MDL-33766 files: Improved validation of areamaxbytes
[moodle.git] / repository / repository_ajax.php
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/>.
18 /**
19  * The Web service script that is called from the filepicker front end
20  *
21  * @since 2.0
22  * @package    repository
23  * @copyright  2009 Dongsheng Cai {@link http://dongsheng.org}
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 define('AJAX_SCRIPT', true);
29 require_once(dirname(dirname(__FILE__)).'/config.php');
30 require_once(dirname(dirname(__FILE__)).'/lib/filelib.php');
31 require_once(dirname(__FILE__).'/lib.php');
33 $err = new stdClass();
35 // Parameters
36 $action    = optional_param('action', '', PARAM_ALPHA);
37 $repo_id   = optional_param('repo_id', 0, PARAM_INT);           // Repository ID
38 $contextid = optional_param('ctx_id', SYSCONTEXTID, PARAM_INT); // Context ID
39 $env       = optional_param('env', 'filepicker', PARAM_ALPHA);  // Opened in editor or moodleform
40 $license   = optional_param('license', $CFG->sitedefaultlicense, PARAM_TEXT);
41 $author    = optional_param('author', '', PARAM_TEXT);          // File author
42 $source    = optional_param('source', '', PARAM_RAW);           // File to download
43 $itemid    = optional_param('itemid', 0, PARAM_INT);            // Itemid
44 $page      = optional_param('page', '', PARAM_RAW);             // Page
45 $maxbytes  = optional_param('maxbytes', 0, PARAM_INT);          // Maxbytes
46 $req_path  = optional_param('p', '', PARAM_RAW);                // Path
47 $accepted_types  = optional_param_array('accepted_types', '*', PARAM_RAW);
48 $saveas_filename = optional_param('title', '', PARAM_FILE);     // save as file name
49 $areamaxbytes  = optional_param('areamaxbytes', FILE_AREA_MAX_BYTES_UNLIMITED, PARAM_INT); // Area max bytes.
50 $saveas_path   = optional_param('savepath', '/', PARAM_PATH);   // save as file path
51 $search_text   = optional_param('s', '', PARAM_CLEANHTML);
52 $linkexternal  = optional_param('linkexternal', '', PARAM_ALPHA);
53 $usefilereference  = optional_param('usefilereference', false, PARAM_BOOL);
55 list($context, $course, $cm) = get_context_info_array($contextid);
56 require_login($course, false, $cm);
57 $PAGE->set_context($context);
59 echo $OUTPUT->header(); // send headers
60 @header('Content-type: text/html; charset=utf-8');
62 // If uploaded file is larger than post_max_size (php.ini) setting, $_POST content will be empty.
63 if (empty($_POST) && !empty($action)) {
64     $err->error = get_string('errorpostmaxsize', 'repository');
65     die(json_encode($err));
66 }
68 if (!confirm_sesskey()) {
69     $err->error = get_string('invalidsesskey', 'error');
70     die(json_encode($err));
71 }
73 // Get repository instance information
74 $repooptions = array(
75     'ajax' => true,
76     'mimetypes' => $accepted_types
77 );
78 $repo = repository::get_repository_by_id($repo_id, $contextid, $repooptions);
80 // Check permissions
81 $repo->check_capability();
83 $coursemaxbytes = 0;
84 if (!empty($course)) {
85     $coursemaxbytes = $course->maxbytes;
86 }
87 // Make sure maxbytes passed is within site filesize limits.
88 $maxbytes = get_user_max_upload_file_size($context, $CFG->maxbytes, $coursemaxbytes, $maxbytes);
90 // Wait as long as it takes for this script to finish
91 set_time_limit(0);
93 // Early actions which need to be done before repository instances initialised
94 switch ($action) {
95     // global search
96     case 'gsearch':
97         $params = array();
98         $params['context'] = array(context::instance_by_id($contextid), get_system_context());
99         $params['currentcontext'] = context::instance_by_id($contextid);
100         $repos = repository::get_instances($params);
101         $list = array();
102         foreach($repos as $repo){
103             if ($repo->global_search()) {
104                 $ret = $repo->search($search_text);
105                 array_walk($ret['list'], 'repository_attach_id', $repo->id);  // See function below
106                 $tmp = array_merge($list, $ret['list']);
107                 $list = $tmp;
108             }
109         }
110         $listing = array('list'=>$list);
111         $listing['gsearch'] = true;
112         die(json_encode($listing));
113         break;
115     // remove the cache files & logout
116     case 'ccache':
117         $cache = new curl_cache;
118         $cache->refresh();
119         $action = 'list';
120         break;
123 // These actions all occur on the currently active repository instance
124 switch ($action) {
125     case 'sign':
126     case 'signin':
127     case 'list':
128         if ($repo->check_login()) {
129             $listing = repository::prepare_listing($repo->get_listing($req_path, $page));
130             $listing['repo_id'] = $repo_id;
131             echo json_encode($listing);
132             break;
133         } else {
134             $action = 'login';
135         }
136     case 'login':
137         $listing = $repo->print_login();
138         $listing['repo_id'] = $repo_id;
139         echo json_encode($listing);
140         break;
141     case 'logout':
142         $logout = $repo->logout();
143         $logout['repo_id'] = $repo_id;
144         echo json_encode($logout);
145         break;
146     case 'searchform':
147         $search_form['repo_id'] = $repo_id;
148         $search_form['form'] = $repo->print_search();
149         $search_form['allowcaching'] = true;
150         echo json_encode($search_form);
151         break;
152     case 'search':
153         $search_result = repository::prepare_listing($repo->search($search_text, (int)$page));
154         $search_result['repo_id'] = $repo_id;
155         $search_result['issearchresult'] = true;
156         echo json_encode($search_result);
157         break;
158     case 'download':
159         // validate mimetype
160         $mimetypes = array();
161         if ((is_array($accepted_types) and in_array('*', $accepted_types)) or $accepted_types == '*') {
162             $mimetypes = '*';
163         } else {
164             foreach ($accepted_types as $type) {
165                 $mimetypes[] = mimeinfo('type', $type);
166             }
167             if (!in_array(mimeinfo('type', $saveas_filename), $mimetypes)) {
168                 throw new moodle_exception('invalidfiletype', 'repository', '', get_mimetype_description(array('filename' => $saveas_filename)));
169             }
170         }
172         // We have two special repository type need to deal with
173         // local and recent plugins don't added new files to moodle, just add new records to database
174         // so we don't check user quota and maxbytes here
175         $allowexternallink = (int)get_config(null, 'repositoryallowexternallinks');
176         if (!empty($allowexternallink)) {
177             $allowexternallink = true;
178         } else {
179             $allowexternallink = false;
180         }
181         // allow external links in url element all the time
182         $allowexternallink = ($allowexternallink || ($env == 'url'));
184         $reference = $repo->get_file_reference($source);
186         // Use link of the files
187         if ($allowexternallink and $linkexternal === 'yes' and ($repo->supported_returntypes() & FILE_EXTERNAL)) {
188             // use external link
189             $link = $repo->get_link($reference);
190             $info = array();
191             $info['file'] = $saveas_filename;
192             $info['type'] = 'link';
193             $info['url'] = $link;
194             echo json_encode($info);
195             die;
196         } else {
197             $fs = get_file_storage();
199             // Prepare file record.
200             $record = new stdClass();
201             $record->filepath = $saveas_path;
202             $record->filename = $saveas_filename;
203             $record->component = 'user';
204             $record->filearea = 'draft';
205             $record->itemid = $itemid;
206             $record->license = $license;
207             $record->author = $author;
209             if ($record->filepath !== '/') {
210                 $record->filepath = trim($record->filepath, '/');
211                 $record->filepath = '/'.$record->filepath.'/';
212             }
213             $usercontext = context_user::instance($USER->id);
214             $now = time();
215             $record->contextid = $usercontext->id;
216             $record->timecreated = $now;
217             $record->timemodified = $now;
218             $record->userid = $USER->id;
219             $record->sortorder = 0;
221             // Check that user has permission to access this file
222             if (!$repo->file_is_accessible($source)) {
223                 throw new file_exception('storedfilecannotread');
224             }
226             // {@link repository::build_source_field()}
227             $sourcefield = $repo->get_file_source_info($source);
228             $record->source = $repo::build_source_field($sourcefield);
230             // If file is already a reference, set $source = file source, $repo = file repository
231             // note that in this case user may not have permission to access the source file directly
232             // so no file_browser/file_info can be used below
233             if ($repo->has_moodle_files()) {
234                 $file = repository::get_moodle_file($source);
235                 if ($file && $file->is_external_file()) {
236                     $sourcefield = $file->get_source(); // remember the original source
237                     $record->source = $repo::build_source_field($sourcefield);
238                     $record->contenthash = $file->get_contenthash();
239                     $record->filesize = $file->get_filesize();
240                     $reference = $file->get_reference();
241                     $repo_id = $file->get_repository_id();
242                     $repo = repository::get_repository_by_id($repo_id, $contextid, $repooptions);
243                 }
244             }
246             if ($usefilereference) {
247                 if ($repo->has_moodle_files()) {
248                     $sourcefile = repository::get_moodle_file($reference);
249                     $record->contenthash = $sourcefile->get_contenthash();
250                     $record->filesize = $sourcefile->get_filesize();
251                 }
252                 // Check if file exists.
253                 if (repository::draftfile_exists($itemid, $saveas_path, $saveas_filename)) {
254                     // File name being used, rename it.
255                     $unused_filename = repository::get_unused_filename($itemid, $saveas_path, $saveas_filename);
256                     $record->filename = $unused_filename;
257                     // Create a file copy using unused filename.
258                     $storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
260                     $event = array();
261                     $event['event'] = 'fileexists';
262                     $event['newfile'] = new stdClass;
263                     $event['newfile']->filepath = $saveas_path;
264                     $event['newfile']->filename = $unused_filename;
265                     $event['newfile']->url = moodle_url::make_draftfile_url($itemid, $saveas_path, $unused_filename)->out();
267                     $event['existingfile'] = new stdClass;
268                     $event['existingfile']->filepath = $saveas_path;
269                     $event['existingfile']->filename = $saveas_filename;
270                     $event['existingfile']->url      = moodle_url::make_draftfile_url($itemid, $saveas_path, $saveas_filename)->out();;
271                 } else {
273                     $storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
274                     $event = array(
275                         'url'=>moodle_url::make_draftfile_url($storedfile->get_itemid(), $storedfile->get_filepath(), $storedfile->get_filename())->out(),
276                         'id'=>$storedfile->get_itemid(),
277                         'file'=>$storedfile->get_filename(),
278                         'icon' => $OUTPUT->pix_url(file_file_icon($storedfile, 32))->out(),
279                     );
280                 }
281                 // Repository plugin callback
282                 // You can cache reository file in this callback
283                 // or complete other tasks.
284                 $repo->cache_file_by_reference($reference, $storedfile);
285                 echo json_encode($event);
286                 die;
287             } else if ($repo->has_moodle_files()) {
288                 // Some repository plugins (local, user, coursefiles, recent) are hosting moodle
289                 // internal files, we cannot use get_file method, so we use copy_to_area method
291                 // If the moodle file is an alias we copy this alias, otherwise we copy the file
292                 // {@link repository::copy_to_area()}.
293                 $fileinfo = $repo->copy_to_area($reference, $record, $maxbytes, $areamaxbytes);
295                 echo json_encode($fileinfo);
296                 die;
297             } else {
298                 // Download file to moodle.
299                 $downloadedfile = $repo->get_file($reference, $saveas_filename);
300                 if (empty($downloadedfile['path'])) {
301                     $err->error = get_string('cannotdownload', 'repository');
302                     die(json_encode($err));
303                 }
305                 // Check if we exceed the max bytes of the area.
306                 if (file_is_draft_area_limit_reached($itemid, $areamaxbytes, filesize($downloadedfile['path']))) {
307                     throw new file_exception('maxareabytes');
308                 }
310                 // Check if exceed maxbytes.
311                 if ($maxbytes != -1 && filesize($downloadedfile['path']) > $maxbytes) {
312                     throw new file_exception('maxbytes');
313                 }
315                 $info = repository::move_to_filepool($downloadedfile['path'], $record);
316                 if (empty($info)) {
317                     $info['e'] = get_string('error', 'moodle');
318                 }
319             }
320             echo json_encode($info);
321             die;
322         }
323         break;
324     case 'upload':
325         $result = $repo->upload($saveas_filename, $maxbytes);
326         echo json_encode($result);
327         break;
329     case 'overwrite':
330         // existing file
331         $filepath    = required_param('existingfilepath', PARAM_PATH);
332         $filename    = required_param('existingfilename', PARAM_FILE);
333         // user added file which needs to replace the existing file
334         $newfilepath = required_param('newfilepath', PARAM_PATH);
335         $newfilename = required_param('newfilename', PARAM_FILE);
337         $info = repository::overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename);
338         echo json_encode($info);
339         break;
341     case 'deletetmpfile':
342         // delete tmp file
343         $newfilepath = required_param('newfilepath', PARAM_PATH);
344         $newfilename = required_param('newfilename', PARAM_FILE);
345         echo json_encode(repository::delete_tempfile_from_draft($itemid, $newfilepath, $newfilename));
347         break;