Followup r70461 if PARAM_REQUIRED is set, use for missing param in getPossibleErrors...
[lhc/web/wiklou.git] / includes / api / ApiUpload.php
1 <?php
2 /**
3 * Created on Aug 21, 2008
4 * API for MediaWiki 1.8+
5 *
6 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 */
23
24 if ( !defined( 'MEDIAWIKI' ) ) {
25 // Eclipse helper - will be ignored in production
26 require_once( "ApiBase.php" );
27 }
28
29 /**
30 * @ingroup API
31 */
32 class ApiUpload extends ApiBase {
33 protected $mUpload = null;
34 protected $mParams;
35
36 public function __construct( $main, $action ) {
37 parent::__construct( $main, $action );
38 }
39
40 public function execute() {
41 global $wgUser;
42
43 // Check whether upload is enabled
44 if ( !UploadBase::isEnabled() ) {
45 $this->dieUsageMsg( array( 'uploaddisabled' ) );
46 }
47
48 // Parameter handling
49 $this->mParams = $this->extractRequestParams();
50 $request = $this->getMain()->getRequest();
51 // Add the uploaded file to the params array
52 $this->mParams['file'] = $request->getFileName( 'file' );
53
54 // Select an upload module
55 $this->selectUploadModule();
56 if ( !isset( $this->mUpload ) ) {
57 $this->dieUsage( 'No upload module set', 'nomodule' );
58 }
59
60 // First check permission to upload
61 $this->checkPermissions( $wgUser );
62
63 // Fetch the file
64 $status = $this->mUpload->fetchFile();
65 if ( !$status->isGood() ) {
66 $errors = $status->getErrorsArray();
67 $error = array_shift( $errors[0] );
68 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
69 }
70
71 // Check if the uploaded file is sane
72 $this->verifyUpload();
73
74 // Check permission to upload this file
75 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
76 if ( $permErrors !== true ) {
77 // Todo: stash the upload and allow choosing a new name
78 $this->dieUsageMsg( array( 'badaccess-groups' ) );
79 }
80
81 // Check warnings if necessary
82 $warnings = $this->checkForWarnings();
83 if ( $warnings ) {
84 $this->getResult()->addValue( null, $this->getModuleName(), $warnings );
85 } else {
86 // Perform the upload
87 $result = $this->performUpload();
88 $this->getResult()->addValue( null, $this->getModuleName(), $result );
89 }
90
91 // Cleanup any temporary mess
92 $this->mUpload->cleanupTempFile();
93 }
94
95 /**
96 * Select an upload module and set it to mUpload. Dies on failure.
97 */
98 protected function selectUploadModule() {
99 $request = $this->getMain()->getRequest();
100
101 // One and only one of the following parameters is needed
102 $this->requireOnlyOneParameter( $this->mParams,
103 'sessionkey', 'file', 'url' );
104
105 if ( $this->mParams['sessionkey'] ) {
106 // Upload stashed in a previous request
107 $sessionData = $request->getSessionData( UploadBase::getSessionKeyName() );
108 if ( !UploadFromStash::isValidSessionKey( $this->mParams['sessionkey'], $sessionData ) ) {
109 $this->dieUsageMsg( array( 'invalid-session-key' ) );
110 }
111
112 $this->mUpload = new UploadFromStash();
113 $this->mUpload->initialize( $this->mParams['filename'],
114 $this->mParams['sessionkey'],
115 $sessionData[$this->mParams['sessionkey']] );
116
117
118 } elseif ( isset( $this->mParams['file'] ) ) {
119 $this->mUpload = new UploadFromFile();
120 $this->mUpload->initialize(
121 $this->mParams['filename'],
122 $request->getUpload( 'file' )
123 );
124 } elseif ( isset( $this->mParams['url'] ) ) {
125 // Make sure upload by URL is enabled:
126 if ( !UploadFromUrl::isEnabled() ) {
127 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
128 }
129
130 $async = false;
131 if ( $this->mParams['asyncdownload'] ) {
132 if ( $this->mParams['leavemessage'] ) {
133 $async = 'async-leavemessage';
134 } else {
135 $async = 'async';
136 }
137 }
138 $this->mUpload = new UploadFromUrl;
139 $this->mUpload->initialize( $this->mParams['filename'],
140 $this->mParams['url'], $async );
141
142 }
143 }
144
145 /**
146 * Checks that the user has permissions to perform this upload.
147 * Dies with usage message on inadequate permissions.
148 * @param $user User The user to check.
149 */
150 protected function checkPermissions( $user ) {
151 // Check whether the user has the appropriate permissions to upload anyway
152 $permission = $this->mUpload->isAllowed( $user );
153
154 if ( $permission !== true ) {
155 if ( !$user->isLoggedIn() ) {
156 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
157 } else {
158 $this->dieUsageMsg( array( 'badaccess-groups' ) );
159 }
160 }
161 }
162
163 /**
164 * Performs file verification, dies on error.
165 */
166 protected function verifyUpload( ) {
167 $verification = $this->mUpload->verifyUpload( );
168 if ( $verification['status'] === UploadBase::OK ) {
169 return;
170 }
171
172 // TODO: Move them to ApiBase's message map
173 switch( $verification['status'] ) {
174 case UploadBase::EMPTY_FILE:
175 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
176 break;
177 case UploadBase::FILE_TOO_LARGE:
178 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
179 break;
180 case UploadBase::FILETYPE_MISSING:
181 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
182 break;
183 case UploadBase::FILETYPE_BADTYPE:
184 global $wgFileExtensions;
185 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
186 0, array(
187 'filetype' => $verification['finalExt'],
188 'allowed' => $wgFileExtensions
189 ) );
190 break;
191 case UploadBase::MIN_LENGTH_PARTNAME:
192 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
193 break;
194 case UploadBase::ILLEGAL_FILENAME:
195 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
196 0, array( 'filename' => $verification['filtered'] ) );
197 break;
198 case UploadBase::VERIFICATION_ERROR:
199 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
200 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
201 0, array( 'details' => $verification['details'] ) );
202 break;
203 case UploadBase::HOOK_ABORTED:
204 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
205 'hookaborted', 0, array( 'error' => $verification['error'] ) );
206 break;
207 default:
208 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
209 0, array( 'code' => $verification['status'] ) );
210 break;
211 }
212 }
213
214 /**
215 * Check warnings if ignorewarnings is not set.
216 * Returns a suitable result array if there were warnings
217 */
218 protected function checkForWarnings() {
219 $result = array();
220
221 if ( !$this->mParams['ignorewarnings'] ) {
222 $warnings = $this->mUpload->checkWarnings();
223 if ( $warnings ) {
224 // Add indices
225 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
226
227 if ( isset( $warnings['duplicate'] ) ) {
228 $dupes = array();
229 foreach ( $warnings['duplicate'] as $key => $dupe )
230 $dupes[] = $dupe->getName();
231 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
232 $warnings['duplicate'] = $dupes;
233 }
234
235 if ( isset( $warnings['exists'] ) ) {
236 $warning = $warnings['exists'];
237 unset( $warnings['exists'] );
238 $warnings[$warning['warning']] = $warning['file']->getName();
239 }
240
241 $result['result'] = 'Warning';
242 $result['warnings'] = $warnings;
243
244 $sessionKey = $this->mUpload->stashSession();
245 if ( !$sessionKey ) {
246 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
247 }
248
249 $result['sessionkey'] = $sessionKey;
250
251 return $result;
252 }
253 }
254 return;
255 }
256
257 /**
258 * Perform the actual upload. Returns a suitable result array on success;
259 * dies on failure.
260 */
261 protected function performUpload() {
262 global $wgUser;
263
264 // Use comment as initial page text by default
265 if ( is_null( $this->mParams['text'] ) ) {
266 $this->mParams['text'] = $this->mParams['comment'];
267 }
268
269 $file = $this->mUpload->getLocalFile();
270 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
271
272 // Deprecated parameters
273 if ( $this->mParams['watch'] ) {
274 $watch = true;
275 }
276
277 // No errors, no warnings: do the upload
278 $status = $this->mUpload->performUpload( $this->mParams['comment'],
279 $this->mParams['text'], $watch, $wgUser );
280
281 if ( !$status->isGood() ) {
282 $error = $status->getErrorsArray();
283
284 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
285 // The upload can not be performed right now, because the user
286 // requested so
287 return array(
288 'result' => 'Queued',
289 'sessionkey' => $error[0][1],
290 );
291 } else {
292 $this->getResult()->setIndexedTagName( $error, 'error' );
293
294 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
295 }
296 }
297
298 $file = $this->mUpload->getLocalFile();
299
300 $result['result'] = 'Success';
301 $result['filename'] = $file->getName();
302 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
303
304 return $result;
305 }
306
307 public function mustBePosted() {
308 return true;
309 }
310
311 public function isWriteMode() {
312 return true;
313 }
314
315 public function getAllowedParams() {
316 $params = array(
317 'filename' => array(
318 ApiBase::PARAM_TYPE => 'string',
319 ApiBase::PARAM_REQUIRED => true
320 ),
321 'comment' => array(
322 ApiBase::PARAM_DFLT => ''
323 ),
324 'text' => null,
325 'token' => null,
326 'watch' => array(
327 ApiBase::PARAM_DFLT => false,
328 ApiBase::PARAM_DEPRECATED => true,
329 ),
330 'watchlist' => array(
331 ApiBase::PARAM_DFLT => 'preferences',
332 ApiBase::PARAM_TYPE => array(
333 'watch',
334 'preferences',
335 'nochange'
336 ),
337 ),
338 'ignorewarnings' => false,
339 'file' => null,
340 'url' => null,
341
342 'sessionkey' => null,
343 );
344
345 global $wgAllowAsyncCopyUploads;
346 if ( $wgAllowAsyncCopyUploads ) {
347 $params += array(
348 'asyncdownload' => false,
349 'leavemessage' => false,
350 );
351 }
352 return $params;
353 }
354
355 public function getParamDescription() {
356 $params = array(
357 'filename' => 'Target filename',
358 'token' => 'Edit token. You can get one of these through prop=info',
359 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
360 'text' => 'Initial page text for new files',
361 'watch' => 'Watch the page',
362 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
363 'ignorewarnings' => 'Ignore any warnings',
364 'file' => 'File contents',
365 'url' => 'Url to fetch the file from',
366 'sessionkey' => 'Session key returned by a previous upload that failed due to warnings',
367 );
368
369 global $wgAllowAsyncCopyUploads;
370 if ( $wgAllowAsyncCopyUploads ) {
371 $params += array(
372 'asyncdownload' => 'Make fetching a URL asynchronous',
373 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
374 );
375 }
376
377 return $params;
378
379 }
380
381 public function getDescription() {
382 return array(
383 'Upload a file, or get the status of pending uploads. Several methods are available:',
384 ' * Upload file contents directly, using the "file" parameter',
385 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
386 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
387 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
388 'sending the "file". Note also that queries using session keys must be',
389 'done in the same login session as the query that originally returned the key (i.e. do not',
390 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
391 );
392 }
393
394 public function getPossibleErrors() {
395 return array_merge( parent::getPossibleErrors(), array(
396 array( 'uploaddisabled' ),
397 array( 'invalid-session-key' ),
398 array( 'uploaddisabled' ),
399 array( 'badaccess-groups' ),
400 array( 'mustbeloggedin', 'upload' ),
401 array( 'badaccess-groups' ),
402 array( 'badaccess-groups' ),
403 array( 'code' => 'fetchfileerror', 'info' => '' ),
404 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
405 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
406 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
407 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
408 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
409 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
410 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
411 ) );
412 }
413
414 public function getTokenSalt() {
415 return '';
416 }
417
418 protected function getExamples() {
419 return array(
420 'Upload from a URL:',
421 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
422 'Complete an upload that failed due to warnings:',
423 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
424 );
425 }
426
427 public function getVersion() {
428 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';
429 }
430 }