forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
repository_ajax.php
354 lines (313 loc) · 15.3 KB
/
repository_ajax.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* The Web service script that is called from the filepicker front end
*
* @since Moodle 2.0
* @package repository
* @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('AJAX_SCRIPT', true);
require_once(__DIR__ . '/../config.php');
require_once(__DIR__ . '/../lib/filelib.php');
require_once(__DIR__.'/lib.php');
$err = new stdClass();
// Parameters
$action = optional_param('action', '', PARAM_ALPHA);
$repo_id = optional_param('repo_id', 0, PARAM_INT); // Repository ID
$contextid = optional_param('ctx_id', SYSCONTEXTID, PARAM_INT); // Context ID
$env = optional_param('env', 'filepicker', PARAM_ALPHA); // Opened in editor or moodleform
$license = optional_param('license', $CFG->sitedefaultlicense, PARAM_TEXT);
$author = optional_param('author', '', PARAM_TEXT); // File author
$source = optional_param('source', '', PARAM_RAW); // File to download
$sourcekey = optional_param('sourcekey', '', PARAM_RAW); // Used to verify the source.
$itemid = optional_param('itemid', 0, PARAM_INT); // Itemid
$page = optional_param('page', '', PARAM_RAW); // Page
$maxbytes = optional_param('maxbytes', 0, PARAM_INT); // Maxbytes
$req_path = optional_param('p', '', PARAM_RAW); // Path
$accepted_types = optional_param_array('accepted_types', '*', PARAM_RAW);
$saveas_filename = optional_param('title', '', PARAM_FILE); // save as file name
$areamaxbytes = optional_param('areamaxbytes', FILE_AREA_MAX_BYTES_UNLIMITED, PARAM_INT); // Area max bytes.
$saveas_path = optional_param('savepath', '/', PARAM_PATH); // save as file path
$search_text = optional_param('s', '', PARAM_CLEANHTML);
$linkexternal = optional_param('linkexternal', '', PARAM_ALPHA);
$usefilereference = optional_param('usefilereference', false, PARAM_BOOL);
$usecontrolledlink = optional_param('usecontrolledlink', false, PARAM_BOOL);
list($context, $course, $cm) = get_context_info_array($contextid);
require_login($course, false, $cm, false, true);
$PAGE->set_context($context);
echo $OUTPUT->header(); // send headers
// If uploaded file is larger than post_max_size (php.ini) setting, $_POST content will be empty.
if (empty($_POST) && !empty($action)) {
$err->error = get_string('errorpostmaxsize', 'repository');
die(json_encode($err));
}
if (!confirm_sesskey()) {
$err->error = get_string('invalidsesskey', 'error');
die(json_encode($err));
}
// Get repository instance information
$repooptions = array(
'ajax' => true,
'mimetypes' => $accepted_types
);
ajax_capture_output();
$repo = repository::get_repository_by_id($repo_id, $contextid, $repooptions);
// Check permissions
$repo->check_capability();
$coursemaxbytes = 0;
if (!empty($course)) {
$coursemaxbytes = $course->maxbytes;
}
// Make sure maxbytes passed is within site filesize limits.
$maxbytes = get_user_max_upload_file_size($context, $CFG->maxbytes, $coursemaxbytes, $maxbytes);
// Wait as long as it takes for this script to finish
core_php_time_limit::raise();
// These actions all occur on the currently active repository instance
switch ($action) {
case 'sign':
case 'signin':
case 'list':
if ($repo->check_login()) {
$listing = repository::prepare_listing($repo->get_listing($req_path, $page));
$listing['repo_id'] = $repo_id;
ajax_check_captured_output();
echo json_encode($listing);
break;
} else {
$action = 'login';
}
case 'login':
$listing = $repo->print_login();
$listing['repo_id'] = $repo_id;
ajax_check_captured_output();
echo json_encode($listing);
break;
case 'logout':
$logout = $repo->logout();
$logout['repo_id'] = $repo_id;
ajax_check_captured_output();
echo json_encode($logout);
break;
case 'searchform':
$search_form['repo_id'] = $repo_id;
$search_form['form'] = $repo->print_search();
$search_form['allowcaching'] = true;
ajax_check_captured_output();
echo json_encode($search_form);
break;
case 'search':
$search_result = repository::prepare_listing($repo->search($search_text, (int)$page));
$search_result['repo_id'] = $repo_id;
$search_result['issearchresult'] = true;
ajax_check_captured_output();
echo json_encode($search_result);
break;
case 'download':
// validate mimetype
$mimetypes = array();
if ((is_array($accepted_types) and in_array('*', $accepted_types)) or $accepted_types == '*') {
$mimetypes = '*';
} else {
foreach ($accepted_types as $type) {
$mimetypes[] = mimeinfo('type', $type);
}
if (!in_array(mimeinfo('type', $saveas_filename), $mimetypes)) {
throw new moodle_exception('invalidfiletype', 'repository', '', get_mimetype_description(array('filename' => $saveas_filename)));
}
}
// We have two special repository type need to deal with
// local and recent plugins don't added new files to moodle, just add new records to database
// so we don't check user quota and maxbytes here
$allowexternallink = (int)get_config(null, 'repositoryallowexternallinks');
if (!empty($allowexternallink)) {
$allowexternallink = true;
} else {
$allowexternallink = false;
}
// allow external links in url element all the time
$allowexternallink = ($allowexternallink || ($env == 'url'));
// Validate the sourcekey.
if (empty($sourcekey)) {
throw new moodle_exception('missingsourcekey', 'repository');
}
// Check that the sourcekey matches.
if (sha1($source . repository::get_secret_key() . sesskey()) !== $sourcekey) {
throw new moodle_exception('sourcekeymismatch', 'repository');
}
$reference = $repo->get_file_reference($source);
// Use link of the files
if ($allowexternallink and $linkexternal === 'yes' and ($repo->supported_returntypes() & FILE_EXTERNAL)) {
// use external link
$link = $repo->get_link($reference);
$info = array();
$info['file'] = $saveas_filename;
$info['type'] = 'link';
$info['url'] = $link;
ajax_check_captured_output();
echo json_encode($info);
die;
} else {
$fs = get_file_storage();
// Prepare file record.
$record = new stdClass();
$record->filepath = $saveas_path;
$record->filename = $saveas_filename;
$record->component = 'user';
$record->filearea = 'draft';
$record->itemid = $itemid;
$record->license = $license;
$record->author = $author;
if ($record->filepath !== '/') {
$record->filepath = trim($record->filepath, '/');
$record->filepath = '/'.$record->filepath.'/';
}
$usercontext = context_user::instance($USER->id);
$now = time();
$record->contextid = $usercontext->id;
$record->timecreated = $now;
$record->timemodified = $now;
$record->userid = $USER->id;
$record->sortorder = 0;
// Check that user has permission to access this file
if (!$repo->file_is_accessible($source)) {
throw new file_exception('storedfilecannotread');
}
// {@link repository::build_source_field()}
$sourcefield = $repo->get_file_source_info($source);
$record->source = $repo::build_source_field($sourcefield);
// If file is already a reference, set $source = file source, $repo = file repository
// note that in this case user may not have permission to access the source file directly
// so no file_browser/file_info can be used below
if ($repo->has_moodle_files()) {
$file = repository::get_moodle_file($reference);
if ($file && $file->is_external_file()) {
$sourcefield = $file->get_source(); // remember the original source
$record->source = $repo::build_source_field($sourcefield);
$record->contenthash = $file->get_contenthash();
$record->filesize = $file->get_filesize();
$reference = $file->get_reference();
$repo_id = $file->get_repository_id();
$repo = repository::get_repository_by_id($repo_id, $contextid, $repooptions);
}
}
if ($usefilereference || $usecontrolledlink) {
if ($repo->has_moodle_files()) {
$sourcefile = repository::get_moodle_file($reference);
$record->contenthash = $sourcefile->get_contenthash();
$record->filesize = $sourcefile->get_filesize();
}
// Check if file exists.
if (repository::draftfile_exists($itemid, $saveas_path, $saveas_filename)) {
// File name being used, rename it.
$unused_filename = repository::get_unused_filename($itemid, $saveas_path, $saveas_filename);
$record->filename = $unused_filename;
// Create a file copy using unused filename.
$storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
$event = array();
$event['event'] = 'fileexists';
$event['newfile'] = new stdClass;
$event['newfile']->filepath = $saveas_path;
$event['newfile']->filename = $unused_filename;
$event['newfile']->url = moodle_url::make_draftfile_url($itemid, $saveas_path, $unused_filename)->out();
$event['existingfile'] = new stdClass;
$event['existingfile']->filepath = $saveas_path;
$event['existingfile']->filename = $saveas_filename;
$event['existingfile']->url = moodle_url::make_draftfile_url($itemid, $saveas_path, $saveas_filename)->out();
} else {
$storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
$event = array(
'url'=>moodle_url::make_draftfile_url($storedfile->get_itemid(), $storedfile->get_filepath(), $storedfile->get_filename())->out(),
'id'=>$storedfile->get_itemid(),
'file'=>$storedfile->get_filename(),
'icon' => $OUTPUT->image_url(file_file_icon($storedfile))->out(),
);
}
// Repository plugin callback
// You can cache reository file in this callback
// or complete other tasks.
$repo->cache_file_by_reference($reference, $storedfile);
ajax_check_captured_output();
echo json_encode($event);
die;
} else if ($repo->has_moodle_files()) {
// Some repository plugins (local, user, coursefiles, recent) are hosting moodle
// internal files, we cannot use get_file method, so we use copy_to_area method
// If the moodle file is an alias we copy this alias, otherwise we copy the file
// {@link repository::copy_to_area()}.
$fileinfo = $repo->copy_to_area($reference, $record, $maxbytes, $areamaxbytes);
ajax_check_captured_output();
echo json_encode($fileinfo);
die;
} else {
// Download file to moodle.
$downloadedfile = $repo->get_file($reference, $saveas_filename);
if (!empty($downloadedfile['newfilename'])) {
$record->filename = $downloadedfile['newfilename'];
}
if (empty($downloadedfile['path'])) {
$err->error = get_string('cannotdownload', 'repository');
die(json_encode($err));
}
// Check if exceed maxbytes.
if ($maxbytes != -1 && filesize($downloadedfile['path']) > $maxbytes) {
$maxbytesdisplay = display_size($maxbytes, 0);
throw new file_exception('maxbytesfile', (object) array('file' => $record->filename,
'size' => $maxbytesdisplay));
}
// Check if we exceed the max bytes of the area.
if (file_is_draft_area_limit_reached($itemid, $areamaxbytes, filesize($downloadedfile['path']))) {
throw new file_exception('maxareabytes');
}
// Ensure the user does not upload too many draft files in a short period.
if (file_is_draft_areas_limit_reached($USER->id)) {
throw new file_exception('maxdraftitemids');
}
$info = repository::move_to_filepool($downloadedfile['path'], $record);
if (empty($info)) {
$info['e'] = get_string('error', 'moodle');
}
}
ajax_check_captured_output();
echo json_encode($info);
die;
}
break;
case 'upload':
$result = $repo->upload($saveas_filename, $maxbytes);
ajax_check_captured_output();
echo json_encode($result);
break;
case 'overwrite':
// existing file
$filepath = required_param('existingfilepath', PARAM_PATH);
$filename = required_param('existingfilename', PARAM_FILE);
// user added file which needs to replace the existing file
$newfilepath = required_param('newfilepath', PARAM_PATH);
$newfilename = required_param('newfilename', PARAM_FILE);
$info = repository::overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename);
ajax_check_captured_output();
echo json_encode($info);
break;
case 'deletetmpfile':
// delete tmp file
$newfilepath = required_param('newfilepath', PARAM_PATH);
$newfilename = required_param('newfilename', PARAM_FILE);
ajax_check_captured_output();
echo json_encode(repository::delete_tempfile_from_draft($itemid, $newfilepath, $newfilename));
break;
}