a8c5e825467b171717ce9864faf1f80ec3c8891a
[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 Moodle 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(__DIR__ . '/../config.php');
30 require_once(__DIR__ . '/../lib/filelib.php');
31 require_once(__DIR__.'/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, false, true);
57 $PAGE->set_context($context);
59 echo $OUTPUT->header(); // send headers
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 $repooptions = array(
74     'ajax' => true,
75     'mimetypes' => $accepted_types
76 );
78 ajax_capture_output();
79 $repo = repository::get_repository_by_id($repo_id, $contextid, $repooptions);
81 // Check permissions
82 $repo->check_capability();
84 $coursemaxbytes = 0;
85 if (!empty($course)) {
86     $coursemaxbytes = $course->maxbytes;
87 }
88 // Make sure maxbytes passed is within site filesize limits.
89 $maxbytes = get_user_max_upload_file_size($context, $CFG->maxbytes, $coursemaxbytes, $maxbytes,
90         null, $repo->uses_post_requests());
92 // Wait as long as it takes for this script to finish
93 core_php_time_limit::raise();
95 // These actions all occur on the currently active repository instance
96 switch ($action) {
97     case 'sign':
98     case 'signin':
99     case 'list':
100         if ($repo->check_login()) {
101             $listing = repository::prepare_listing($repo->get_listing($req_path, $page));
102             $listing['repo_id'] = $repo_id;
103             ajax_check_captured_output();
104             echo json_encode($listing);
105             break;
106         } else {
107             $action = 'login';
108         }
109     case 'login':
110         $listing = $repo->print_login();
111         $listing['repo_id'] = $repo_id;
112         ajax_check_captured_output();
113         echo json_encode($listing);
114         break;
115     case 'logout':
116         $logout = $repo->logout();
117         $logout['repo_id'] = $repo_id;
118         ajax_check_captured_output();
119         echo json_encode($logout);
120         break;
121     case 'searchform':
122         $search_form['repo_id'] = $repo_id;
123         $search_form['form'] = $repo->print_search();
124         $search_form['allowcaching'] = true;
125         ajax_check_captured_output();
126         echo json_encode($search_form);
127         break;
128     case 'search':
129         $search_result = repository::prepare_listing($repo->search($search_text, (int)$page));
130         $search_result['repo_id'] = $repo_id;
131         $search_result['issearchresult'] = true;
132         ajax_check_captured_output();
133         echo json_encode($search_result);
134         break;
135     case 'download':
136         // validate mimetype
137         $mimetypes = array();
138         if ((is_array($accepted_types) and in_array('*', $accepted_types)) or $accepted_types == '*') {
139             $mimetypes = '*';
140         } else {
141             foreach ($accepted_types as $type) {
142                 $mimetypes[] = mimeinfo('type', $type);
143             }
144             if (!in_array(mimeinfo('type', $saveas_filename), $mimetypes)) {
145                 throw new moodle_exception('invalidfiletype', 'repository', '', get_mimetype_description(array('filename' => $saveas_filename)));
146             }
147         }
149         // We have two special repository type need to deal with
150         // local and recent plugins don't added new files to moodle, just add new records to database
151         // so we don't check user quota and maxbytes here
152         $allowexternallink = (int)get_config(null, 'repositoryallowexternallinks');
153         if (!empty($allowexternallink)) {
154             $allowexternallink = true;
155         } else {
156             $allowexternallink = false;
157         }
158         // allow external links in url element all the time
159         $allowexternallink = ($allowexternallink || ($env == 'url'));
161         $reference = $repo->get_file_reference($source);
163         // Use link of the files
164         if ($allowexternallink and $linkexternal === 'yes' and ($repo->supported_returntypes() & FILE_EXTERNAL)) {
165             // use external link
166             $link = $repo->get_link($reference);
167             $info = array();
168             $info['file'] = $saveas_filename;
169             $info['type'] = 'link';
170             $info['url'] = $link;
171             ajax_check_captured_output();
172             echo json_encode($info);
173             die;
174         } else {
175             $fs = get_file_storage();
177             // Prepare file record.
178             $record = new stdClass();
179             $record->filepath = $saveas_path;
180             $record->filename = $saveas_filename;
181             $record->component = 'user';
182             $record->filearea = 'draft';
183             $record->itemid = $itemid;
184             $record->license = $license;
185             $record->author = $author;
187             if ($record->filepath !== '/') {
188                 $record->filepath = trim($record->filepath, '/');
189                 $record->filepath = '/'.$record->filepath.'/';
190             }
191             $usercontext = context_user::instance($USER->id);
192             $now = time();
193             $record->contextid = $usercontext->id;
194             $record->timecreated = $now;
195             $record->timemodified = $now;
196             $record->userid = $USER->id;
197             $record->sortorder = 0;
199             // Check that user has permission to access this file
200             if (!$repo->file_is_accessible($source)) {
201                 throw new file_exception('storedfilecannotread');
202             }
204             // {@link repository::build_source_field()}
205             $sourcefield = $repo->get_file_source_info($source);
206             $record->source = $repo::build_source_field($sourcefield);
208             // If file is already a reference, set $source = file source, $repo = file repository
209             // note that in this case user may not have permission to access the source file directly
210             // so no file_browser/file_info can be used below
211             if ($repo->has_moodle_files()) {
212                 $file = repository::get_moodle_file($reference);
213                 if ($file && $file->is_external_file()) {
214                     $sourcefield = $file->get_source(); // remember the original source
215                     $record->source = $repo::build_source_field($sourcefield);
216                     $record->contenthash = $file->get_contenthash();
217                     $record->filesize = $file->get_filesize();
218                     $reference = $file->get_reference();
219                     $repo_id = $file->get_repository_id();
220                     $repo = repository::get_repository_by_id($repo_id, $contextid, $repooptions);
221                 }
222             }
224             if ($usefilereference) {
225                 if ($repo->has_moodle_files()) {
226                     $sourcefile = repository::get_moodle_file($reference);
227                     $record->contenthash = $sourcefile->get_contenthash();
228                     $record->filesize = $sourcefile->get_filesize();
229                 }
230                 // Check if file exists.
231                 if (repository::draftfile_exists($itemid, $saveas_path, $saveas_filename)) {
232                     // File name being used, rename it.
233                     $unused_filename = repository::get_unused_filename($itemid, $saveas_path, $saveas_filename);
234                     $record->filename = $unused_filename;
235                     // Create a file copy using unused filename.
236                     $storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
238                     $event = array();
239                     $event['event'] = 'fileexists';
240                     $event['newfile'] = new stdClass;
241                     $event['newfile']->filepath = $saveas_path;
242                     $event['newfile']->filename = $unused_filename;
243                     $event['newfile']->url = moodle_url::make_draftfile_url($itemid, $saveas_path, $unused_filename)->out();
245                     $event['existingfile'] = new stdClass;
246                     $event['existingfile']->filepath = $saveas_path;
247                     $event['existingfile']->filename = $saveas_filename;
248                     $event['existingfile']->url      = moodle_url::make_draftfile_url($itemid, $saveas_path, $saveas_filename)->out();
249                 } else {
251                     $storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
252                     $event = array(
253                         'url'=>moodle_url::make_draftfile_url($storedfile->get_itemid(), $storedfile->get_filepath(), $storedfile->get_filename())->out(),
254                         'id'=>$storedfile->get_itemid(),
255                         'file'=>$storedfile->get_filename(),
256                         'icon' => $OUTPUT->pix_url(file_file_icon($storedfile, 32))->out(),
257                     );
258                 }
259                 // Repository plugin callback
260                 // You can cache reository file in this callback
261                 // or complete other tasks.
262                 $repo->cache_file_by_reference($reference, $storedfile);
263                 ajax_check_captured_output();
264                 echo json_encode($event);
265                 die;
266             } else if ($repo->has_moodle_files()) {
267                 // Some repository plugins (local, user, coursefiles, recent) are hosting moodle
268                 // internal files, we cannot use get_file method, so we use copy_to_area method
270                 // If the moodle file is an alias we copy this alias, otherwise we copy the file
271                 // {@link repository::copy_to_area()}.
272                 $fileinfo = $repo->copy_to_area($reference, $record, $maxbytes, $areamaxbytes);
274                 ajax_check_captured_output();
275                 echo json_encode($fileinfo);
276                 die;
277             } else {
278                 // Download file to moodle.
279                 $downloadedfile = $repo->get_file($reference, $saveas_filename);
280                 if (empty($downloadedfile['path'])) {
281                     $err->error = get_string('cannotdownload', 'repository');
282                     die(json_encode($err));
283                 }
285                 // Check if exceed maxbytes.
286                 if ($maxbytes != -1 && filesize($downloadedfile['path']) > $maxbytes) {
287                     $maxbytesdisplay = display_size($maxbytes);
288                     throw new file_exception('maxbytesfile', (object) array('file' => $record->filename,
289                                                                             'size' => $maxbytesdisplay));
290                 }
292                 // Check if we exceed the max bytes of the area.
293                 if (file_is_draft_area_limit_reached($itemid, $areamaxbytes, filesize($downloadedfile['path']))) {
294                     throw new file_exception('maxareabytes');
295                 }
297                 $info = repository::move_to_filepool($downloadedfile['path'], $record);
298                 if (empty($info)) {
299                     $info['e'] = get_string('error', 'moodle');
300                 }
301             }
302             ajax_check_captured_output();
303             echo json_encode($info);
304             die;
305         }
306         break;
307     case 'upload':
308         $result = $repo->upload($saveas_filename, $maxbytes);
309         ajax_check_captured_output();
310         echo json_encode($result);
311         break;
313     case 'overwrite':
314         // existing file
315         $filepath    = required_param('existingfilepath', PARAM_PATH);
316         $filename    = required_param('existingfilename', PARAM_FILE);
317         // user added file which needs to replace the existing file
318         $newfilepath = required_param('newfilepath', PARAM_PATH);
319         $newfilename = required_param('newfilename', PARAM_FILE);
321         $info = repository::overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename);
322         ajax_check_captured_output();
323         echo json_encode($info);
324         break;
326     case 'deletetmpfile':
327         // delete tmp file
328         $newfilepath = required_param('newfilepath', PARAM_PATH);
329         $newfilename = required_param('newfilename', PARAM_FILE);
330         ajax_check_captured_output();
331         echo json_encode(repository::delete_tempfile_from_draft($itemid, $newfilepath, $newfilename));
333         break;