Revert "(bug 30625) Add, to every API upload response, the warnings raised."
[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 /**
28 * @ingroup API
29 */
30 class ApiUpload extends ApiBase {
31
32 /**
33 * @var UploadBase
34 */
35 protected $mUpload = null;
36
37 protected $mParams;
38
39 public function __construct( $main, $action ) {
40 parent::__construct( $main, $action );
41 }
42
43 public function execute() {
44 // Check whether upload is enabled
45 if ( !UploadBase::isEnabled() ) {
46 $this->dieUsageMsg( 'uploaddisabled' );
47 }
48
49 $user = $this->getUser();
50
51 // Parameter handling
52 $this->mParams = $this->extractRequestParams();
53 $request = $this->getMain()->getRequest();
54 // Add the uploaded file to the params array
55 $this->mParams['file'] = $request->getFileName( 'file' );
56 $this->mParams['chunk'] = $request->getFileName( 'chunk' );
57
58 // Copy the session key to the file key, for backward compatibility.
59 if( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
60 $this->mParams['filekey'] = $this->mParams['sessionkey'];
61 }
62
63 // Select an upload module
64 if ( !$this->selectUploadModule() ) {
65 // This is not a true upload, but a status request or similar
66 return;
67 }
68 if ( !isset( $this->mUpload ) ) {
69 $this->dieUsage( 'No upload module set', 'nomodule' );
70 }
71
72 // First check permission to upload
73 $this->checkPermissions( $user );
74
75 // Fetch the file
76 $status = $this->mUpload->fetchFile();
77 if ( !$status->isGood() ) {
78 $errors = $status->getErrorsArray();
79 $error = array_shift( $errors[0] );
80 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
81 }
82
83 // Check if the uploaded file is sane
84 if ( $this->mParams['chunk'] ) {
85 $maxSize = $this->mUpload->getMaxUploadSize( );
86 if( $this->mParams['filesize'] > $maxSize ) {
87 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
88 }
89 } else {
90 $this->verifyUpload();
91 }
92
93 // Check if the user has the rights to modify or overwrite the requested title
94 // (This check is irrelevant if stashing is already requested, since the errors
95 // can always be fixed by changing the title)
96 if ( ! $this->mParams['stash'] ) {
97 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
98 if ( $permErrors !== true ) {
99 $this->dieRecoverableError( $permErrors[0], 'filename' );
100 }
101 }
102 // Get the result based on the current upload context:
103 $result = $this->getContextResult();
104
105 if ( $result['result'] === 'Success' ) {
106 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
107 }
108
109 $this->getResult()->addValue( null, $this->getModuleName(), $result );
110
111 // Cleanup any temporary mess
112 $this->mUpload->cleanupTempFile();
113 }
114 /**
115 * Get an uplaod result based on upload context
116 * @return array
117 */
118 private function getContextResult(){
119 $warnings = $this->getApiWarnings();
120 if ( $warnings ) {
121 // Get warnings formated in result array format
122 return $this->getWarningsResult( $warnings );
123 } elseif ( $this->mParams['chunk'] ) {
124 // Add chunk, and get result
125 return $this->getChunkResult();
126 } elseif ( $this->mParams['stash'] ) {
127 // Stash the file and get stash result
128 return $this->getStashResult();
129 }
130 // This is the most common case -- a normal upload with no warnings
131 // performUpload will return a formatted properly for the API with status
132 return $this->performUpload();
133 }
134 /**
135 * Get Stash Result, throws an expetion if the file could not be stashed.
136 * @return array
137 */
138 private function getStashResult(){
139 $result = array ();
140 // Some uploads can request they be stashed, so as not to publish them immediately.
141 // In this case, a failure to stash ought to be fatal
142 try {
143 $result['result'] = 'Success';
144 $result['filekey'] = $this->performStash();
145 $result['sessionkey'] = $result['filekey']; // backwards compatibility
146 } catch ( MWException $e ) {
147 $this->dieUsage( $e->getMessage(), 'stashfailed' );
148 }
149 return $result;
150 }
151 /**
152 * Get Warnings Result
153 * @param $warnings Array of Api upload warnings
154 * @return array
155 */
156 private function getWarningsResult( $warnings ){
157 $result = array();
158 $result['result'] = 'Warning';
159 $result['warnings'] = $warnings;
160 // in case the warnings can be fixed with some further user action, let's stash this upload
161 // and return a key they can use to restart it
162 try {
163 $result['filekey'] = $this->performStash();
164 $result['sessionkey'] = $result['filekey']; // backwards compatibility
165 } catch ( MWException $e ) {
166 $result['warnings']['stashfailed'] = $e->getMessage();
167 }
168 return $result;
169 }
170 /**
171 * Get the result of a chunk upload.
172 * @return array
173 */
174 private function getChunkResult(){
175 $result = array();
176
177 $result['result'] = 'Continue';
178 $request = $this->getMain()->getRequest();
179 $chunkPath = $request->getFileTempname( 'chunk' );
180 $chunkSize = $request->getUpload( 'chunk' )->getSize();
181 if ($this->mParams['offset'] == 0) {
182 $result['filekey'] = $this->performStash();
183 } else {
184 $status = $this->mUpload->addChunk($chunkPath, $chunkSize,
185 $this->mParams['offset']);
186 if ( !$status->isGood() ) {
187 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
188 return array();
189 }
190
191 // Check we added the last chunk:
192 if( $this->mParams['offset'] + $chunkSize == $this->mParams['filesize'] ) {
193 $status = $this->mUpload->concatenateChunks();
194
195 if ( !$status->isGood() ) {
196 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
197 return array();
198 }
199
200 // We have a new filekey for the fully concatenated file.
201 $result['filekey'] = $this->mUpload->getLocalFile()->getFileKey();
202
203 // Remove chunk from stash. (Checks against user ownership of chunks.)
204 $this->mUpload->stash->removeFile( $this->mParams['filekey'] );
205
206 $result['result'] = 'Success';
207
208 } else {
209
210 // Continue passing through the filekey for adding further chunks.
211 $result['filekey'] = $this->mParams['filekey'];
212 }
213 }
214 $result['offset'] = $this->mParams['offset'] + $chunkSize;
215 return $result;
216 }
217
218 /**
219 * Stash the file and return the file key
220 * Also re-raises exceptions with slightly more informative message strings (useful for API)
221 * @throws MWException
222 * @return String file key
223 */
224 function performStash() {
225 try {
226 $stashFile = $this->mUpload->stashFile();
227
228 if ( !$stashFile ) {
229 throw new MWException( 'Invalid stashed file' );
230 }
231 $fileKey = $stashFile->getFileKey();
232 } catch ( MWException $e ) {
233 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
234 wfDebug( __METHOD__ . ' ' . $message . "\n");
235 throw new MWException( $message );
236 }
237 return $fileKey;
238 }
239
240 /**
241 * Throw an error that the user can recover from by providing a better
242 * value for $parameter
243 *
244 * @param $error array Error array suitable for passing to dieUsageMsg()
245 * @param $parameter string Parameter that needs revising
246 * @param $data array Optional extra data to pass to the user
247 * @throws UsageException
248 */
249 function dieRecoverableError( $error, $parameter, $data = array() ) {
250 try {
251 $data['filekey'] = $this->performStash();
252 $data['sessionkey'] = $data['filekey'];
253 } catch ( MWException $e ) {
254 $data['stashfailed'] = $e->getMessage();
255 }
256 $data['invalidparameter'] = $parameter;
257
258 $parsed = $this->parseMsg( $error );
259 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
260 }
261
262 /**
263 * Select an upload module and set it to mUpload. Dies on failure. If the
264 * request was a status request and not a true upload, returns false;
265 * otherwise true
266 *
267 * @return bool
268 */
269 protected function selectUploadModule() {
270 $request = $this->getMain()->getRequest();
271
272 // chunk or one and only one of the following parameters is needed
273 if( !$this->mParams['chunk'] ) {
274 $this->requireOnlyOneParameter( $this->mParams,
275 'filekey', 'file', 'url', 'statuskey' );
276 }
277
278 if ( $this->mParams['statuskey'] ) {
279 $this->checkAsyncDownloadEnabled();
280
281 // Status request for an async upload
282 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
283 if ( !isset( $sessionData['result'] ) ) {
284 $this->dieUsage( 'No result in session data', 'missingresult' );
285 }
286 if ( $sessionData['result'] == 'Warning' ) {
287 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
288 $sessionData['sessionkey'] = $this->mParams['statuskey'];
289 }
290 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
291 return false;
292
293 }
294
295 // The following modules all require the filename parameter to be set
296 if ( is_null( $this->mParams['filename'] ) ) {
297 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
298 }
299
300 if ( $this->mParams['chunk'] ) {
301 // Chunk upload
302 $this->mUpload = new UploadFromChunks();
303 if( isset( $this->mParams['filekey'] ) ){
304 // handle new chunk
305 $this->mUpload->continueChunks(
306 $this->mParams['filename'],
307 $this->mParams['filekey'],
308 $request->getUpload( 'chunk' )
309 );
310 } else {
311 // handle first chunk
312 $this->mUpload->initialize(
313 $this->mParams['filename'],
314 $request->getUpload( 'chunk' )
315 );
316 }
317 } elseif ( isset( $this->mParams['filekey'] ) ) {
318 // Upload stashed in a previous request
319 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
320 $this->dieUsageMsg( 'invalid-file-key' );
321 }
322
323 $this->mUpload = new UploadFromStash( $this->getUser() );
324
325 $this->mUpload->initialize( $this->mParams['filekey'], $this->mParams['filename'] );
326 } elseif ( isset( $this->mParams['file'] ) ) {
327 $this->mUpload = new UploadFromFile();
328 $this->mUpload->initialize(
329 $this->mParams['filename'],
330 $request->getUpload( 'file' )
331 );
332 } elseif ( isset( $this->mParams['url'] ) ) {
333 // Make sure upload by URL is enabled:
334 if ( !UploadFromUrl::isEnabled() ) {
335 $this->dieUsageMsg( 'copyuploaddisabled' );
336 }
337
338 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
339 $this->dieUsageMsg( 'copyuploadbaddomain' );
340 }
341
342 $async = false;
343 if ( $this->mParams['asyncdownload'] ) {
344 $this->checkAsyncDownloadEnabled();
345
346 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
347 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
348 'missing-ignorewarnings' );
349 }
350
351 if ( $this->mParams['leavemessage'] ) {
352 $async = 'async-leavemessage';
353 } else {
354 $async = 'async';
355 }
356 }
357 $this->mUpload = new UploadFromUrl;
358 $this->mUpload->initialize( $this->mParams['filename'],
359 $this->mParams['url'], $async );
360 }
361
362 return true;
363 }
364
365 /**
366 * Checks that the user has permissions to perform this upload.
367 * Dies with usage message on inadequate permissions.
368 * @param $user User The user to check.
369 */
370 protected function checkPermissions( $user ) {
371 // Check whether the user has the appropriate permissions to upload anyway
372 $permission = $this->mUpload->isAllowed( $user );
373
374 if ( $permission !== true ) {
375 if ( !$user->isLoggedIn() ) {
376 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
377 } else {
378 $this->dieUsageMsg( 'badaccess-groups' );
379 }
380 }
381 }
382
383 /**
384 * Performs file verification, dies on error.
385 */
386 protected function verifyUpload( ) {
387 global $wgFileExtensions;
388
389 $verification = $this->mUpload->verifyUpload( );
390 if ( $verification['status'] === UploadBase::OK ) {
391 return;
392 }
393
394 // TODO: Move them to ApiBase's message map
395 switch( $verification['status'] ) {
396 // Recoverable errors
397 case UploadBase::MIN_LENGTH_PARTNAME:
398 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
399 break;
400 case UploadBase::ILLEGAL_FILENAME:
401 $this->dieRecoverableError( 'illegal-filename', 'filename',
402 array( 'filename' => $verification['filtered'] ) );
403 break;
404 case UploadBase::FILENAME_TOO_LONG:
405 $this->dieRecoverableError( 'filename-toolong', 'filename' );
406 break;
407 case UploadBase::FILETYPE_MISSING:
408 $this->dieRecoverableError( 'filetype-missing', 'filename' );
409 break;
410 case UploadBase::WINDOWS_NONASCII_FILENAME:
411 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
412 break;
413
414 // Unrecoverable errors
415 case UploadBase::EMPTY_FILE:
416 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
417 break;
418 case UploadBase::FILE_TOO_LARGE:
419 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
420 break;
421
422 case UploadBase::FILETYPE_BADTYPE:
423 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
424 0, array(
425 'filetype' => $verification['finalExt'],
426 'allowed' => $wgFileExtensions
427 ) );
428 break;
429 case UploadBase::VERIFICATION_ERROR:
430 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
431 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
432 0, array( 'details' => $verification['details'] ) );
433 break;
434 case UploadBase::HOOK_ABORTED:
435 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
436 'hookaborted', 0, array( 'error' => $verification['error'] ) );
437 break;
438 default:
439 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
440 0, array( 'code' => $verification['status'] ) );
441 break;
442 }
443 }
444
445
446 /**
447 * Check warnings if ignorewarnings is not set.
448 * Returns a suitable array for inclusion into API results if there were warnings
449 * Returns the empty array if there were no warnings
450 *
451 * @return array
452 */
453 protected function getApiWarnings() {
454 $warnings = array();
455
456 if ( !$this->mParams['ignorewarnings'] ) {
457 $warnings = $this->mUpload->checkWarnings();
458 }
459 return $this->transformWarnings( $warnings );
460 }
461
462 protected function transformWarnings( $warnings ) {
463 if ( $warnings ) {
464 // Add indices
465 $result = $this->getResult();
466 $result->setIndexedTagName( $warnings, 'warning' );
467
468 if ( isset( $warnings['duplicate'] ) ) {
469 $dupes = array();
470 foreach ( $warnings['duplicate'] as $dupe ) {
471 $dupes[] = $dupe->getName();
472 }
473 $result->setIndexedTagName( $dupes, 'duplicate' );
474 $warnings['duplicate'] = $dupes;
475 }
476
477 if ( isset( $warnings['exists'] ) ) {
478 $warning = $warnings['exists'];
479 unset( $warnings['exists'] );
480 $warnings[$warning['warning']] = $warning['file']->getName();
481 }
482 }
483 return $warnings;
484 }
485
486
487 /**
488 * Perform the actual upload. Returns a suitable result array on success;
489 * dies on failure.
490 *
491 * @return array
492 */
493 protected function performUpload() {
494 // Use comment as initial page text by default
495 if ( is_null( $this->mParams['text'] ) ) {
496 $this->mParams['text'] = $this->mParams['comment'];
497 }
498
499 $file = $this->mUpload->getLocalFile();
500 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
501
502 // Deprecated parameters
503 if ( $this->mParams['watch'] ) {
504 $watch = true;
505 }
506
507 // No errors, no warnings: do the upload
508 $status = $this->mUpload->performUpload( $this->mParams['comment'],
509 $this->mParams['text'], $watch, $this->getUser() );
510
511 if ( !$status->isGood() ) {
512 $error = $status->getErrorsArray();
513
514 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
515 // The upload can not be performed right now, because the user
516 // requested so
517 return array(
518 'result' => 'Queued',
519 'statuskey' => $error[0][1],
520 );
521 } else {
522 $this->getResult()->setIndexedTagName( $error, 'error' );
523
524 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
525 }
526 }
527
528 $file = $this->mUpload->getLocalFile();
529
530 $result['result'] = 'Success';
531 $result['filename'] = $file->getName();
532
533 return $result;
534 }
535
536 /**
537 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
538 */
539 protected function checkAsyncDownloadEnabled() {
540 global $wgAllowAsyncCopyUploads;
541 if ( !$wgAllowAsyncCopyUploads ) {
542 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
543 }
544 }
545
546 public function mustBePosted() {
547 return true;
548 }
549
550 public function isWriteMode() {
551 return true;
552 }
553
554 public function getAllowedParams() {
555 $params = array(
556 'filename' => array(
557 ApiBase::PARAM_TYPE => 'string',
558 ),
559 'comment' => array(
560 ApiBase::PARAM_DFLT => ''
561 ),
562 'text' => null,
563 'token' => null,
564 'watch' => array(
565 ApiBase::PARAM_DFLT => false,
566 ApiBase::PARAM_DEPRECATED => true,
567 ),
568 'watchlist' => array(
569 ApiBase::PARAM_DFLT => 'preferences',
570 ApiBase::PARAM_TYPE => array(
571 'watch',
572 'preferences',
573 'nochange'
574 ),
575 ),
576 'ignorewarnings' => false,
577 'file' => null,
578 'url' => null,
579 'filekey' => null,
580 'sessionkey' => array(
581 ApiBase::PARAM_DFLT => null,
582 ApiBase::PARAM_DEPRECATED => true,
583 ),
584 'stash' => false,
585
586 'filesize' => null,
587 'offset' => null,
588 'chunk' => null,
589
590 'asyncdownload' => false,
591 'leavemessage' => false,
592 'statuskey' => null,
593 );
594
595 return $params;
596 }
597
598 public function getParamDescription() {
599 $params = array(
600 'filename' => 'Target filename',
601 'token' => 'Edit token. You can get one of these through prop=info',
602 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
603 'text' => 'Initial page text for new files',
604 'watch' => 'Watch the page',
605 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
606 'ignorewarnings' => 'Ignore any warnings',
607 'file' => 'File contents',
608 'url' => 'URL to fetch the file from',
609 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
610 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
611 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
612
613 'chunk' => 'Chunk contents',
614 'offset' => 'Offset of chunk in bytes',
615 'filesize' => 'Filesize of entire upload',
616
617 'asyncdownload' => 'Make fetching a URL asynchronous',
618 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
619 'statuskey' => 'Fetch the upload status for this file key',
620 );
621
622 return $params;
623
624 }
625
626 public function getDescription() {
627 return array(
628 'Upload a file, or get the status of pending uploads. Several methods are available:',
629 ' * Upload file contents directly, using the "file" parameter',
630 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
631 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
632 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
633 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
634 );
635 }
636
637 public function getPossibleErrors() {
638 return array_merge( parent::getPossibleErrors(),
639 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
640 array(
641 array( 'uploaddisabled' ),
642 array( 'invalid-file-key' ),
643 array( 'uploaddisabled' ),
644 array( 'mustbeloggedin', 'upload' ),
645 array( 'badaccess-groups' ),
646 array( 'code' => 'fetchfileerror', 'info' => '' ),
647 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
648 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
649 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
650 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
651 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
652 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
653 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
654 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
655 )
656 );
657 }
658
659 public function needsToken() {
660 return true;
661 }
662
663 public function getTokenSalt() {
664 return '';
665 }
666
667 public function getExamples() {
668 return array(
669 'api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png'
670 => 'Upload from a URL',
671 'api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1'
672 => 'Complete an upload that failed due to warnings',
673 );
674 }
675
676 public function getHelpUrls() {
677 return 'https://www.mediawiki.org/wiki/API:Upload';
678 }
679
680 public function getVersion() {
681 return __CLASS__ . ': $Id$';
682 }
683 }