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