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