Translation updates from translatewiki.net
[mediawiki.git] / includes / api / ApiUpload.php
blob67165b9a6d0c85d3d4c6b8e0440c9d986e8a60ab
1 <?php
2 /**
5 * Created on Aug 21, 2008
7 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
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.
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.
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
24 * @file
27 /**
28 * @ingroup API
30 class ApiUpload extends ApiBase {
32 /**
33 * @var UploadBase
35 protected $mUpload = null;
37 protected $mParams;
39 public function __construct( $main, $action ) {
40 parent::__construct( $main, $action );
43 public function execute() {
44 // Check whether upload is enabled
45 if ( !UploadBase::isEnabled() ) {
46 $this->dieUsageMsg( 'uploaddisabled' );
49 $user = $this->getUser();
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' );
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'];
63 // Select an upload module
64 if ( !$this->selectUploadModule() ) {
65 // This is not a true upload, but a status request or similar
66 return;
68 if ( !isset( $this->mUpload ) ) {
69 $this->dieUsage( 'No upload module set', 'nomodule' );
72 // First check permission to upload
73 $this->checkPermissions( $user );
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] );
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' );
89 } else {
90 $this->verifyUpload();
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' );
102 // Get the result based on the current upload context:
103 $result = $this->getContextResult();
105 if ( $result['result'] === 'Success' ) {
106 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
109 $this->getResult()->addValue( null, $this->getModuleName(), $result );
111 // Cleanup any temporary mess
112 $this->mUpload->cleanupTempFile();
115 * Get an uplaod result based on upload context
116 * @return array
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();
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();
135 * Get Stash Result, throws an expetion if the file could not be stashed.
136 * @return array
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' );
149 return $result;
152 * Get Warnings Result
153 * @param $warnings Array of Api upload warnings
154 * @return array
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();
168 return $result;
171 * Get the result of a chunk upload.
172 * @return array
174 private function getChunkResult(){
175 $result = array();
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 ;
190 $result['filekey'] = $this->mParams['filekey'];
191 // Check we added the last chunk:
192 if( $this->mParams['offset'] + $chunkSize == $this->mParams['filesize'] ) {
193 $status = $this->mUpload->concatenateChunks();
194 if ( !$status->isGood() ) {
195 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
196 return ;
198 $result['result'] = 'Success';
201 $result['offset'] = $this->mParams['offset'] + $chunkSize;
202 return $result;
206 * Stash the file and return the file key
207 * Also re-raises exceptions with slightly more informative message strings (useful for API)
208 * @throws MWException
209 * @return String file key
211 function performStash() {
212 try {
213 $stashFile = $this->mUpload->stashFile();
215 if ( !$stashFile ) {
216 throw new MWException( 'Invalid stashed file' );
218 $fileKey = $stashFile->getFileKey();
219 } catch ( MWException $e ) {
220 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
221 wfDebug( __METHOD__ . ' ' . $message . "\n");
222 throw new MWException( $message );
224 return $fileKey;
228 * Throw an error that the user can recover from by providing a better
229 * value for $parameter
231 * @param $error array Error array suitable for passing to dieUsageMsg()
232 * @param $parameter string Parameter that needs revising
233 * @param $data array Optional extra data to pass to the user
234 * @throws UsageException
236 function dieRecoverableError( $error, $parameter, $data = array() ) {
237 try {
238 $data['filekey'] = $this->performStash();
239 $data['sessionkey'] = $data['filekey'];
240 } catch ( MWException $e ) {
241 $data['stashfailed'] = $e->getMessage();
243 $data['invalidparameter'] = $parameter;
245 $parsed = $this->parseMsg( $error );
246 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
250 * Select an upload module and set it to mUpload. Dies on failure. If the
251 * request was a status request and not a true upload, returns false;
252 * otherwise true
254 * @return bool
256 protected function selectUploadModule() {
257 $request = $this->getMain()->getRequest();
259 // chunk or one and only one of the following parameters is needed
260 if( !$this->mParams['chunk'] ) {
261 $this->requireOnlyOneParameter( $this->mParams,
262 'filekey', 'file', 'url', 'statuskey' );
265 if ( $this->mParams['statuskey'] ) {
266 $this->checkAsyncDownloadEnabled();
268 // Status request for an async upload
269 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
270 if ( !isset( $sessionData['result'] ) ) {
271 $this->dieUsage( 'No result in session data', 'missingresult' );
273 if ( $sessionData['result'] == 'Warning' ) {
274 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
275 $sessionData['sessionkey'] = $this->mParams['statuskey'];
277 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
278 return false;
282 // The following modules all require the filename parameter to be set
283 if ( is_null( $this->mParams['filename'] ) ) {
284 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
287 if ( $this->mParams['chunk'] ) {
288 // Chunk upload
289 $this->mUpload = new UploadFromChunks();
290 if( isset( $this->mParams['filekey'] ) ){
291 // handle new chunk
292 $this->mUpload->continueChunks(
293 $this->mParams['filename'],
294 $this->mParams['filekey'],
295 $request->getUpload( 'chunk' )
297 } else {
298 // handle first chunk
299 $this->mUpload->initialize(
300 $this->mParams['filename'],
301 $request->getUpload( 'chunk' )
304 } elseif ( isset( $this->mParams['filekey'] ) ) {
305 // Upload stashed in a previous request
306 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
307 $this->dieUsageMsg( 'invalid-file-key' );
310 $this->mUpload = new UploadFromStash( $this->getUser() );
312 $this->mUpload->initialize( $this->mParams['filekey'], $this->mParams['filename'] );
313 } elseif ( isset( $this->mParams['file'] ) ) {
314 $this->mUpload = new UploadFromFile();
315 $this->mUpload->initialize(
316 $this->mParams['filename'],
317 $request->getUpload( 'file' )
319 } elseif ( isset( $this->mParams['url'] ) ) {
320 // Make sure upload by URL is enabled:
321 if ( !UploadFromUrl::isEnabled() ) {
322 $this->dieUsageMsg( 'copyuploaddisabled' );
325 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
326 $this->dieUsageMsg( 'copyuploadbaddomain' );
329 $async = false;
330 if ( $this->mParams['asyncdownload'] ) {
331 $this->checkAsyncDownloadEnabled();
333 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
334 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
335 'missing-ignorewarnings' );
338 if ( $this->mParams['leavemessage'] ) {
339 $async = 'async-leavemessage';
340 } else {
341 $async = 'async';
344 $this->mUpload = new UploadFromUrl;
345 $this->mUpload->initialize( $this->mParams['filename'],
346 $this->mParams['url'], $async );
349 return true;
353 * Checks that the user has permissions to perform this upload.
354 * Dies with usage message on inadequate permissions.
355 * @param $user User The user to check.
357 protected function checkPermissions( $user ) {
358 // Check whether the user has the appropriate permissions to upload anyway
359 $permission = $this->mUpload->isAllowed( $user );
361 if ( $permission !== true ) {
362 if ( !$user->isLoggedIn() ) {
363 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
364 } else {
365 $this->dieUsageMsg( 'badaccess-groups' );
371 * Performs file verification, dies on error.
373 protected function verifyUpload( ) {
374 global $wgFileExtensions;
376 $verification = $this->mUpload->verifyUpload( );
377 if ( $verification['status'] === UploadBase::OK ) {
378 return;
381 // TODO: Move them to ApiBase's message map
382 switch( $verification['status'] ) {
383 // Recoverable errors
384 case UploadBase::MIN_LENGTH_PARTNAME:
385 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
386 break;
387 case UploadBase::ILLEGAL_FILENAME:
388 $this->dieRecoverableError( 'illegal-filename', 'filename',
389 array( 'filename' => $verification['filtered'] ) );
390 break;
391 case UploadBase::FILENAME_TOO_LONG:
392 $this->dieRecoverableError( 'filename-toolong', 'filename' );
393 break;
394 case UploadBase::FILETYPE_MISSING:
395 $this->dieRecoverableError( 'filetype-missing', 'filename' );
396 break;
397 case UploadBase::WINDOWS_NONASCII_FILENAME:
398 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
399 break;
401 // Unrecoverable errors
402 case UploadBase::EMPTY_FILE:
403 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
404 break;
405 case UploadBase::FILE_TOO_LARGE:
406 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
407 break;
409 case UploadBase::FILETYPE_BADTYPE:
410 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
411 0, array(
412 'filetype' => $verification['finalExt'],
413 'allowed' => $wgFileExtensions
414 ) );
415 break;
416 case UploadBase::VERIFICATION_ERROR:
417 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
418 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
419 0, array( 'details' => $verification['details'] ) );
420 break;
421 case UploadBase::HOOK_ABORTED:
422 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
423 'hookaborted', 0, array( 'error' => $verification['error'] ) );
424 break;
425 default:
426 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
427 0, array( 'code' => $verification['status'] ) );
428 break;
434 * Check warnings if ignorewarnings is not set.
435 * Returns a suitable array for inclusion into API results if there were warnings
436 * Returns the empty array if there were no warnings
438 * @return array
440 protected function getApiWarnings() {
441 $warnings = array();
443 if ( !$this->mParams['ignorewarnings'] ) {
444 $warnings = $this->mUpload->checkWarnings();
446 return $this->transformWarnings( $warnings );
449 protected function transformWarnings( $warnings ) {
450 if ( $warnings ) {
451 // Add indices
452 $result = $this->getResult();
453 $result->setIndexedTagName( $warnings, 'warning' );
455 if ( isset( $warnings['duplicate'] ) ) {
456 $dupes = array();
457 foreach ( $warnings['duplicate'] as $dupe ) {
458 $dupes[] = $dupe->getName();
460 $result->setIndexedTagName( $dupes, 'duplicate' );
461 $warnings['duplicate'] = $dupes;
464 if ( isset( $warnings['exists'] ) ) {
465 $warning = $warnings['exists'];
466 unset( $warnings['exists'] );
467 $warnings[$warning['warning']] = $warning['file']->getName();
470 return $warnings;
475 * Perform the actual upload. Returns a suitable result array on success;
476 * dies on failure.
478 * @return array
480 protected function performUpload() {
481 // Use comment as initial page text by default
482 if ( is_null( $this->mParams['text'] ) ) {
483 $this->mParams['text'] = $this->mParams['comment'];
486 $file = $this->mUpload->getLocalFile();
487 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
489 // Deprecated parameters
490 if ( $this->mParams['watch'] ) {
491 $watch = true;
494 // No errors, no warnings: do the upload
495 $status = $this->mUpload->performUpload( $this->mParams['comment'],
496 $this->mParams['text'], $watch, $this->getUser() );
498 if ( !$status->isGood() ) {
499 $error = $status->getErrorsArray();
501 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
502 // The upload can not be performed right now, because the user
503 // requested so
504 return array(
505 'result' => 'Queued',
506 'statuskey' => $error[0][1],
508 } else {
509 $this->getResult()->setIndexedTagName( $error, 'error' );
511 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
515 $file = $this->mUpload->getLocalFile();
517 $result['result'] = 'Success';
518 $result['filename'] = $file->getName();
520 return $result;
524 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
526 protected function checkAsyncDownloadEnabled() {
527 global $wgAllowAsyncCopyUploads;
528 if ( !$wgAllowAsyncCopyUploads ) {
529 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
533 public function mustBePosted() {
534 return true;
537 public function isWriteMode() {
538 return true;
541 public function getAllowedParams() {
542 $params = array(
543 'filename' => array(
544 ApiBase::PARAM_TYPE => 'string',
546 'comment' => array(
547 ApiBase::PARAM_DFLT => ''
549 'text' => null,
550 'token' => null,
551 'watch' => array(
552 ApiBase::PARAM_DFLT => false,
553 ApiBase::PARAM_DEPRECATED => true,
555 'watchlist' => array(
556 ApiBase::PARAM_DFLT => 'preferences',
557 ApiBase::PARAM_TYPE => array(
558 'watch',
559 'preferences',
560 'nochange'
563 'ignorewarnings' => false,
564 'file' => null,
565 'url' => null,
566 'filekey' => null,
567 'sessionkey' => array(
568 ApiBase::PARAM_DFLT => null,
569 ApiBase::PARAM_DEPRECATED => true,
571 'stash' => false,
573 'filesize' => null,
574 'offset' => null,
575 'chunk' => null,
577 'asyncdownload' => false,
578 'leavemessage' => false,
579 'statuskey' => null,
582 return $params;
585 public function getParamDescription() {
586 $params = array(
587 'filename' => 'Target filename',
588 'token' => 'Edit token. You can get one of these through prop=info',
589 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
590 'text' => 'Initial page text for new files',
591 'watch' => 'Watch the page',
592 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
593 'ignorewarnings' => 'Ignore any warnings',
594 'file' => 'File contents',
595 'url' => 'URL to fetch the file from',
596 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
597 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
598 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
600 'chunk' => 'Chunk contents',
601 'offset' => 'Offset of chunk in bytes',
602 'filesize' => 'Filesize of entire upload',
604 'asyncdownload' => 'Make fetching a URL asynchronous',
605 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
606 'statuskey' => 'Fetch the upload status for this file key',
609 return $params;
613 public function getDescription() {
614 return array(
615 'Upload a file, or get the status of pending uploads. Several methods are available:',
616 ' * Upload file contents directly, using the "file" parameter',
617 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
618 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
619 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
620 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
624 public function getPossibleErrors() {
625 return array_merge( parent::getPossibleErrors(),
626 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
627 array(
628 array( 'uploaddisabled' ),
629 array( 'invalid-file-key' ),
630 array( 'uploaddisabled' ),
631 array( 'mustbeloggedin', 'upload' ),
632 array( 'badaccess-groups' ),
633 array( 'code' => 'fetchfileerror', 'info' => '' ),
634 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
635 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
636 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
637 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
638 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
639 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
640 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
641 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
646 public function needsToken() {
647 return true;
650 public function getTokenSalt() {
651 return '';
654 public function getExamples() {
655 return array(
656 'api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png'
657 => 'Upload from a URL',
658 'api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1'
659 => 'Complete an upload that failed due to warnings',
663 public function getHelpUrls() {
664 return 'https://www.mediawiki.org/wiki/API:Upload';
667 public function getVersion() {
668 return __CLASS__ . ': $Id$';