MDL-33950 check if source file is accessible in repository_ajax.php
[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 $saveas_path   = optional_param('savepath', '/', PARAM_PATH);   // save as file path
50 $search_text   = optional_param('s', '', PARAM_CLEANHTML);
51 $linkexternal  = optional_param('linkexternal', '', PARAM_ALPHA);
52 $usefilereference  = optional_param('usefilereference', false, PARAM_BOOL);
54 list($context, $course, $cm) = get_context_info_array($contextid);
55 require_login($course, false, $cm);
56 $PAGE->set_context($context);
58 echo $OUTPUT->header(); // send headers
59 @header('Content-type: text/html; charset=utf-8');
61 // If uploaded file is larger than post_max_size (php.ini) setting, $_POST content will be empty.
62 if (empty($_POST) && !empty($action)) {
63     $err->error = get_string('errorpostmaxsize', 'repository');
64     die(json_encode($err));
65 }
67 if (!confirm_sesskey()) {
68     $err->error = get_string('invalidsesskey', 'error');
69     die(json_encode($err));
70 }
72 // Get repository instance information
73 $sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
75 if (!$repository = $DB->get_record_sql($sql, array($repo_id))) {
76     $err->error = get_string('invalidrepositoryid', 'repository');
77     die(json_encode($err));
78 } else {
79     $type = $repository->type;
80 }
82 // Check permissions
83 repository::check_capability($contextid, $repository);
85 $moodle_maxbytes = get_user_max_upload_file_size($context);
86 // to prevent maxbytes greater than moodle maxbytes setting
87 if ($maxbytes == 0 || $maxbytes>=$moodle_maxbytes) {
88     $maxbytes = $moodle_maxbytes;
89 }
91 // Wait as long as it takes for this script to finish
92 set_time_limit(0);
94 // Early actions which need to be done before repository instances initialised
95 switch ($action) {
96     // global search
97     case 'gsearch':
98         $params = array();
99         $params['context'] = array(get_context_instance_by_id($contextid), get_system_context());
100         $params['currentcontext'] = get_context_instance_by_id($contextid);
101         $repos = repository::get_instances($params);
102         $list = array();
103         foreach($repos as $repo){
104             if ($repo->global_search()) {
105                 $ret = $repo->search($search_text);
106                 array_walk($ret['list'], 'repository_attach_id', $repo->id);  // See function below
107                 $tmp = array_merge($list, $ret['list']);
108                 $list = $tmp;
109             }
110         }
111         $listing = array('list'=>$list);
112         $listing['gsearch'] = true;
113         die(json_encode($listing));
114         break;
116     // remove the cache files & logout
117     case 'ccache':
118         $cache = new curl_cache;
119         $cache->refresh();
120         $action = 'list';
121         break;
124 if (file_exists($CFG->dirroot.'/repository/'.$type.'/lib.php')) {
125     require_once($CFG->dirroot.'/repository/'.$type.'/lib.php');
126     $classname = 'repository_' . $type;
127     $repooptions = array(
128         'ajax' => true,
129         'name' => $repository->name,
130         'type' => $type,
131         'mimetypes' => $accepted_types
132     );
133     $repo = new $classname($repo_id, $contextid, $repooptions);
134 } else {
135     $err->error = get_string('invalidplugin', 'repository', $type);
136     die(json_encode($err));
139 // These actions all occur on the currently active repository instance
140 switch ($action) {
141     case 'sign':
142     case 'signin':
143     case 'list':
144         if ($repo->check_login()) {
145             $listing = repository::prepare_listing($repo->get_listing($req_path, $page));
146             $listing['repo_id'] = $repo_id;
147             echo json_encode($listing);
148             break;
149         } else {
150             $action = 'login';
151         }
152     case 'login':
153         $listing = $repo->print_login();
154         $listing['repo_id'] = $repo_id;
155         echo json_encode($listing);
156         break;
157     case 'logout':
158         $logout = $repo->logout();
159         $logout['repo_id'] = $repo_id;
160         echo json_encode($logout);
161         break;
162     case 'searchform':
163         $search_form['repo_id'] = $repo_id;
164         $search_form['form'] = $repo->print_search();
165         $search_form['allowcaching'] = true;
166         echo json_encode($search_form);
167         break;
168     case 'search':
169         $search_result = repository::prepare_listing($repo->search($search_text, (int)$page));
170         $search_result['repo_id'] = $repo_id;
171         $search_result['issearchresult'] = true;
172         echo json_encode($search_result);
173         break;
174     case 'download':
175         // validate mimetype
176         $mimetypes = array();
177         if ((is_array($accepted_types) and in_array('*', $accepted_types)) or $accepted_types == '*') {
178             $mimetypes = '*';
179         } else {
180             foreach ($accepted_types as $type) {
181                 $mimetypes[] = mimeinfo('type', $type);
182             }
183             if (!in_array(mimeinfo('type', $saveas_filename), $mimetypes)) {
184                 throw new moodle_exception('invalidfiletype', 'repository', '', get_mimetype_description(array('filename' => $saveas_filename)));
185             }
186         }
188         // We have two special repository type need to deal with
189         // local and recent plugins don't added new files to moodle, just add new records to database
190         // so we don't check user quota and maxbytes here
191         $allowexternallink = (int)get_config(null, 'repositoryallowexternallinks');
192         if (!empty($allowexternallink)) {
193             $allowexternallink = true;
194         } else {
195             $allowexternallink = false;
196         }
197         // allow external links in url element all the time
198         $allowexternallink = ($allowexternallink || ($env == 'url'));
200         // Use link of the files
201         if ($allowexternallink and $linkexternal === 'yes' and ($repo->supported_returntypes() & FILE_EXTERNAL)) {
202             // use external link
203             $link = $repo->get_link($source);
204             $info = array();
205             $info['file'] = $saveas_filename;
206             $info['type'] = 'link';
207             $info['url'] = $link;
208             echo json_encode($info);
209             die;
210         } else {
211             $fs = get_file_storage();
213             // Prepare file record.
214             $record = new stdClass();
215             $record->filepath = $saveas_path;
216             $record->filename = $saveas_filename;
217             $record->component = 'user';
218             $record->filearea = 'draft';
219             $record->itemid = $itemid;
220             $record->license = $license;
221             $record->author = $author;
223             if ($record->filepath !== '/') {
224                 $record->filepath = trim($record->filepath, '/');
225                 $record->filepath = '/'.$record->filepath.'/';
226             }
227             $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
228             $now = time();
229             $record->contextid = $usercontext->id;
230             $record->timecreated = $now;
231             $record->timemodified = $now;
232             $record->userid = $USER->id;
233             $record->sortorder = 0;
235             // Check that user has permission to access this file
236             if (!$repo->file_is_accessible($source)) {
237                 throw new file_exception('storedfilecannotread');
238             }
240             // If file is already a reference, set $source = file source, $repo = file repository
241             // note that in this case user may not have permission to access the source file directly
242             // so no file_browser/file_info can be used below
243             if ($repo->has_moodle_files()) {
244                 $file = repository::get_moodle_file($source);
245                 if ($file && $file->is_external_file()) {
246                     $source = $file->get_reference();
247                     $repo_id = $file->get_repository_id();
248                     $repo = repository::get_repository_by_id($repo_id, $contextid, $repooptions);
249                 }
250             }
252             // {@link repository::build_source_field()}
253             $sourcefield = $repo->get_file_source_info($source);
254             $record->source = $repo::build_source_field($sourcefield);
256             if ($usefilereference) {
257                 $reference = $repo->get_file_reference($source);
258                 // get reference life time from repo
259                 $record->referencelifetime = $repo->get_reference_file_lifetime($reference);
260                 // Check if file exists.
261                 if (repository::draftfile_exists($itemid, $saveas_path, $saveas_filename)) {
262                     // File name being used, rename it.
263                     $unused_filename = repository::get_unused_filename($itemid, $saveas_path, $saveas_filename);
264                     $record->filename = $unused_filename;
265                     // Create a file copy using unused filename.
266                     $storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
268                     $event = array();
269                     $event['event'] = 'fileexists';
270                     $event['newfile'] = new stdClass;
271                     $event['newfile']->filepath = $saveas_path;
272                     $event['newfile']->filename = $unused_filename;
273                     $event['newfile']->url = moodle_url::make_draftfile_url($itemid, $saveas_path, $unused_filename)->out();
275                     $event['existingfile'] = new stdClass;
276                     $event['existingfile']->filepath = $saveas_path;
277                     $event['existingfile']->filename = $saveas_filename;
278                     $event['existingfile']->url      = moodle_url::make_draftfile_url($itemid, $saveas_path, $saveas_filename)->out();;
279                 } else {
281                     $storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
282                     $event = array(
283                         'url'=>moodle_url::make_draftfile_url($storedfile->get_itemid(), $storedfile->get_filepath(), $storedfile->get_filename())->out(),
284                         'id'=>$storedfile->get_itemid(),
285                         'file'=>$storedfile->get_filename(),
286                         'icon' => $OUTPUT->pix_url(file_file_icon($storedfile, 32))->out(),
287                     );
288                 }
289                 // Repository plugin callback
290                 // You can cache reository file in this callback
291                 // or complete other tasks.
292                 $repo->cache_file_by_reference($reference, $storedfile);
293                 echo json_encode($event);
294                 die;
295             } else if ($repo->has_moodle_files()) {
296                 // Some repository plugins (local, user, coursefiles, recent) are hosting moodle
297                 // internal files, we cannot use get_file method, so we use copy_to_area method
299                 // If the moodle file is an alias we copy this alias, otherwise we copy the file
300                 // {@link repository::copy_to_area()}.
301                 $fileinfo = $repo->copy_to_area($source, $record, $maxbytes);
303                 echo json_encode($fileinfo);
304                 die;
305             } else {
306                 // Download file to moodle.
307                 $downloadedfile = $repo->get_file($source, $saveas_filename);
308                 if (empty($downloadedfile['path'])) {
309                     $err->error = get_string('cannotdownload', 'repository');
310                     die(json_encode($err));
311                 }
313                 // Check if exceed maxbytes.
314                 if ($maxbytes != -1 && filesize($downloadedfile['path']) > $maxbytes) {
315                     throw new file_exception('maxbytes');
316                 }
318                 $info = repository::move_to_filepool($downloadedfile['path'], $record);
319                 if (empty($info)) {
320                     $info['e'] = get_string('error', 'moodle');
321                 }
322             }
323             echo json_encode($info);
324             die;
325         }
326         break;
327     case 'upload':
328         $result = $repo->upload($saveas_filename, $maxbytes);
329         echo json_encode($result);
330         break;
332     case 'overwrite':
333         // existing file
334         $filepath    = required_param('existingfilepath', PARAM_PATH);
335         $filename    = required_param('existingfilename', PARAM_FILE);
336         // user added file which needs to replace the existing file
337         $newfilepath = required_param('newfilepath', PARAM_PATH);
338         $newfilename = required_param('newfilename', PARAM_FILE);
340         $info = repository::overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename);
341         echo json_encode($info);
342         break;
344     case 'deletetmpfile':
345         // delete tmp file
346         $newfilepath = required_param('newfilepath', PARAM_PATH);
347         $newfilename = required_param('newfilename', PARAM_FILE);
348         echo json_encode(repository::delete_tempfile_from_draft($itemid, $newfilepath, $newfilename));
350         break;