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