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