Merge "Make sure Parsoid doesn't get snobbish and treat non-html5 tags badly."
[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 execute() {
40 global $wgEnableAsyncUploads;
41
42 // Check whether upload is enabled
43 if ( !UploadBase::isEnabled() ) {
44 $this->dieUsageMsg( 'uploaddisabled' );
45 }
46
47 $user = $this->getUser();
48
49 // Parameter handling
50 $this->mParams = $this->extractRequestParams();
51 $request = $this->getMain()->getRequest();
52 // Check if async mode is actually supported (jobs done in cli mode)
53 $this->mParams['async'] = ( $this->mParams['async'] && $wgEnableAsyncUploads );
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 return; // not a true upload, but a status request or similar
66 } elseif ( !isset( $this->mUpload ) ) {
67 $this->dieUsage( 'No upload module set', 'nomodule' );
68 }
69
70 // First check permission to upload
71 $this->checkPermissions( $user );
72
73 // Fetch the file (usually a no-op)
74 /** @var $status Status */
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 if ( $this->mParams['chunk'] ) {
84 $maxSize = $this->mUpload->getMaxUploadSize( );
85 if( $this->mParams['filesize'] > $maxSize ) {
86 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
87 }
88 if ( !$this->mUpload->getTitle() ) {
89 $this->dieUsage( 'Invalid file title supplied', 'internal-error' );
90 }
91 } elseif ( $this->mParams['async'] ) {
92 // defer verification to background process
93 } else {
94 $this->verifyUpload();
95 }
96
97 // Check if the user has the rights to modify or overwrite the requested title
98 // (This check is irrelevant if stashing is already requested, since the errors
99 // can always be fixed by changing the title)
100 if ( !$this->mParams['stash'] ) {
101 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
102 if ( $permErrors !== true ) {
103 $this->dieRecoverableError( $permErrors[0], 'filename' );
104 }
105 }
106
107 // Get the result based on the current upload context:
108 $result = $this->getContextResult();
109 if ( $result['result'] === 'Success' ) {
110 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
111 }
112
113 $this->getResult()->addValue( null, $this->getModuleName(), $result );
114
115 // Cleanup any temporary mess
116 $this->mUpload->cleanupTempFile();
117 }
118
119 /**
120 * Get an upload result based on upload context
121 * @return array
122 */
123 private function getContextResult() {
124 $warnings = $this->getApiWarnings();
125 if ( $warnings && !$this->mParams['ignorewarnings'] ) {
126 // Get warnings formatted in result array format
127 return $this->getWarningsResult( $warnings );
128 } elseif ( $this->mParams['chunk'] ) {
129 // Add chunk, and get result
130 return $this->getChunkResult( $warnings );
131 } elseif ( $this->mParams['stash'] ) {
132 // Stash the file and get stash result
133 return $this->getStashResult( $warnings );
134 }
135 // This is the most common case -- a normal upload with no warnings
136 // performUpload will return a formatted properly for the API with status
137 return $this->performUpload( $warnings );
138 }
139
140 /**
141 * Get Stash Result, throws an exception if the file could not be stashed.
142 * @param $warnings array Array of Api upload warnings
143 * @return array
144 */
145 private function getStashResult( $warnings ) {
146 $result = array ();
147 // Some uploads can request they be stashed, so as not to publish them immediately.
148 // In this case, a failure to stash ought to be fatal
149 try {
150 $result['result'] = 'Success';
151 $result['filekey'] = $this->performStash();
152 $result['sessionkey'] = $result['filekey']; // backwards compatibility
153 if ( $warnings && count( $warnings ) > 0 ) {
154 $result['warnings'] = $warnings;
155 }
156 } catch ( MWException $e ) {
157 $this->dieUsage( $e->getMessage(), 'stashfailed' );
158 }
159 return $result;
160 }
161
162 /**
163 * Get Warnings Result
164 * @param $warnings array Array of Api upload warnings
165 * @return array
166 */
167 private function getWarningsResult( $warnings ) {
168 $result = array();
169 $result['result'] = 'Warning';
170 $result['warnings'] = $warnings;
171 // in case the warnings can be fixed with some further user action, let's stash this upload
172 // and return a key they can use to restart it
173 try {
174 $result['filekey'] = $this->performStash();
175 $result['sessionkey'] = $result['filekey']; // backwards compatibility
176 } catch ( MWException $e ) {
177 $result['warnings']['stashfailed'] = $e->getMessage();
178 }
179 return $result;
180 }
181
182 /**
183 * Get the result of a chunk upload.
184 * @param $warnings array Array of Api upload warnings
185 * @return array
186 */
187 private function getChunkResult( $warnings ) {
188 $result = array();
189
190 $result['result'] = 'Continue';
191 if ( $warnings && count( $warnings ) > 0 ) {
192 $result['warnings'] = $warnings;
193 }
194 $request = $this->getMain()->getRequest();
195 $chunkPath = $request->getFileTempname( 'chunk' );
196 $chunkSize = $request->getUpload( 'chunk' )->getSize();
197 if ( $this->mParams['offset'] == 0 ) {
198 $filekey = $this->performStash();
199 } else {
200 $filekey = $this->mParams['filekey'];
201 /** @var $status Status */
202 $status = $this->mUpload->addChunk(
203 $chunkPath, $chunkSize, $this->mParams['offset'] );
204 if ( !$status->isGood() ) {
205 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
206 return array();
207 }
208 }
209
210 // Check we added the last chunk:
211 if ( $this->mParams['offset'] + $chunkSize == $this->mParams['filesize'] ) {
212 if ( $this->mParams['async'] ) {
213 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
214 if ( $progress && $progress['result'] === 'Poll' ) {
215 $this->dieUsage( "Chunk assembly already in progress.", 'stashfailed' );
216 }
217 UploadBase::setSessionStatus(
218 $this->mParams['filekey'],
219 array( 'result' => 'Poll',
220 'stage' => 'queued', 'status' => Status::newGood() )
221 );
222 $ok = JobQueueGroup::singleton()->push( new AssembleUploadChunksJob(
223 Title::makeTitle( NS_FILE, $this->mParams['filekey'] ),
224 array(
225 'filename' => $this->mParams['filename'],
226 'filekey' => $this->mParams['filekey'],
227 'session' => $this->getRequest()->exportUserSession(),
228 'userid' => $this->getUser()->getId()
229 )
230 ) );
231 if ( $ok ) {
232 $result['result'] = 'Poll';
233 } else {
234 UploadBase::setSessionStatus( $this->mParams['filekey'], false );
235 $this->dieUsage(
236 "Failed to start AssembleUploadChunks.php", 'stashfailed' );
237 }
238 } else {
239 $status = $this->mUpload->concatenateChunks();
240 if ( !$status->isGood() ) {
241 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
242 return array();
243 }
244
245 // The fully concatenated file has a new filekey. So remove
246 // the old filekey and fetch the new one.
247 $this->mUpload->stash->removeFile( $filekey );
248 $filekey = $this->mUpload->getLocalFile()->getFileKey();
249
250 $result['result'] = 'Success';
251 }
252 }
253 $result['filekey'] = $filekey;
254 $result['offset'] = $this->mParams['offset'] + $chunkSize;
255 return $result;
256 }
257
258 /**
259 * Stash the file and return the file key
260 * Also re-raises exceptions with slightly more informative message strings (useful for API)
261 * @throws MWException
262 * @return String file key
263 */
264 private function performStash() {
265 try {
266 $stashFile = $this->mUpload->stashFile();
267
268 if ( !$stashFile ) {
269 throw new MWException( 'Invalid stashed file' );
270 }
271 $fileKey = $stashFile->getFileKey();
272 } catch ( MWException $e ) {
273 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
274 wfDebug( __METHOD__ . ' ' . $message . "\n" );
275 throw new MWException( $message );
276 }
277 return $fileKey;
278 }
279
280 /**
281 * Throw an error that the user can recover from by providing a better
282 * value for $parameter
283 *
284 * @param $error array Error array suitable for passing to dieUsageMsg()
285 * @param $parameter string Parameter that needs revising
286 * @param $data array Optional extra data to pass to the user
287 * @throws UsageException
288 */
289 private function dieRecoverableError( $error, $parameter, $data = array() ) {
290 try {
291 $data['filekey'] = $this->performStash();
292 $data['sessionkey'] = $data['filekey'];
293 } catch ( MWException $e ) {
294 $data['stashfailed'] = $e->getMessage();
295 }
296 $data['invalidparameter'] = $parameter;
297
298 $parsed = $this->parseMsg( $error );
299 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
300 }
301
302 /**
303 * Select an upload module and set it to mUpload. Dies on failure. If the
304 * request was a status request and not a true upload, returns false;
305 * otherwise true
306 *
307 * @return bool
308 */
309 protected function selectUploadModule() {
310 $request = $this->getMain()->getRequest();
311
312 // chunk or one and only one of the following parameters is needed
313 if ( !$this->mParams['chunk'] ) {
314 $this->requireOnlyOneParameter( $this->mParams,
315 'filekey', 'file', 'url', 'statuskey' );
316 }
317
318 // Status report for "upload to stash"/"upload from stash"
319 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
320 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
321 if ( !$progress ) {
322 $this->dieUsage( 'No result in status data', 'missingresult' );
323 } elseif ( !$progress['status']->isGood() ) {
324 $this->dieUsage( $progress['status']->getWikiText(), 'stashfailed' );
325 }
326 if ( isset( $progress['status']->value['verification'] ) ) {
327 $this->checkVerification( $progress['status']->value['verification'] );
328 }
329 unset( $progress['status'] ); // remove Status object
330 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
331 return false;
332 }
333
334 if ( $this->mParams['statuskey'] ) {
335 $this->checkAsyncDownloadEnabled();
336
337 // Status request for an async upload
338 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
339 if ( !isset( $sessionData['result'] ) ) {
340 $this->dieUsage( 'No result in session data', 'missingresult' );
341 }
342 if ( $sessionData['result'] == 'Warning' ) {
343 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
344 $sessionData['sessionkey'] = $this->mParams['statuskey'];
345 }
346 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
347 return false;
348 }
349
350 // The following modules all require the filename parameter to be set
351 if ( is_null( $this->mParams['filename'] ) ) {
352 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
353 }
354
355 if ( $this->mParams['chunk'] ) {
356 // Chunk upload
357 $this->mUpload = new UploadFromChunks();
358 if( isset( $this->mParams['filekey'] ) ) {
359 // handle new chunk
360 $this->mUpload->continueChunks(
361 $this->mParams['filename'],
362 $this->mParams['filekey'],
363 $request->getUpload( 'chunk' )
364 );
365 } else {
366 // handle first chunk
367 $this->mUpload->initialize(
368 $this->mParams['filename'],
369 $request->getUpload( 'chunk' )
370 );
371 }
372 } elseif ( isset( $this->mParams['filekey'] ) ) {
373 // Upload stashed in a previous request
374 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
375 $this->dieUsageMsg( 'invalid-file-key' );
376 }
377
378 $this->mUpload = new UploadFromStash( $this->getUser() );
379 // This will not download the temp file in initialize() in async mode.
380 // We still have enough information to call checkWarnings() and such.
381 $this->mUpload->initialize(
382 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
383 );
384 } elseif ( isset( $this->mParams['file'] ) ) {
385 $this->mUpload = new UploadFromFile();
386 $this->mUpload->initialize(
387 $this->mParams['filename'],
388 $request->getUpload( 'file' )
389 );
390 } elseif ( isset( $this->mParams['url'] ) ) {
391 // Make sure upload by URL is enabled:
392 if ( !UploadFromUrl::isEnabled() ) {
393 $this->dieUsageMsg( 'copyuploaddisabled' );
394 }
395
396 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
397 $this->dieUsageMsg( 'copyuploadbaddomain' );
398 }
399
400 $async = false;
401 if ( $this->mParams['asyncdownload'] ) {
402 $this->checkAsyncDownloadEnabled();
403
404 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
405 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
406 'missing-ignorewarnings' );
407 }
408
409 if ( $this->mParams['leavemessage'] ) {
410 $async = 'async-leavemessage';
411 } else {
412 $async = 'async';
413 }
414 }
415 $this->mUpload = new UploadFromUrl;
416 $this->mUpload->initialize( $this->mParams['filename'],
417 $this->mParams['url'], $async );
418 }
419
420 return true;
421 }
422
423 /**
424 * Checks that the user has permissions to perform this upload.
425 * Dies with usage message on inadequate permissions.
426 * @param $user User The user to check.
427 */
428 protected function checkPermissions( $user ) {
429 // Check whether the user has the appropriate permissions to upload anyway
430 $permission = $this->mUpload->isAllowed( $user );
431
432 if ( $permission !== true ) {
433 if ( !$user->isLoggedIn() ) {
434 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
435 } else {
436 $this->dieUsageMsg( 'badaccess-groups' );
437 }
438 }
439 }
440
441 /**
442 * Performs file verification, dies on error.
443 */
444 protected function verifyUpload( ) {
445 $verification = $this->mUpload->verifyUpload( );
446 if ( $verification['status'] === UploadBase::OK ) {
447 return;
448 } else {
449 return $this->checkVerification( $verification );
450 }
451 }
452
453 /**
454 * Performs file verification, dies on error.
455 */
456 protected function checkVerification( array $verification ) {
457 global $wgFileExtensions;
458
459 // TODO: Move them to ApiBase's message map
460 switch( $verification['status'] ) {
461 // Recoverable errors
462 case UploadBase::MIN_LENGTH_PARTNAME:
463 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
464 break;
465 case UploadBase::ILLEGAL_FILENAME:
466 $this->dieRecoverableError( 'illegal-filename', 'filename',
467 array( 'filename' => $verification['filtered'] ) );
468 break;
469 case UploadBase::FILENAME_TOO_LONG:
470 $this->dieRecoverableError( 'filename-toolong', 'filename' );
471 break;
472 case UploadBase::FILETYPE_MISSING:
473 $this->dieRecoverableError( 'filetype-missing', 'filename' );
474 break;
475 case UploadBase::WINDOWS_NONASCII_FILENAME:
476 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
477 break;
478
479 // Unrecoverable errors
480 case UploadBase::EMPTY_FILE:
481 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
482 break;
483 case UploadBase::FILE_TOO_LARGE:
484 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
485 break;
486
487 case UploadBase::FILETYPE_BADTYPE:
488 $extradata = array(
489 'filetype' => $verification['finalExt'],
490 'allowed' => $wgFileExtensions
491 );
492 $this->getResult()->setIndexedTagName( $extradata['allowed'], 'ext' );
493
494 $msg = "Filetype not permitted: ";
495 if ( isset( $verification['blacklistedExt'] ) ) {
496 $msg .= join( ', ', $verification['blacklistedExt'] );
497 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
498 $this->getResult()->setIndexedTagName( $extradata['blacklisted'], 'ext' );
499 } else {
500 $msg .= $verification['finalExt'];
501 }
502 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
503 break;
504 case UploadBase::VERIFICATION_ERROR:
505 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
506 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
507 0, array( 'details' => $verification['details'] ) );
508 break;
509 case UploadBase::HOOK_ABORTED:
510 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
511 'hookaborted', 0, array( 'error' => $verification['error'] ) );
512 break;
513 default:
514 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
515 0, array( 'code' => $verification['status'] ) );
516 break;
517 }
518 }
519
520 /**
521 * Check warnings.
522 * Returns a suitable array for inclusion into API results if there were warnings
523 * Returns the empty array if there were no warnings
524 *
525 * @return array
526 */
527 protected function getApiWarnings() {
528 $warnings = $this->mUpload->checkWarnings();
529
530 return $this->transformWarnings( $warnings );
531 }
532
533 protected function transformWarnings( $warnings ) {
534 if ( $warnings ) {
535 // Add indices
536 $result = $this->getResult();
537 $result->setIndexedTagName( $warnings, 'warning' );
538
539 if ( isset( $warnings['duplicate'] ) ) {
540 $dupes = array();
541 foreach ( $warnings['duplicate'] as $dupe ) {
542 $dupes[] = $dupe->getName();
543 }
544 $result->setIndexedTagName( $dupes, 'duplicate' );
545 $warnings['duplicate'] = $dupes;
546 }
547
548 if ( isset( $warnings['exists'] ) ) {
549 $warning = $warnings['exists'];
550 unset( $warnings['exists'] );
551 $warnings[$warning['warning']] = $warning['file']->getName();
552 }
553 }
554 return $warnings;
555 }
556
557 /**
558 * Perform the actual upload. Returns a suitable result array on success;
559 * dies on failure.
560 *
561 * @param $warnings array Array of Api upload warnings
562 * @return array
563 */
564 protected function performUpload( $warnings ) {
565 // Use comment as initial page text by default
566 if ( is_null( $this->mParams['text'] ) ) {
567 $this->mParams['text'] = $this->mParams['comment'];
568 }
569
570 /** @var $file File */
571 $file = $this->mUpload->getLocalFile();
572 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
573
574 // Deprecated parameters
575 if ( $this->mParams['watch'] ) {
576 $watch = true;
577 }
578
579 // No errors, no warnings: do the upload
580 if ( $this->mParams['async'] ) {
581 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
582 if ( $progress && $progress['result'] === 'Poll' ) {
583 $this->dieUsage( "Upload from stash already in progress.", 'publishfailed' );
584 }
585 UploadBase::setSessionStatus(
586 $this->mParams['filekey'],
587 array( 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() )
588 );
589 $ok = JobQueueGroup::singleton()->push( new PublishStashedFileJob(
590 Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
591 array(
592 'filename' => $this->mParams['filename'],
593 'filekey' => $this->mParams['filekey'],
594 'comment' => $this->mParams['comment'],
595 'text' => $this->mParams['text'],
596 'watch' => $watch,
597 'session' => $this->getRequest()->exportUserSession(),
598 'userid' => $this->getUser()->getId()
599 )
600 ) );
601 if ( $ok ) {
602 $result['result'] = 'Poll';
603 } else {
604 UploadBase::setSessionStatus( $this->mParams['filekey'], false );
605 $this->dieUsage(
606 "Failed to start PublishStashedFile.php", 'publishfailed' );
607 }
608 } else {
609 /** @var $status Status */
610 $status = $this->mUpload->performUpload( $this->mParams['comment'],
611 $this->mParams['text'], $watch, $this->getUser() );
612
613 if ( !$status->isGood() ) {
614 $error = $status->getErrorsArray();
615
616 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
617 // The upload can not be performed right now, because the user
618 // requested so
619 return array(
620 'result' => 'Queued',
621 'statuskey' => $error[0][1],
622 );
623 } else {
624 $this->getResult()->setIndexedTagName( $error, 'error' );
625
626 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
627 }
628 }
629 $result['result'] = 'Success';
630 }
631
632 $result['filename'] = $file->getName();
633 if ( $warnings && count( $warnings ) > 0 ) {
634 $result['warnings'] = $warnings;
635 }
636
637 return $result;
638 }
639
640 /**
641 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
642 */
643 protected function checkAsyncDownloadEnabled() {
644 global $wgAllowAsyncCopyUploads;
645 if ( !$wgAllowAsyncCopyUploads ) {
646 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled' );
647 }
648 }
649
650 public function mustBePosted() {
651 return true;
652 }
653
654 public function isWriteMode() {
655 return true;
656 }
657
658 public function getAllowedParams() {
659 $params = array(
660 'filename' => array(
661 ApiBase::PARAM_TYPE => 'string',
662 ),
663 'comment' => array(
664 ApiBase::PARAM_DFLT => ''
665 ),
666 'text' => null,
667 'token' => array(
668 ApiBase::PARAM_TYPE => 'string',
669 ApiBase::PARAM_REQUIRED => true
670 ),
671 'watch' => array(
672 ApiBase::PARAM_DFLT => false,
673 ApiBase::PARAM_DEPRECATED => true,
674 ),
675 'watchlist' => array(
676 ApiBase::PARAM_DFLT => 'preferences',
677 ApiBase::PARAM_TYPE => array(
678 'watch',
679 'preferences',
680 'nochange'
681 ),
682 ),
683 'ignorewarnings' => false,
684 'file' => array(
685 ApiBase::PARAM_TYPE => 'upload',
686 ),
687 'url' => null,
688 'filekey' => null,
689 'sessionkey' => array(
690 ApiBase::PARAM_DFLT => null,
691 ApiBase::PARAM_DEPRECATED => true,
692 ),
693 'stash' => false,
694
695 'filesize' => null,
696 'offset' => null,
697 'chunk' => array(
698 ApiBase::PARAM_TYPE => 'upload',
699 ),
700
701 'async' => false,
702 'asyncdownload' => false,
703 'leavemessage' => false,
704 'statuskey' => null,
705 'checkstatus' => false,
706 );
707
708 return $params;
709 }
710
711 public function getParamDescription() {
712 $params = array(
713 'filename' => 'Target filename',
714 'token' => 'Edit token. You can get one of these through prop=info',
715 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
716 'text' => 'Initial page text for new files',
717 'watch' => 'Watch the page',
718 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
719 'ignorewarnings' => 'Ignore any warnings',
720 'file' => 'File contents',
721 'url' => 'URL to fetch the file from',
722 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
723 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
724 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
725
726 'chunk' => 'Chunk contents',
727 'offset' => 'Offset of chunk in bytes',
728 'filesize' => 'Filesize of entire upload',
729
730 'async' => 'Make potentially large file operations asynchronous when possible',
731 'asyncdownload' => 'Make fetching a URL asynchronous',
732 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
733 'statuskey' => 'Fetch the upload status for this file key (upload by URL)',
734 'checkstatus' => 'Only fetch the upload status for the given file key',
735 );
736
737 return $params;
738
739 }
740
741 public function getResultProperties() {
742 return array(
743 '' => array(
744 'result' => array(
745 ApiBase::PROP_TYPE => array(
746 'Success',
747 'Warning',
748 'Continue',
749 'Queued'
750 ),
751 ),
752 'filekey' => array(
753 ApiBase::PROP_TYPE => 'string',
754 ApiBase::PROP_NULLABLE => true
755 ),
756 'sessionkey' => array(
757 ApiBase::PROP_TYPE => 'string',
758 ApiBase::PROP_NULLABLE => true
759 ),
760 'offset' => array(
761 ApiBase::PROP_TYPE => 'integer',
762 ApiBase::PROP_NULLABLE => true
763 ),
764 'statuskey' => array(
765 ApiBase::PROP_TYPE => 'string',
766 ApiBase::PROP_NULLABLE => true
767 ),
768 'filename' => array(
769 ApiBase::PROP_TYPE => 'string',
770 ApiBase::PROP_NULLABLE => true
771 )
772 )
773 );
774 }
775
776 public function getDescription() {
777 return array(
778 'Upload a file, or get the status of pending uploads. Several methods are available:',
779 ' * Upload file contents directly, using the "file" parameter',
780 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
781 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
782 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
783 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
784 );
785 }
786
787 public function getPossibleErrors() {
788 return array_merge( parent::getPossibleErrors(),
789 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
790 array(
791 array( 'uploaddisabled' ),
792 array( 'invalid-file-key' ),
793 array( 'uploaddisabled' ),
794 array( 'mustbeloggedin', 'upload' ),
795 array( 'badaccess-groups' ),
796 array( 'code' => 'fetchfileerror', 'info' => '' ),
797 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
798 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
799 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
800 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
801 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
802 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
803 array( 'code' => 'publishfailed', 'info' => 'Publishing of stashed file failed' ),
804 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
805 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
806 array( 'fileexists-forbidden' ),
807 array( 'fileexists-shared-forbidden' ),
808 )
809 );
810 }
811
812 public function needsToken() {
813 return true;
814 }
815
816 public function getTokenSalt() {
817 return '';
818 }
819
820 public function getExamples() {
821 return array(
822 'api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png'
823 => 'Upload from a URL',
824 'api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1'
825 => 'Complete an upload that failed due to warnings',
826 );
827 }
828
829 public function getHelpUrls() {
830 return 'https://www.mediawiki.org/wiki/API:Upload';
831 }
832 }