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