jquery.makeCollapsible: Align toggle based on content language
[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|UploadFromChunks */
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->logFeatureUsage( 'action=upload&sessionkey' );
56 $this->mParams['filekey'] = $this->mParams['sessionkey'];
57 }
58
59 // Select an upload module
60 try {
61 if ( !$this->selectUploadModule() ) {
62 return; // not a true upload, but a status request or similar
63 } elseif ( !isset( $this->mUpload ) ) {
64 $this->dieUsage( 'No upload module set', 'nomodule' );
65 }
66 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
67 $this->handleStashException( $e );
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'] && $this->mParams['filekey'] ) {
92 // defer verification to background process
93 } else {
94 wfDebug( __METHOD__ . " about to verify\n" );
95 $this->verifyUpload();
96 }
97
98 // Check if the user has the rights to modify or overwrite the requested title
99 // (This check is irrelevant if stashing is already requested, since the errors
100 // can always be fixed by changing the title)
101 if ( !$this->mParams['stash'] ) {
102 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
103 if ( $permErrors !== true ) {
104 $this->dieRecoverableError( $permErrors[0], 'filename' );
105 }
106 }
107
108 // Get the result based on the current upload context:
109 try {
110 $result = $this->getContextResult();
111 if ( $result['result'] === 'Success' ) {
112 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
113 }
114 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
115 $this->handleStashException( $e );
116 }
117
118 $this->getResult()->addValue( null, $this->getModuleName(), $result );
119
120 // Cleanup any temporary mess
121 $this->mUpload->cleanupTempFile();
122 }
123
124 /**
125 * Get an upload result based on upload context
126 * @return array
127 */
128 private function getContextResult() {
129 $warnings = $this->getApiWarnings();
130 if ( $warnings && !$this->mParams['ignorewarnings'] ) {
131 // Get warnings formatted in result array format
132 return $this->getWarningsResult( $warnings );
133 } elseif ( $this->mParams['chunk'] ) {
134 // Add chunk, and get result
135 return $this->getChunkResult( $warnings );
136 } elseif ( $this->mParams['stash'] ) {
137 // Stash the file and get stash result
138 return $this->getStashResult( $warnings );
139 }
140
141 // This is the most common case -- a normal upload with no warnings
142 // performUpload will return a formatted properly for the API with status
143 return $this->performUpload( $warnings );
144 }
145
146 /**
147 * Get Stash Result, throws an exception if the file could not be stashed.
148 * @param array $warnings Array of Api upload warnings
149 * @return array
150 */
151 private function getStashResult( $warnings ) {
152 $result = array();
153 // Some uploads can request they be stashed, so as not to publish them immediately.
154 // In this case, a failure to stash ought to be fatal
155 try {
156 $result['result'] = 'Success';
157 $result['filekey'] = $this->performStash();
158 $result['sessionkey'] = $result['filekey']; // backwards compatibility
159 if ( $warnings && count( $warnings ) > 0 ) {
160 $result['warnings'] = $warnings;
161 }
162 } catch ( UploadStashException $e ) {
163 $this->handleStashException( $e );
164 } catch ( Exception $e ) {
165 $this->dieUsage( $e->getMessage(), 'stashfailed' );
166 }
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 ( Exception $e ) {
186 $result['warnings']['stashfailed'] = $e->getMessage();
187 }
188
189 return $result;
190 }
191
192 /**
193 * Get the result of a chunk upload.
194 * @param array $warnings Array of Api upload warnings
195 * @return array
196 */
197 private function getChunkResult( $warnings ) {
198 $result = array();
199
200 $result['result'] = 'Continue';
201 if ( $warnings && count( $warnings ) > 0 ) {
202 $result['warnings'] = $warnings;
203 }
204 $request = $this->getMain()->getRequest();
205 $chunkPath = $request->getFileTempname( 'chunk' );
206 $chunkSize = $request->getUpload( 'chunk' )->getSize();
207 if ( $this->mParams['offset'] == 0 ) {
208 try {
209 $filekey = $this->performStash();
210 } catch ( UploadStashException $e ) {
211 $this->handleStashException( $e );
212 } catch ( Exception $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 $status = $this->mUpload->addChunk(
219 $chunkPath, $chunkSize, $this->mParams['offset'] );
220 if ( !$status->isGood() ) {
221 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
222
223 return array();
224 }
225 }
226
227 // Check we added the last chunk:
228 if ( $this->mParams['offset'] + $chunkSize == $this->mParams['filesize'] ) {
229 if ( $this->mParams['async'] ) {
230 $progress = UploadBase::getSessionStatus( $this->getUser(), $filekey );
231 if ( $progress && $progress['result'] === 'Poll' ) {
232 $this->dieUsage( "Chunk assembly already in progress.", 'stashfailed' );
233 }
234 UploadBase::setSessionStatus(
235 $this->getUser(),
236 $filekey,
237 array( 'result' => 'Poll',
238 'stage' => 'queued', 'status' => Status::newGood() )
239 );
240 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 $result['result'] = 'Poll';
249 $result['stage'] = 'queued';
250 } else {
251 $status = $this->mUpload->concatenateChunks();
252 if ( !$status->isGood() ) {
253 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
254
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
269 return $result;
270 }
271
272 /**
273 * Stash the file and return the file key
274 * Also re-raises exceptions with slightly more informative message strings (useful for API)
275 * @throws MWException
276 * @return string File key
277 */
278 private function performStash() {
279 try {
280 $stashFile = $this->mUpload->stashFile( $this->getUser() );
281
282 if ( !$stashFile ) {
283 throw new MWException( 'Invalid stashed file' );
284 }
285 $fileKey = $stashFile->getFileKey();
286 } catch ( Exception $e ) {
287 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
288 wfDebug( __METHOD__ . ' ' . $message . "\n" );
289 $className = get_class( $e );
290 throw new $className( $message );
291 }
292
293 return $fileKey;
294 }
295
296 /**
297 * Throw an error that the user can recover from by providing a better
298 * value for $parameter
299 *
300 * @param array $error Error array suitable for passing to dieUsageMsg()
301 * @param string $parameter Parameter that needs revising
302 * @param array $data Optional extra data to pass to the user
303 * @throws UsageException
304 */
305 private function dieRecoverableError( $error, $parameter, $data = array() ) {
306 try {
307 $data['filekey'] = $this->performStash();
308 $data['sessionkey'] = $data['filekey'];
309 } catch ( Exception $e ) {
310 $data['stashfailed'] = $e->getMessage();
311 }
312 $data['invalidparameter'] = $parameter;
313
314 $parsed = $this->parseMsg( $error );
315 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
316 }
317
318 /**
319 * Select an upload module and set it to mUpload. Dies on failure. If the
320 * request was a status request and not a true upload, returns false;
321 * otherwise true
322 *
323 * @return bool
324 */
325 protected function selectUploadModule() {
326 $request = $this->getMain()->getRequest();
327
328 // chunk or one and only one of the following parameters is needed
329 if ( !$this->mParams['chunk'] ) {
330 $this->requireOnlyOneParameter( $this->mParams,
331 'filekey', 'file', 'url', 'statuskey' );
332 }
333
334 // Status report for "upload to stash"/"upload from stash"
335 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
336 $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
337 if ( !$progress ) {
338 $this->dieUsage( 'No result in status data', 'missingresult' );
339 } elseif ( !$progress['status']->isGood() ) {
340 $this->dieUsage( $progress['status']->getWikiText(), 'stashfailed' );
341 }
342 if ( isset( $progress['status']->value['verification'] ) ) {
343 $this->checkVerification( $progress['status']->value['verification'] );
344 }
345 unset( $progress['status'] ); // remove Status object
346 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
347
348 return false;
349 }
350
351 if ( $this->mParams['statuskey'] ) {
352 $this->checkAsyncDownloadEnabled();
353
354 // Status request for an async upload
355 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
356 if ( !isset( $sessionData['result'] ) ) {
357 $this->dieUsage( 'No result in session data', 'missingresult' );
358 }
359 if ( $sessionData['result'] == 'Warning' ) {
360 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
361 $sessionData['sessionkey'] = $this->mParams['statuskey'];
362 }
363 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
364
365 return false;
366 }
367
368 // The following modules all require the filename parameter to be set
369 if ( is_null( $this->mParams['filename'] ) ) {
370 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
371 }
372
373 if ( $this->mParams['chunk'] ) {
374 // Chunk upload
375 $this->mUpload = new UploadFromChunks();
376 if ( isset( $this->mParams['filekey'] ) ) {
377 // handle new chunk
378 $this->mUpload->continueChunks(
379 $this->mParams['filename'],
380 $this->mParams['filekey'],
381 $request->getUpload( 'chunk' )
382 );
383 } else {
384 // handle first chunk
385 $this->mUpload->initialize(
386 $this->mParams['filename'],
387 $request->getUpload( 'chunk' )
388 );
389 }
390 } elseif ( isset( $this->mParams['filekey'] ) ) {
391 // Upload stashed in a previous request
392 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
393 $this->dieUsageMsg( 'invalid-file-key' );
394 }
395
396 $this->mUpload = new UploadFromStash( $this->getUser() );
397 // This will not download the temp file in initialize() in async mode.
398 // We still have enough information to call checkWarnings() and such.
399 $this->mUpload->initialize(
400 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
401 );
402 } elseif ( isset( $this->mParams['file'] ) ) {
403 $this->mUpload = new UploadFromFile();
404 $this->mUpload->initialize(
405 $this->mParams['filename'],
406 $request->getUpload( 'file' )
407 );
408 } elseif ( isset( $this->mParams['url'] ) ) {
409 // Make sure upload by URL is enabled:
410 if ( !UploadFromUrl::isEnabled() ) {
411 $this->dieUsageMsg( 'copyuploaddisabled' );
412 }
413
414 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
415 $this->dieUsageMsg( 'copyuploadbaddomain' );
416 }
417
418 if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
419 $this->dieUsageMsg( 'copyuploadbadurl' );
420 }
421
422 $async = false;
423 if ( $this->mParams['asyncdownload'] ) {
424 $this->checkAsyncDownloadEnabled();
425
426 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
427 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
428 'missing-ignorewarnings' );
429 }
430
431 if ( $this->mParams['leavemessage'] ) {
432 $async = 'async-leavemessage';
433 } else {
434 $async = 'async';
435 }
436 }
437 $this->mUpload = new UploadFromUrl;
438 $this->mUpload->initialize( $this->mParams['filename'],
439 $this->mParams['url'], $async );
440 }
441
442 return true;
443 }
444
445 /**
446 * Checks that the user has permissions to perform this upload.
447 * Dies with usage message on inadequate permissions.
448 * @param User $user The user to check.
449 */
450 protected function checkPermissions( $user ) {
451 // Check whether the user has the appropriate permissions to upload anyway
452 $permission = $this->mUpload->isAllowed( $user );
453
454 if ( $permission !== true ) {
455 if ( !$user->isLoggedIn() ) {
456 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
457 }
458
459 $this->dieUsageMsg( 'badaccess-groups' );
460 }
461 }
462
463 /**
464 * Performs file verification, dies on error.
465 */
466 protected function verifyUpload() {
467 $verification = $this->mUpload->verifyUpload();
468 if ( $verification['status'] === UploadBase::OK ) {
469 return;
470 }
471
472 $this->checkVerification( $verification );
473 }
474
475 /**
476 * Performs file verification, dies on error.
477 * @param array $verification
478 */
479 protected function checkVerification( array $verification ) {
480 // @todo Move them to ApiBase's message map
481 switch ( $verification['status'] ) {
482 // Recoverable errors
483 case UploadBase::MIN_LENGTH_PARTNAME:
484 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
485 break;
486 case UploadBase::ILLEGAL_FILENAME:
487 $this->dieRecoverableError( 'illegal-filename', 'filename',
488 array( 'filename' => $verification['filtered'] ) );
489 break;
490 case UploadBase::FILENAME_TOO_LONG:
491 $this->dieRecoverableError( 'filename-toolong', 'filename' );
492 break;
493 case UploadBase::FILETYPE_MISSING:
494 $this->dieRecoverableError( 'filetype-missing', 'filename' );
495 break;
496 case UploadBase::WINDOWS_NONASCII_FILENAME:
497 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
498 break;
499
500 // Unrecoverable errors
501 case UploadBase::EMPTY_FILE:
502 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
503 break;
504 case UploadBase::FILE_TOO_LARGE:
505 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
506 break;
507
508 case UploadBase::FILETYPE_BADTYPE:
509 $extradata = array(
510 'filetype' => $verification['finalExt'],
511 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
512 );
513 $this->getResult()->setIndexedTagName( $extradata['allowed'], 'ext' );
514
515 $msg = "Filetype not permitted: ";
516 if ( isset( $verification['blacklistedExt'] ) ) {
517 $msg .= join( ', ', $verification['blacklistedExt'] );
518 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
519 $this->getResult()->setIndexedTagName( $extradata['blacklisted'], 'ext' );
520 } else {
521 $msg .= $verification['finalExt'];
522 }
523 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
524 break;
525 case UploadBase::VERIFICATION_ERROR:
526 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
527 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
528 0, array( 'details' => $verification['details'] ) );
529 break;
530 case UploadBase::HOOK_ABORTED:
531 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
532 'hookaborted', 0, array( 'error' => $verification['error'] ) );
533 break;
534 default:
535 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
536 0, array( 'code' => $verification['status'] ) );
537 break;
538 }
539 }
540
541 /**
542 * Check warnings.
543 * Returns a suitable array for inclusion into API results if there were warnings
544 * Returns the empty array if there were no warnings
545 *
546 * @return array
547 */
548 protected function getApiWarnings() {
549 $warnings = $this->mUpload->checkWarnings();
550
551 return $this->transformWarnings( $warnings );
552 }
553
554 protected function transformWarnings( $warnings ) {
555 if ( $warnings ) {
556 // Add indices
557 $result = $this->getResult();
558 $result->setIndexedTagName( $warnings, 'warning' );
559
560 if ( isset( $warnings['duplicate'] ) ) {
561 $dupes = array();
562 /** @var File $dupe */
563 foreach ( $warnings['duplicate'] as $dupe ) {
564 $dupes[] = $dupe->getName();
565 }
566 $result->setIndexedTagName( $dupes, 'duplicate' );
567 $warnings['duplicate'] = $dupes;
568 }
569
570 if ( isset( $warnings['exists'] ) ) {
571 $warning = $warnings['exists'];
572 unset( $warnings['exists'] );
573 /** @var LocalFile $localFile */
574 $localFile = isset( $warning['normalizedFile'] )
575 ? $warning['normalizedFile']
576 : $warning['file'];
577 $warnings[$warning['warning']] = $localFile->getName();
578 }
579 }
580
581 return $warnings;
582 }
583
584 /**
585 * Handles a stash exception, giving a useful error to the user.
586 * @param Exception $e The exception we encountered.
587 */
588 protected function handleStashException( $e ) {
589 $exceptionType = get_class( $e );
590
591 switch ( $exceptionType ) {
592 case 'UploadStashFileNotFoundException':
593 $this->dieUsage( 'Could not find the file in the stash: ' . $e->getMessage(), 'stashedfilenotfound' );
594 break;
595 case 'UploadStashBadPathException':
596 $this->dieUsage( 'File key of improper format or otherwise invalid: ' . $e->getMessage(), 'stashpathinvalid' );
597 break;
598 case 'UploadStashFileException':
599 $this->dieUsage( 'Could not store upload in the stash: ' . $e->getMessage(), 'stashfilestorage' );
600 break;
601 case 'UploadStashZeroLengthFileException':
602 $this->dieUsage( 'File is of zero length, and could not be stored in the stash: ' . $e->getMessage(), 'stashzerolength' );
603 break;
604 case 'UploadStashNotLoggedInException':
605 $this->dieUsage( 'Not logged in: ' . $e->getMessage(), 'stashnotloggedin' );
606 break;
607 case 'UploadStashWrongOwnerException':
608 $this->dieUsage( 'Wrong owner: ' . $e->getMessage(), 'stashwrongowner' );
609 break;
610 case 'UploadStashNoSuchKeyException':
611 $this->dieUsage( 'No such filekey: ' . $e->getMessage(), 'stashnosuchfilekey' );
612 break;
613 default:
614 $this->dieUsage( $exceptionType . ": " . $e->getMessage(), 'stasherror' );
615 break;
616 }
617 }
618
619 /**
620 * Perform the actual upload. Returns a suitable result array on success;
621 * dies on failure.
622 *
623 * @param array $warnings Array of Api upload warnings
624 * @return array
625 */
626 protected function performUpload( $warnings ) {
627 // Use comment as initial page text by default
628 if ( is_null( $this->mParams['text'] ) ) {
629 $this->mParams['text'] = $this->mParams['comment'];
630 }
631
632 /** @var $file File */
633 $file = $this->mUpload->getLocalFile();
634
635 // For preferences mode, we want to watch if 'watchdefault' is set or
636 // if the *file* doesn't exist and 'watchcreations' is set. But
637 // getWatchlistValue()'s automatic handling checks if the *title*
638 // exists or not, so we need to check both prefs manually.
639 $watch = $this->getWatchlistValue(
640 $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
641 );
642 if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
643 $watch = $this->getWatchlistValue(
644 $this->mParams['watchlist'], $file->getTitle(), 'watchcreations'
645 );
646 }
647
648 // Deprecated parameters
649 if ( $this->mParams['watch'] ) {
650 $this->logFeatureUsage( 'action=upload&watch' );
651 $watch = true;
652 }
653
654 // No errors, no warnings: do the upload
655 if ( $this->mParams['async'] ) {
656 $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
657 if ( $progress && $progress['result'] === 'Poll' ) {
658 $this->dieUsage( "Upload from stash already in progress.", 'publishfailed' );
659 }
660 UploadBase::setSessionStatus(
661 $this->getUser(),
662 $this->mParams['filekey'],
663 array( 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() )
664 );
665 JobQueueGroup::singleton()->push( new PublishStashedFileJob(
666 Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
667 array(
668 'filename' => $this->mParams['filename'],
669 'filekey' => $this->mParams['filekey'],
670 'comment' => $this->mParams['comment'],
671 'text' => $this->mParams['text'],
672 'watch' => $watch,
673 'session' => $this->getContext()->exportSession()
674 )
675 ) );
676 $result['result'] = 'Poll';
677 $result['stage'] = 'queued';
678 } else {
679 /** @var $status Status */
680 $status = $this->mUpload->performUpload( $this->mParams['comment'],
681 $this->mParams['text'], $watch, $this->getUser() );
682
683 if ( !$status->isGood() ) {
684 $error = $status->getErrorsArray();
685
686 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
687 // The upload can not be performed right now, because the user
688 // requested so
689 return array(
690 'result' => 'Queued',
691 'statuskey' => $error[0][1],
692 );
693 }
694
695 $this->getResult()->setIndexedTagName( $error, 'error' );
696 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
697 }
698 $result['result'] = 'Success';
699 }
700
701 $result['filename'] = $file->getName();
702 if ( $warnings && count( $warnings ) > 0 ) {
703 $result['warnings'] = $warnings;
704 }
705
706 return $result;
707 }
708
709 /**
710 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
711 */
712 protected function checkAsyncDownloadEnabled() {
713 if ( !$this->getConfig()->get( 'AllowAsyncCopyUploads' ) ) {
714 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled' );
715 }
716 }
717
718 public function mustBePosted() {
719 return true;
720 }
721
722 public function isWriteMode() {
723 return true;
724 }
725
726 public function getAllowedParams() {
727 $params = array(
728 'filename' => array(
729 ApiBase::PARAM_TYPE => 'string',
730 ),
731 'comment' => array(
732 ApiBase::PARAM_DFLT => ''
733 ),
734 'text' => null,
735 'watch' => array(
736 ApiBase::PARAM_DFLT => false,
737 ApiBase::PARAM_DEPRECATED => true,
738 ),
739 'watchlist' => array(
740 ApiBase::PARAM_DFLT => 'preferences',
741 ApiBase::PARAM_TYPE => array(
742 'watch',
743 'preferences',
744 'nochange'
745 ),
746 ),
747 'ignorewarnings' => false,
748 'file' => array(
749 ApiBase::PARAM_TYPE => 'upload',
750 ),
751 'url' => null,
752 'filekey' => null,
753 'sessionkey' => array(
754 ApiBase::PARAM_DFLT => null,
755 ApiBase::PARAM_DEPRECATED => true,
756 ),
757 'stash' => false,
758
759 'filesize' => null,
760 'offset' => null,
761 'chunk' => array(
762 ApiBase::PARAM_TYPE => 'upload',
763 ),
764
765 'async' => false,
766 'asyncdownload' => false,
767 'leavemessage' => false,
768 'statuskey' => null,
769 'checkstatus' => false,
770 );
771
772 return $params;
773 }
774
775 public function needsToken() {
776 return 'csrf';
777 }
778
779 protected function getExamplesMessages() {
780 return array(
781 'action=upload&filename=Wiki.png' .
782 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
783 => 'apihelp-upload-example-url',
784 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
785 => 'apihelp-upload-example-filekey',
786 );
787 }
788
789 public function getHelpUrls() {
790 return 'https://www.mediawiki.org/wiki/API:Upload';
791 }
792 }