Follow-up r70037: Fix ApiUpload by passing a WebRequestUpload to the the initializer
[lhc/web/wiklou.git] / includes / api / ApiUpload.php
1 <?php
2 /**
3 * Created on Aug 21, 2008
4 * API for MediaWiki 1.8+
5 *
6 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 */
23
24 if ( !defined( 'MEDIAWIKI' ) ) {
25 // Eclipse helper - will be ignored in production
26 require_once( "ApiBase.php" );
27 }
28
29 /**
30 * @ingroup API
31 */
32 class ApiUpload extends ApiBase {
33 protected $mUpload = null;
34 protected $mParams;
35
36 public function __construct( $main, $action ) {
37 parent::__construct( $main, $action );
38 }
39
40 public function execute() {
41 global $wgUser, $wgAllowCopyUploads;
42
43 // Check whether upload is enabled
44 if ( !UploadBase::isEnabled() ) {
45 $this->dieUsageMsg( array( 'uploaddisabled' ) );
46 }
47
48 $this->mParams = $this->extractRequestParams();
49 $request = $this->getMain()->getRequest();
50
51 // Add the uploaded file to the params array
52 $this->mParams['file'] = $request->getFileName( 'file' );
53
54 // One and only one of the following parameters is needed
55 $this->requireOnlyOneParameter( $this->mParams,
56 'sessionkey', 'file', 'url' );
57 // And this one is needed
58 if ( !isset( $this->mParams['filename'] ) ) {
59 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
60 }
61
62
63 if ( $this->mParams['sessionkey'] ) {
64 // Upload stashed in a previous request
65 $sessionData = $request->getSessionData( UploadBase::SESSION_KEYNAME );
66 if ( !UploadFromStash::isValidSessionKey( $this->mParams['sessionkey'], $sessionData ) ) {
67 $this->dieUsageMsg( array( 'invalid-session-key' ) );
68 }
69
70 $this->mUpload = new UploadFromStash();
71 $this->mUpload->initialize( $this->mParams['filename'],
72 $this->mParams['sessionkey'],
73 $sessionData[$this->mParams['sessionkey']] );
74
75
76 } elseif ( isset( $this->mParams['file'] ) ) {
77 $this->mUpload = new UploadFromFile();
78 $this->mUpload->initialize(
79 $this->mParams['filename'],
80 $request->getUpload( 'file' )
81 );
82 } elseif ( isset( $this->mParams['url'] ) ) {
83 // Make sure upload by URL is enabled:
84 if ( !$wgAllowCopyUploads ) {
85 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
86 }
87
88 $this->mUpload = new UploadFromUrl;
89 $async = $this->mParams['asyncdownload'] ? 'async' : null;
90 $this->checkPermissions( $wgUser );
91
92 $result = $this->mUpload->initialize(
93 $this->mParams['filename'],
94 $this->mParams['url'],
95 $this->mParams['comment'],
96 $this->mParams['watchlist'],
97 $this->mParams['ignorewarnings'],
98 $async );
99
100 if ( $async ) {
101 $this->getResult()->addValue( null,
102 $this->getModuleName(),
103 array( 'queued' => $result ) );
104 return;
105 }
106
107 $status = $this->mUpload->retrieveFileFromUrl();
108 if ( !$status->isGood() ) {
109 $this->getResult()->addValue( null,
110 $this->getModuleName(),
111 array( 'error' => $status ) );
112 return;
113 }
114 }
115
116
117 $this->checkPermissions( $wgUser );
118
119 if ( !isset( $this->mUpload ) ) {
120 $this->dieUsage( 'No upload module set', 'nomodule' );
121 }
122
123 // Perform the upload
124 $result = $this->performUpload();
125
126 // Cleanup any temporary mess
127 $this->mUpload->cleanupTempFile();
128
129 $this->getResult()->addValue( null, $this->getModuleName(), $result );
130 }
131
132 /**
133 * Checks that the user has permissions to perform this upload.
134 * Dies with usage message on inadequate permissions.
135 * @param $user User The user to check.
136 */
137 protected function checkPermissions( $user ) {
138 // Check whether the user has the appropriate permissions to upload anyway
139 $permission = $this->mUpload->isAllowed( $user );
140
141 if ( $permission !== true ) {
142 if ( !$user->isLoggedIn() ) {
143 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
144 } else {
145 $this->dieUsageMsg( array( 'badaccess-groups' ) );
146 }
147 }
148 }
149
150 /**
151 * Performs file verification, dies on error.
152 */
153 public function verifyUpload( ) {
154 $verification = $this->mUpload->verifyUpload( );
155 if ( $verification['status'] === UploadBase::OK ) {
156 return $verification;
157 }
158
159 $this->getVerificationError( $verification );
160 }
161
162 /**
163 * Produce the usage error
164 *
165 * @param $verification array an associative array with the status
166 * key
167 */
168 public function getVerificationError( $verification ) {
169 // TODO: Move them to ApiBase's message map
170 switch( $verification['status'] ) {
171 case UploadBase::EMPTY_FILE:
172 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
173 break;
174 case UploadBase::FILE_TOO_LARGE:
175 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
176 break;
177 case UploadBase::FILETYPE_MISSING:
178 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
179 break;
180 case UploadBase::FILETYPE_BADTYPE:
181 global $wgFileExtensions;
182 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
183 0, array(
184 'filetype' => $verification['finalExt'],
185 'allowed' => $wgFileExtensions
186 ) );
187 break;
188 case UploadBase::MIN_LENGTH_PARTNAME:
189 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
190 break;
191 case UploadBase::ILLEGAL_FILENAME:
192 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
193 0, array( 'filename' => $verification['filtered'] ) );
194 break;
195 case UploadBase::OVERWRITE_EXISTING_FILE:
196 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
197 break;
198 case UploadBase::VERIFICATION_ERROR:
199 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
200 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
201 0, array( 'details' => $verification['details'] ) );
202 break;
203 case UploadBase::HOOK_ABORTED:
204 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
205 'hookaborted', 0, array( 'error' => $verification['error'] ) );
206 break;
207 default:
208 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
209 0, array( 'code' => $verification['status'] ) );
210 break;
211 }
212 }
213
214 protected function checkForWarnings() {
215 $result = array();
216
217 if ( !$this->mParams['ignorewarnings'] ) {
218 $warnings = $this->mUpload->checkWarnings();
219 if ( $warnings ) {
220 // Add indices
221 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
222
223 if ( isset( $warnings['duplicate'] ) ) {
224 $dupes = array();
225 foreach ( $warnings['duplicate'] as $key => $dupe )
226 $dupes[] = $dupe->getName();
227 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
228 $warnings['duplicate'] = $dupes;
229 }
230
231 if ( isset( $warnings['exists'] ) ) {
232 $warning = $warnings['exists'];
233 unset( $warnings['exists'] );
234 $warnings[$warning['warning']] = $warning['file']->getName();
235 }
236
237 $result['result'] = 'Warning';
238 $result['warnings'] = $warnings;
239
240 $sessionKey = $this->mUpload->stashSession();
241 if ( !$sessionKey ) {
242 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
243 }
244
245 $result['sessionkey'] = $sessionKey;
246
247 return $result;
248 }
249 }
250 return;
251 }
252
253 protected function performUpload() {
254 global $wgUser;
255 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
256 if ( $permErrors !== true ) {
257 $this->dieUsageMsg( array( 'badaccess-groups' ) );
258 }
259
260 $this->verifyUpload();
261
262 $warnings = $this->checkForWarnings();
263 if ( isset( $warnings ) ) {
264 return $warnings;
265 }
266
267 // Use comment as initial page text by default
268 if ( is_null( $this->mParams['text'] ) ) {
269 $this->mParams['text'] = $this->mParams['comment'];
270 }
271
272 $file = $this->mUpload->getLocalFile();
273 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
274
275 // Deprecated parameters
276 if ( $this->mParams['watch'] ) {
277 $watch = true;
278 }
279
280 // No errors, no warnings: do the upload
281 $status = $this->mUpload->performUpload( $this->mParams['comment'],
282 $this->mParams['text'], $watch, $wgUser );
283
284 if ( !$status->isGood() ) {
285 $error = $status->getErrorsArray();
286 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
287
288 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
289 }
290
291 $file = $this->mUpload->getLocalFile();
292
293 $result['result'] = 'Success';
294 $result['filename'] = $file->getName();
295 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
296
297 return $result;
298 }
299
300 public function mustBePosted() {
301 return true;
302 }
303
304 public function isWriteMode() {
305 return true;
306 }
307
308 public function getAllowedParams() {
309 $params = array(
310 'filename' => null,
311 'comment' => array(
312 ApiBase::PARAM_DFLT => ''
313 ),
314 'text' => null,
315 'token' => null,
316 'watch' => array(
317 ApiBase::PARAM_DFLT => false,
318 ApiBase::PARAM_DEPRECATED => true,
319 ),
320 'watchlist' => array(
321 ApiBase::PARAM_DFLT => 'preferences',
322 ApiBase::PARAM_TYPE => array(
323 'watch',
324 'preferences',
325 'nochange'
326 ),
327 ),
328 'ignorewarnings' => false,
329 'file' => null,
330 'url' => null,
331 'asyncdownload' => false,
332 'sessionkey' => null,
333 );
334 return $params;
335 }
336
337 public function getParamDescription() {
338 return array(
339 'filename' => 'Target filename',
340 'token' => 'Edit token. You can get one of these through prop=info',
341 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
342 'text' => 'Initial page text for new files',
343 'watch' => 'Watch the page',
344 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
345 'ignorewarnings' => 'Ignore any warnings',
346 'file' => 'File contents',
347 'url' => 'Url to fetch the file from',
348 'asyncdownload' => 'Make fetching a URL asyncronous',
349 'sessionkey' => array(
350 'Session key returned by a previous upload that failed due to warnings',
351 ),
352 );
353 }
354
355 public function getDescription() {
356 return array(
357 'Upload a file, or get the status of pending uploads. Several methods are available:',
358 ' * Upload file contents directly, using the "file" parameter',
359 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
360 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
361 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
362 'sending the "file". Note also that queries using session keys must be',
363 'done in the same login session as the query that originally returned the key (i.e. do not',
364 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
365 );
366 }
367
368 public function getPossibleErrors() {
369 return array_merge( parent::getPossibleErrors(), array(
370 array( 'uploaddisabled' ),
371 array( 'invalid-session-key' ),
372 array( 'uploaddisabled' ),
373 array( 'badaccess-groups' ),
374 array( 'missingparam', 'filename' ),
375 array( 'mustbeloggedin', 'upload' ),
376 array( 'badaccess-groups' ),
377 array( 'badaccess-groups' ),
378 array( 'code' => 'fetchfileerror', 'info' => '' ),
379 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
380 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
381 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
382 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
383 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
384 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
385 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
386 ) );
387 }
388
389 public function getTokenSalt() {
390 return '';
391 }
392
393 protected function getExamples() {
394 return array(
395 'Upload from a URL:',
396 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
397 'Complete an upload that failed due to warnings:',
398 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
399 );
400 }
401
402 public function getVersion() {
403 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';
404 }
405 }