b101ecc672900c103bed505cdee8b3a9ab4435d5
[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 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( "ApiBase.php" );
30 }
31
32 /**
33 * @ingroup API
34 */
35 class ApiUpload extends ApiBase {
36
37 /**
38 * @var UploadBase
39 */
40 protected $mUpload = null;
41
42 protected $mParams;
43
44 public function __construct( $main, $action ) {
45 parent::__construct( $main, $action );
46 }
47
48 public function execute() {
49 global $wgUser;
50
51 // Check whether upload is enabled
52 if ( !UploadBase::isEnabled() ) {
53 $this->dieUsageMsg( 'uploaddisabled' );
54 }
55
56 // Parameter handling
57 $this->mParams = $this->extractRequestParams();
58 $request = $this->getMain()->getRequest();
59 // Add the uploaded file to the params array
60 $this->mParams['file'] = $request->getFileName( 'file' );
61
62 // Copy the session key to the file key, for backward compatibility.
63 if( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
64 $this->mParams['filekey'] = $this->mParams['sessionkey'];
65 }
66
67 // Select an upload module
68 if ( !$this->selectUploadModule() ) {
69 // This is not a true upload, but a status request or similar
70 return;
71 }
72 if ( !isset( $this->mUpload ) ) {
73 $this->dieUsage( 'No upload module set', 'nomodule' );
74 }
75
76 // First check permission to upload
77 $this->checkPermissions( $wgUser );
78
79 // Fetch the file
80 $status = $this->mUpload->fetchFile();
81 if ( !$status->isGood() ) {
82 $errors = $status->getErrorsArray();
83 $error = array_shift( $errors[0] );
84 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
85 }
86
87 // Check if the uploaded file is sane
88 $this->verifyUpload();
89
90
91 // Check if the user has the rights to modify or overwrite the requested title
92 // (This check is irrelevant if stashing is already requested, since the errors
93 // can always be fixed by changing the title)
94 if ( ! $this->mParams['stash'] ) {
95 $permErrors = $this->mUpload->verifyTitlePermissions( $wgUser );
96 if ( $permErrors !== true ) {
97 $this->dieRecoverableError( $permErrors[0], 'filename' );
98 }
99 }
100
101 // Prepare the API result
102 $result = array();
103
104 $warnings = $this->getApiWarnings();
105 if ( $warnings ) {
106 $result['result'] = 'Warning';
107 $result['warnings'] = $warnings;
108 // in case the warnings can be fixed with some further user action, let's stash this upload
109 // and return a key they can use to restart it
110 try {
111 $result['filekey'] = $this->performStash();
112 $result['sessionkey'] = $result['filekey']; // backwards compatibility
113 } catch ( MWException $e ) {
114 $result['warnings']['stashfailed'] = $e->getMessage();
115 }
116 } elseif ( $this->mParams['stash'] ) {
117 // Some uploads can request they be stashed, so as not to publish them immediately.
118 // In this case, a failure to stash ought to be fatal
119 try {
120 $result['result'] = 'Success';
121 $result['filekey'] = $this->performStash();
122 $result['sessionkey'] = $result['filekey']; // backwards compatibility
123 } catch ( MWException $e ) {
124 $this->dieUsage( $e->getMessage(), 'stashfailed' );
125 }
126 } else {
127 // This is the most common case -- a normal upload with no warnings
128 // $result will be formatted properly for the API already, with a status
129 $result = $this->performUpload();
130 }
131
132 if ( $result['result'] === 'Success' ) {
133 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
134 }
135
136 $this->getResult()->addValue( null, $this->getModuleName(), $result );
137
138 // Cleanup any temporary mess
139 $this->mUpload->cleanupTempFile();
140 }
141
142 /**
143 * Stash the file and return the file key
144 * Also re-raises exceptions with slightly more informative message strings (useful for API)
145 * @throws MWException
146 * @return String file key
147 */
148 function performStash() {
149 try {
150 xdebug_break();
151 $fileKey = $this->mUpload->stashFile()->getFileKey();
152 } catch ( MWException $e ) {
153 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
154 wfDebug( __METHOD__ . ' ' . $message . "\n");
155 throw new MWException( $message );
156 }
157 return $fileKey;
158 }
159
160 /**
161 * Throw an error that the user can recover from by providing a better
162 * value for $parameter
163 *
164 * @param $error array Error array suitable for passing to dieUsageMsg()
165 * @param $parameter string Parameter that needs revising
166 * @param $data array Optional extra data to pass to the user
167 * @throws UsageException
168 */
169 function dieRecoverableError( $error, $parameter, $data = array() ) {
170 try {
171 $data['filekey'] = $this->performStash();
172 $data['sessionkey'] = $data['filekey'];
173 } catch ( MWException $e ) {
174 $data['stashfailed'] = $e->getMessage();
175 }
176 $data['invalidparameter'] = $parameter;
177
178 $parsed = $this->parseMsg( $error );
179 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
180 }
181
182 /**
183 * Select an upload module and set it to mUpload. Dies on failure. If the
184 * request was a status request and not a true upload, returns false;
185 * otherwise true
186 *
187 * @return bool
188 */
189 protected function selectUploadModule() {
190 $request = $this->getMain()->getRequest();
191
192 // One and only one of the following parameters is needed
193 $this->requireOnlyOneParameter( $this->mParams,
194 'filekey', 'file', 'url', 'statuskey' );
195
196 if ( $this->mParams['statuskey'] ) {
197 $this->checkAsyncDownloadEnabled();
198
199 // Status request for an async upload
200 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
201 if ( !isset( $sessionData['result'] ) ) {
202 $this->dieUsage( 'No result in session data', 'missingresult' );
203 }
204 if ( $sessionData['result'] == 'Warning' ) {
205 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
206 $sessionData['sessionkey'] = $this->mParams['statuskey'];
207 }
208 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
209 return false;
210
211 }
212
213 // The following modules all require the filename parameter to be set
214 if ( is_null( $this->mParams['filename'] ) ) {
215 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
216 }
217
218 if ( $this->mParams['filekey'] ) {
219 // Upload stashed in a previous request
220 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
221 $this->dieUsageMsg( 'invalid-file-key' );
222 }
223
224 // context allows access to the current user without creating new $wgUser references
225 $context = $this->createContext();
226 $this->mUpload = new UploadFromStash( $context->getUser() );
227 $this->mUpload->initialize( $this->mParams['filekey'], $this->mParams['filename'] );
228
229 } elseif ( isset( $this->mParams['file'] ) ) {
230 $this->mUpload = new UploadFromFile();
231 $this->mUpload->initialize(
232 $this->mParams['filename'],
233 $request->getUpload( 'file' )
234 );
235 } elseif ( isset( $this->mParams['url'] ) ) {
236 // Make sure upload by URL is enabled:
237 if ( !UploadFromUrl::isEnabled() ) {
238 $this->dieUsageMsg( 'copyuploaddisabled' );
239 }
240
241 $async = false;
242 if ( $this->mParams['asyncdownload'] ) {
243 $this->checkAsyncDownloadEnabled();
244
245 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
246 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
247 'missing-ignorewarnings' );
248 }
249
250 if ( $this->mParams['leavemessage'] ) {
251 $async = 'async-leavemessage';
252 } else {
253 $async = 'async';
254 }
255 }
256 $this->mUpload = new UploadFromUrl;
257 $this->mUpload->initialize( $this->mParams['filename'],
258 $this->mParams['url'], $async );
259
260 }
261
262 return true;
263 }
264
265 /**
266 * Checks that the user has permissions to perform this upload.
267 * Dies with usage message on inadequate permissions.
268 * @param $user User The user to check.
269 */
270 protected function checkPermissions( $user ) {
271 // Check whether the user has the appropriate permissions to upload anyway
272 $permission = $this->mUpload->isAllowed( $user );
273
274 if ( $permission !== true ) {
275 if ( !$user->isLoggedIn() ) {
276 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
277 } else {
278 $this->dieUsageMsg( 'badaccess-groups' );
279 }
280 }
281 }
282
283 /**
284 * Performs file verification, dies on error.
285 */
286 protected function verifyUpload( ) {
287 global $wgFileExtensions;
288
289 $verification = $this->mUpload->verifyUpload( );
290 if ( $verification['status'] === UploadBase::OK ) {
291 return;
292 }
293
294 // TODO: Move them to ApiBase's message map
295 switch( $verification['status'] ) {
296 // Recoverable errors
297 case UploadBase::MIN_LENGTH_PARTNAME:
298 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
299 break;
300 case UploadBase::ILLEGAL_FILENAME:
301 $this->dieRecoverableError( 'illegal-filename', 'filename',
302 array( 'filename' => $verification['filtered'] ) );
303 break;
304 case UploadBase::FILETYPE_MISSING:
305 $this->dieRecoverableError( 'filetype-missing', 'filename' );
306 break;
307 case UploadBase::WINDOWS_NONASCII_FILENAME:
308 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
309 break;
310
311 // Unrecoverable errors
312 case UploadBase::EMPTY_FILE:
313 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
314 break;
315 case UploadBase::FILE_TOO_LARGE:
316 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
317 break;
318
319 case UploadBase::FILETYPE_BADTYPE:
320 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
321 0, array(
322 'filetype' => $verification['finalExt'],
323 'allowed' => $wgFileExtensions
324 ) );
325 break;
326 case UploadBase::VERIFICATION_ERROR:
327 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
328 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
329 0, array( 'details' => $verification['details'] ) );
330 break;
331 case UploadBase::HOOK_ABORTED:
332 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
333 'hookaborted', 0, array( 'error' => $verification['error'] ) );
334 break;
335 default:
336 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
337 0, array( 'code' => $verification['status'] ) );
338 break;
339 }
340 }
341
342
343 /**
344 * Check warnings if ignorewarnings is not set.
345 * Returns a suitable array for inclusion into API results if there were warnings
346 * Returns the empty array if there were no warnings
347 *
348 * @return array
349 */
350 protected function getApiWarnings() {
351 $warnings = array();
352
353 if ( !$this->mParams['ignorewarnings'] ) {
354 $warnings = $this->mUpload->checkWarnings();
355 }
356 return $this->transformWarnings( $warnings );
357 }
358
359 protected function transformWarnings( $warnings ) {
360 if ( $warnings ) {
361 // Add indices
362 $result = $this->getResult();
363 $result->setIndexedTagName( $warnings, 'warning' );
364
365 if ( isset( $warnings['duplicate'] ) ) {
366 $dupes = array();
367 foreach ( $warnings['duplicate'] as $dupe ) {
368 $dupes[] = $dupe->getName();
369 }
370 $result->setIndexedTagName( $dupes, 'duplicate' );
371 $warnings['duplicate'] = $dupes;
372 }
373
374 if ( isset( $warnings['exists'] ) ) {
375 $warning = $warnings['exists'];
376 unset( $warnings['exists'] );
377 $warnings[$warning['warning']] = $warning['file']->getName();
378 }
379 }
380 return $warnings;
381 }
382
383
384 /**
385 * Perform the actual upload. Returns a suitable result array on success;
386 * dies on failure.
387 */
388 protected function performUpload() {
389 global $wgUser;
390
391 // Use comment as initial page text by default
392 if ( is_null( $this->mParams['text'] ) ) {
393 $this->mParams['text'] = $this->mParams['comment'];
394 }
395
396 $file = $this->mUpload->getLocalFile();
397 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
398
399 // Deprecated parameters
400 if ( $this->mParams['watch'] ) {
401 $watch = true;
402 }
403
404 // No errors, no warnings: do the upload
405 $status = $this->mUpload->performUpload( $this->mParams['comment'],
406 $this->mParams['text'], $watch, $wgUser );
407
408 if ( !$status->isGood() ) {
409 $error = $status->getErrorsArray();
410
411 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
412 // The upload can not be performed right now, because the user
413 // requested so
414 return array(
415 'result' => 'Queued',
416 'statuskey' => $error[0][1],
417 );
418 } else {
419 $this->getResult()->setIndexedTagName( $error, 'error' );
420
421 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
422 }
423 }
424
425 $file = $this->mUpload->getLocalFile();
426
427 $result['result'] = 'Success';
428 $result['filename'] = $file->getName();
429
430 return $result;
431 }
432
433 /**
434 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
435 */
436 protected function checkAsyncDownloadEnabled() {
437 global $wgAllowAsyncCopyUploads;
438 if ( !$wgAllowAsyncCopyUploads ) {
439 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
440 }
441 }
442
443 public function mustBePosted() {
444 return true;
445 }
446
447 public function isWriteMode() {
448 return true;
449 }
450
451 public function getAllowedParams() {
452 $params = array(
453 'filename' => array(
454 ApiBase::PARAM_TYPE => 'string',
455 ),
456 'comment' => array(
457 ApiBase::PARAM_DFLT => ''
458 ),
459 'text' => null,
460 'token' => null,
461 'watch' => array(
462 ApiBase::PARAM_DFLT => false,
463 ApiBase::PARAM_DEPRECATED => true,
464 ),
465 'watchlist' => array(
466 ApiBase::PARAM_DFLT => 'preferences',
467 ApiBase::PARAM_TYPE => array(
468 'watch',
469 'preferences',
470 'nochange'
471 ),
472 ),
473 'ignorewarnings' => false,
474 'file' => null,
475 'url' => null,
476 'filekey' => null,
477 'sessionkey' => array(
478 ApiBase::PARAM_DFLT => null,
479 ApiBase::PARAM_DEPRECATED => true,
480 ),
481 'stash' => false,
482
483 'asyncdownload' => false,
484 'leavemessage' => false,
485 'statuskey' => null,
486 );
487
488 return $params;
489 }
490
491 public function getParamDescription() {
492 $params = array(
493 'filename' => 'Target filename',
494 'token' => 'Edit token. You can get one of these through prop=info',
495 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
496 'text' => 'Initial page text for new files',
497 'watch' => 'Watch the page',
498 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
499 'ignorewarnings' => 'Ignore any warnings',
500 'file' => 'File contents',
501 'url' => 'Url to fetch the file from',
502 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
503 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
504 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
505
506 'asyncdownload' => 'Make fetching a URL asynchronous',
507 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
508 'statuskey' => 'Fetch the upload status for this file key',
509 );
510
511 return $params;
512
513 }
514
515 public function getDescription() {
516 return array(
517 'Upload a file, or get the status of pending uploads. Several methods are available:',
518 ' * Upload file contents directly, using the "file" parameter',
519 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
520 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
521 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
522 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
523 );
524 }
525
526 public function getPossibleErrors() {
527 return array_merge( parent::getPossibleErrors(),
528 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
529 array(
530 array( 'uploaddisabled' ),
531 array( 'invalid-file-key' ),
532 array( 'uploaddisabled' ),
533 array( 'mustbeloggedin', 'upload' ),
534 array( 'badaccess-groups' ),
535 array( 'code' => 'fetchfileerror', 'info' => '' ),
536 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
537 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
538 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
539 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
540 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
541 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
542 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
543 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
544 )
545 );
546 }
547
548 public function needsToken() {
549 return true;
550 }
551
552 public function getTokenSalt() {
553 return '';
554 }
555
556 protected function getExamples() {
557 return array(
558 'Upload from a URL:',
559 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
560 'Complete an upload that failed due to warnings:',
561 ' api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1',
562 );
563 }
564
565 public function getVersion() {
566 return __CLASS__ . ': $Id$';
567 }
568 }