9ba52eaa9bbf8cda90085a4f9e8272cadbe800fd
[lhc/web/wiklou.git] / includes / api / ApiUpload.php
1 <?php
2 /**
3 * API for MediaWiki 1.8+
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 $this->selectUploadModule();
59 if ( !isset( $this->mUpload ) ) {
60 $this->dieUsage( 'No upload module set', 'nomodule' );
61 }
62
63 // First check permission to upload
64 $this->checkPermissions( $wgUser );
65
66 // Fetch the file
67 $status = $this->mUpload->fetchFile();
68 if ( !$status->isGood() ) {
69 $errors = $status->getErrorsArray();
70 $error = array_shift( $errors[0] );
71 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
72 }
73
74 // Check if the uploaded file is sane
75 $this->verifyUpload();
76
77 // Check permission to upload this file
78 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
79 if ( $permErrors !== true ) {
80 // Todo: stash the upload and allow choosing a new name
81 $this->dieUsageMsg( array( 'badaccess-groups' ) );
82 }
83
84 // Check warnings if necessary
85 $warnings = $this->checkForWarnings();
86 if ( $warnings ) {
87 $this->getResult()->addValue( null, $this->getModuleName(), $warnings );
88 } else {
89 // Perform the upload
90 $result = $this->performUpload();
91 $this->getResult()->addValue( null, $this->getModuleName(), $result );
92 }
93
94 // Cleanup any temporary mess
95 $this->mUpload->cleanupTempFile();
96 }
97
98 /**
99 * Select an upload module and set it to mUpload. Dies on failure.
100 */
101 protected function selectUploadModule() {
102 $request = $this->getMain()->getRequest();
103
104 // One and only one of the following parameters is needed
105 $this->requireOnlyOneParameter( $this->mParams,
106 'sessionkey', 'file', 'url' );
107
108 if ( $this->mParams['sessionkey'] ) {
109 // Upload stashed in a previous request
110 $sessionData = $request->getSessionData( UploadBase::getSessionKeyName() );
111 if ( !UploadFromStash::isValidSessionKey( $this->mParams['sessionkey'], $sessionData ) ) {
112 $this->dieUsageMsg( array( 'invalid-session-key' ) );
113 }
114
115 $this->mUpload = new UploadFromStash();
116 $this->mUpload->initialize( $this->mParams['filename'],
117 $this->mParams['sessionkey'],
118 $sessionData[$this->mParams['sessionkey']] );
119
120
121 } elseif ( isset( $this->mParams['file'] ) ) {
122 $this->mUpload = new UploadFromFile();
123 $this->mUpload->initialize(
124 $this->mParams['filename'],
125 $request->getUpload( 'file' )
126 );
127 } elseif ( isset( $this->mParams['url'] ) ) {
128 // Make sure upload by URL is enabled:
129 if ( !UploadFromUrl::isEnabled() ) {
130 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
131 }
132
133 $async = false;
134 if ( $this->mParams['asyncdownload'] ) {
135 if ( $this->mParams['leavemessage'] ) {
136 $async = 'async-leavemessage';
137 } else {
138 $async = 'async';
139 }
140 }
141 $this->mUpload = new UploadFromUrl;
142 $this->mUpload->initialize( $this->mParams['filename'],
143 $this->mParams['url'], $async );
144
145 }
146 }
147
148 /**
149 * Checks that the user has permissions to perform this upload.
150 * Dies with usage message on inadequate permissions.
151 * @param $user User The user to check.
152 */
153 protected function checkPermissions( $user ) {
154 // Check whether the user has the appropriate permissions to upload anyway
155 $permission = $this->mUpload->isAllowed( $user );
156
157 if ( $permission !== true ) {
158 if ( !$user->isLoggedIn() ) {
159 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
160 } else {
161 $this->dieUsageMsg( array( 'badaccess-groups' ) );
162 }
163 }
164 }
165
166 /**
167 * Performs file verification, dies on error.
168 */
169 protected function verifyUpload( ) {
170 global $wgFileExtensions;
171
172 $verification = $this->mUpload->verifyUpload( );
173 if ( $verification['status'] === UploadBase::OK ) {
174 return;
175 }
176
177 // TODO: Move them to ApiBase's message map
178 switch( $verification['status'] ) {
179 case UploadBase::EMPTY_FILE:
180 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
181 break;
182 case UploadBase::FILE_TOO_LARGE:
183 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
184 break;
185 case UploadBase::FILETYPE_MISSING:
186 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
187 break;
188 case UploadBase::FILETYPE_BADTYPE:
189 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
190 0, array(
191 'filetype' => $verification['finalExt'],
192 'allowed' => $wgFileExtensions
193 ) );
194 break;
195 case UploadBase::MIN_LENGTH_PARTNAME:
196 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
197 break;
198 case UploadBase::ILLEGAL_FILENAME:
199 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
200 0, array( 'filename' => $verification['filtered'] ) );
201 break;
202 case UploadBase::VERIFICATION_ERROR:
203 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
204 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
205 0, array( 'details' => $verification['details'] ) );
206 break;
207 case UploadBase::HOOK_ABORTED:
208 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
209 'hookaborted', 0, array( 'error' => $verification['error'] ) );
210 break;
211 default:
212 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
213 0, array( 'code' => $verification['status'] ) );
214 break;
215 }
216 }
217
218 /**
219 * Check warnings if ignorewarnings is not set.
220 * Returns a suitable result array if there were warnings
221 */
222 protected function checkForWarnings() {
223 $result = array();
224
225 if ( !$this->mParams['ignorewarnings'] ) {
226 $warnings = $this->mUpload->checkWarnings();
227 if ( $warnings ) {
228 // Add indices
229 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
230
231 if ( isset( $warnings['duplicate'] ) ) {
232 $dupes = array();
233 foreach ( $warnings['duplicate'] as $key => $dupe )
234 $dupes[] = $dupe->getName();
235 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
236 $warnings['duplicate'] = $dupes;
237 }
238
239 if ( isset( $warnings['exists'] ) ) {
240 $warning = $warnings['exists'];
241 unset( $warnings['exists'] );
242 $warnings[$warning['warning']] = $warning['file']->getName();
243 }
244
245 $result['result'] = 'Warning';
246 $result['warnings'] = $warnings;
247
248 $sessionKey = $this->mUpload->stashSession();
249 if ( !$sessionKey ) {
250 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
251 }
252
253 $result['sessionkey'] = $sessionKey;
254
255 return $result;
256 }
257 }
258 return;
259 }
260
261 /**
262 * Perform the actual upload. Returns a suitable result array on success;
263 * dies on failure.
264 */
265 protected function performUpload() {
266 global $wgUser;
267
268 // Use comment as initial page text by default
269 if ( is_null( $this->mParams['text'] ) ) {
270 $this->mParams['text'] = $this->mParams['comment'];
271 }
272
273 $file = $this->mUpload->getLocalFile();
274 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
275
276 // Deprecated parameters
277 if ( $this->mParams['watch'] ) {
278 $watch = true;
279 }
280
281 // No errors, no warnings: do the upload
282 $status = $this->mUpload->performUpload( $this->mParams['comment'],
283 $this->mParams['text'], $watch, $wgUser );
284
285 if ( !$status->isGood() ) {
286 $error = $status->getErrorsArray();
287
288 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
289 // The upload can not be performed right now, because the user
290 // requested so
291 return array(
292 'result' => 'Queued',
293 'sessionkey' => $error[0][1],
294 );
295 } else {
296 $this->getResult()->setIndexedTagName( $error, 'error' );
297
298 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
299 }
300 }
301
302 $file = $this->mUpload->getLocalFile();
303
304 $result['result'] = 'Success';
305 $result['filename'] = $file->getName();
306 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
307
308 return $result;
309 }
310
311 public function mustBePosted() {
312 return true;
313 }
314
315 public function isWriteMode() {
316 return true;
317 }
318
319 public function getAllowedParams() {
320 $params = array(
321 'filename' => array(
322 ApiBase::PARAM_TYPE => 'string',
323 ApiBase::PARAM_REQUIRED => true
324 ),
325 'comment' => array(
326 ApiBase::PARAM_DFLT => ''
327 ),
328 'text' => null,
329 'token' => null,
330 'watch' => array(
331 ApiBase::PARAM_DFLT => false,
332 ApiBase::PARAM_DEPRECATED => true,
333 ),
334 'watchlist' => array(
335 ApiBase::PARAM_DFLT => 'preferences',
336 ApiBase::PARAM_TYPE => array(
337 'watch',
338 'preferences',
339 'nochange'
340 ),
341 ),
342 'ignorewarnings' => false,
343 'file' => null,
344 'url' => null,
345
346 'sessionkey' => null,
347 );
348
349 global $wgAllowAsyncCopyUploads;
350 if ( $wgAllowAsyncCopyUploads ) {
351 $params += array(
352 'asyncdownload' => false,
353 'leavemessage' => false,
354 );
355 }
356 return $params;
357 }
358
359 public function getParamDescription() {
360 $params = array(
361 'filename' => 'Target filename',
362 'token' => 'Edit token. You can get one of these through prop=info',
363 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
364 'text' => 'Initial page text for new files',
365 'watch' => 'Watch the page',
366 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
367 'ignorewarnings' => 'Ignore any warnings',
368 'file' => 'File contents',
369 'url' => 'Url to fetch the file from',
370 'sessionkey' => 'Session key returned by a previous upload that failed due to warnings',
371 );
372
373 global $wgAllowAsyncCopyUploads;
374 if ( $wgAllowAsyncCopyUploads ) {
375 $params += array(
376 'asyncdownload' => 'Make fetching a URL asynchronous',
377 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
378 );
379 }
380
381 return $params;
382
383 }
384
385 public function getDescription() {
386 return array(
387 'Upload a file, or get the status of pending uploads. Several methods are available:',
388 ' * Upload file contents directly, using the "file" parameter',
389 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
390 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
391 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
392 'sending the "file". Note also that queries using session keys must be',
393 'done in the same login session as the query that originally returned the key (i.e. do not',
394 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
395 );
396 }
397
398 public function getPossibleErrors() {
399 return array_merge( parent::getPossibleErrors(), array(
400 array( 'uploaddisabled' ),
401 array( 'invalid-session-key' ),
402 array( 'uploaddisabled' ),
403 array( 'badaccess-groups' ),
404 array( 'mustbeloggedin', 'upload' ),
405 array( 'badaccess-groups' ),
406 array( 'badaccess-groups' ),
407 array( 'code' => 'fetchfileerror', 'info' => '' ),
408 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
409 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
410 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
411 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
412 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
413 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
414 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
415 ) );
416 }
417
418 public function getTokenSalt() {
419 return '';
420 }
421
422 protected function getExamples() {
423 return array(
424 'Upload from a URL:',
425 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
426 'Complete an upload that failed due to warnings:',
427 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
428 );
429 }
430
431 public function getVersion() {
432 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';
433 }
434 }