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