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