MDL-47868 ws: verify upload areas
[moodle.git] / webservice / upload.php
CommitLineData
42b2809f
DC
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/>.
16
a0a07014 17
42b2809f 18/**
f25aee32 19 * Accept uploading files by web service token
bba1338a 20 *
f25aee32
JM
21 * POST params:
22 * token => the web service user token (needed for authentication)
23 * filepath => the private file aera path (where files will be stored)
24 * [_FILES] => for example you can send the files with <input type=file>,
25 * or with curl magic: 'file_1' => '@/path/to/file', or ...
106c55fb
DW
26 * filearea => 'private' or 'draft' (default = 'private'). These are the only 2 areas we are allowing
27 * direct uploads via webservices. The private file area is deprecated - please don't use it.
28 * itemid => For draft areas this is the draftid - this can be used to add a list of files
29 * to a draft area in separate requests. If it is 0, a new draftid will be generated.
30 * For private files, this is ignored.
bba1338a 31 *
a0a07014 32 * @package core_webservice
42b2809f
DC
33 * @copyright 2011 Dongsheng Cai <dongsheng@moodle.com>
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 */
36
a0a07014
JM
37/**
38 * AJAX_SCRIPT - exception will be converted into JSON
39 */
42b2809f 40define('AJAX_SCRIPT', true);
a0a07014
JM
41
42/**
43 * NO_MOODLE_COOKIES - we don't want any cookie
44 */
42b2809f 45define('NO_MOODLE_COOKIES', true);
a0a07014 46
42b2809f 47require_once(dirname(dirname(__FILE__)) . '/config.php');
07cc3d11 48require_once($CFG->dirroot . '/webservice/lib.php');
42b2809f 49$filepath = optional_param('filepath', '/', PARAM_PATH);
106c55fb
DW
50// The default file area is 'private' for user private files. This
51// area is actually deprecated and only supported for backwards compatibility with
52// the mobile app.
53$filearea = optional_param('filearea', 'private', PARAM_ALPHA);
54$itemid = optional_param('itemid', 0, PARAM_INT);
42b2809f
DC
55
56echo $OUTPUT->header();
57
a0a07014 58// authenticate the user
07cc3d11
JM
59$token = required_param('token', PARAM_ALPHANUM);
60$webservicelib = new webservice();
61$authenticationinfo = $webservicelib->authenticate_user($token);
106c55fb
DW
62$fileuploaddisabled = empty($authenticationinfo['service']->uploadfiles);
63if ($fileuploaddisabled) {
64 throw new webservice_access_exception('Web service file upload must be enabled in external service settings');
65}
42b2809f 66
a0a07014 67// check the user can manage his own files (can upload)
43731030 68$context = context_user::instance($USER->id);
42b2809f
DC
69require_capability('moodle/user:manageownfiles', $context);
70
76ae1f60
PS
71if ($filearea !== 'private' and $filearea !== 'draft') {
72 // Do not dare to allow more areas here!
73 throw new file_exception('error');
74}
75
42b2809f
DC
76$fs = get_file_storage();
77
7515e1ba
DC
78$totalsize = 0;
79$files = array();
80foreach ($_FILES as $fieldname=>$uploaded_file) {
42b2809f
DC
81 // check upload errors
82 if (!empty($_FILES[$fieldname]['error'])) {
83 switch ($_FILES[$fieldname]['error']) {
84 case UPLOAD_ERR_INI_SIZE:
85 throw new moodle_exception('upload_error_ini_size', 'repository_upload');
86 break;
87 case UPLOAD_ERR_FORM_SIZE:
88 throw new moodle_exception('upload_error_form_size', 'repository_upload');
89 break;
90 case UPLOAD_ERR_PARTIAL:
91 throw new moodle_exception('upload_error_partial', 'repository_upload');
92 break;
93 case UPLOAD_ERR_NO_FILE:
94 throw new moodle_exception('upload_error_no_file', 'repository_upload');
95 break;
96 case UPLOAD_ERR_NO_TMP_DIR:
97 throw new moodle_exception('upload_error_no_tmp_dir', 'repository_upload');
98 break;
99 case UPLOAD_ERR_CANT_WRITE:
100 throw new moodle_exception('upload_error_cant_write', 'repository_upload');
101 break;
102 case UPLOAD_ERR_EXTENSION:
103 throw new moodle_exception('upload_error_extension', 'repository_upload');
104 break;
105 default:
106 throw new moodle_exception('nofile');
107 }
108 }
7515e1ba
DC
109 $file = new stdClass();
110 $file->filename = clean_param($_FILES[$fieldname]['name'], PARAM_FILE);
111 // check system maxbytes setting
3b40f3b1 112 if (($_FILES[$fieldname]['size'] > get_max_upload_file_size($CFG->maxbytes))) {
7515e1ba
DC
113 // oversize file will be ignored, error added to array to notify
114 // web service client
3b40f3b1 115 $file->errortype = 'fileoversized';
7515e1ba
DC
116 $file->error = get_string('maxbytes', 'error');
117 } else {
118 $file->filepath = $_FILES[$fieldname]['tmp_name'];
119 // calculate total size of upload
120 $totalsize += $_FILES[$fieldname]['size'];
121 }
122 $files[] = $file;
123}
124
125$fs = get_file_storage();
126
106c55fb
DW
127if ($filearea == 'draft' && $itemid <= 0) {
128 $itemid = file_get_unused_draft_itemid();
129}
130
131// Get any existing file size limits.
132$maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
133$maxupload = get_user_max_upload_file_size($context, $CFG->maxbytes);
134if ($filearea == 'private') {
135 // Private files area is limited by $CFG->userquota.
136 if (!has_capability('moodle/user:ignoreuserquota', $context)) {
137 $maxareabytes = $CFG->userquota;
138 }
106c55fb 139
1495f289
DW
140 // Count the size of all existing files in this area.
141 if ($maxareabytes > 0) {
142 $usedspace = 0;
143 $existingfiles = $fs->get_area_files($context->id, 'user', $filearea, false, 'id', false);
144 foreach ($existingfiles as $file) {
145 $usedspace += $file->get_filesize();
146 }
147 if ($totalsize > ($maxareabytes - $usedspace)) {
148 throw new file_exception('userquotalimit');
149 }
106c55fb 150 }
7515e1ba
DC
151}
152
106c55fb
DW
153// Check the size of this upload.
154if ($maxupload !== USER_CAN_IGNORE_FILE_SIZE_LIMITS && $totalsize > $maxupload) {
7515e1ba
DC
155 throw new file_exception('userquotalimit');
156}
157
158$results = array();
159foreach ($files as $file) {
160 if (!empty($file->error)) {
161 // including error and filename
162 $results[] = $file;
163 continue;
164 }
42b2809f
DC
165 $file_record = new stdClass;
166 $file_record->component = 'user';
167 $file_record->contextid = $context->id;
168 $file_record->userid = $USER->id;
106c55fb 169 $file_record->filearea = $filearea;
7515e1ba 170 $file_record->filename = $file->filename;
42b2809f 171 $file_record->filepath = $filepath;
106c55fb 172 $file_record->itemid = $itemid;
42b2809f 173 $file_record->license = $CFG->sitedefaultlicense;
0e35ba6f 174 $file_record->author = fullname($authenticationinfo['user']);
42b2809f 175 $file_record->source = '';
bba1338a 176
f25aee32 177 //Check if the file already exist
bba1338a 178 $existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea,
f25aee32
JM
179 $file_record->itemid, $file_record->filepath, $file_record->filename);
180 if ($existingfile) {
3b40f3b1
JM
181 $file->errortype = 'filenameexist';
182 $file->error = get_string('filenameexist', 'webservice', $file->filename);
183 $results[] = $file;
264764e2
JM
184 } else {
185 $stored_file = $fs->create_file_from_pathname($file_record, $file->filepath);
186 $results[] = $file_record;
f25aee32 187 }
42b2809f 188}
7515e1ba 189echo json_encode($results);