c5ea2f790ef933fe2c117d5cf444c84dc8018e4f
[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;
42
43 // Check whether upload is enabled
44 if ( !UploadBase::isEnabled() ) {
45 $this->dieUsageMsg( array( 'uploaddisabled' ) );
46 }
47
48 // Parameter handling
49 $this->mParams = $this->extractRequestParams();
50 $request = $this->getMain()->getRequest();
51 // Add the uploaded file to the params array
52 $this->mParams['file'] = $request->getFileName( 'file' );
53
54 // Select an upload module
55 $this->selectUploadModule();
56 if ( !isset( $this->mUpload ) ) {
57 $this->dieUsage( 'No upload module set', 'nomodule' );
58 }
59
60 // First check permission to upload
61 $this->checkPermissions( $wgUser );
62
63 // Fetch the file
64 $status = $this->mUpload->fetchFile();
65 if ( !$status->isGood() ) {
66 $errors = $status->getErrorsArray();
67 $error = array_shift( $errors[0] );
68 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
69 }
70
71 // Check if the uploaded file is sane
72 $this->verifyUpload();
73
74 // Check permission to upload this file
75 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
76 if ( $permErrors !== true ) {
77 // Todo: stash the upload and allow choosing a new name
78 $this->dieUsageMsg( array( 'badaccess-groups' ) );
79 }
80
81 // Check warnings if necessary
82 $warnings = $this->checkForWarnings();
83 if ( $warnings ) {
84 $this->getResult()->addValue( null, $this->getModuleName(), $warnings );
85 } else {
86 // Perform the upload
87 $result = $this->performUpload();
88 $this->getResult()->addValue( null, $this->getModuleName(), $result );
89 }
90
91 // Cleanup any temporary mess
92 $this->mUpload->cleanupTempFile();
93 }
94
95 /**
96 * Select an upload module and set it to mUpload. Dies on failure.
97 */
98 protected function selectUploadModule() {
99 $request = $this->getMain()->getRequest();
100
101 // One and only one of the following parameters is needed
102 $this->requireOnlyOneParameter( $this->mParams,
103 'sessionkey', 'file', 'url' );
104 // And this one is needed
105 if ( !isset( $this->mParams['filename'] ) ) {
106 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
107 }
108
109 if ( $this->mParams['sessionkey'] ) {
110 // Upload stashed in a previous request
111 $sessionData = $request->getSessionData( UploadBase::getSessionKeyName() );
112 if ( !UploadFromStash::isValidSessionKey( $this->mParams['sessionkey'], $sessionData ) ) {
113 $this->dieUsageMsg( array( 'invalid-session-key' ) );
114 }
115
116 $this->mUpload = new UploadFromStash();
117 $this->mUpload->initialize( $this->mParams['filename'],
118 $this->mParams['sessionkey'],
119 $sessionData[$this->mParams['sessionkey']] );
120
121
122 } elseif ( isset( $this->mParams['file'] ) ) {
123 $this->mUpload = new UploadFromFile();
124 $this->mUpload->initialize(
125 $this->mParams['filename'],
126 $request->getUpload( 'file' )
127 );
128 } elseif ( isset( $this->mParams['url'] ) ) {
129 // Make sure upload by URL is enabled:
130 if ( !UploadFromUrl::isEnabled() ) {
131 $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
132 }
133
134 $async = false;
135 if ( $this->mParams['asyncdownload'] ) {
136 if ( $this->mParams['leavemessage'] ) {
137 $async = 'async-leavemessage';
138 } else {
139 $async = 'async';
140 }
141 }
142 $this->mUpload = new UploadFromUrl;
143 $this->mUpload->initialize( $this->mParams['filename'],
144 $this->mParams['url'], $async );
145
146 }
147 }
148
149 /**
150 * Checks that the user has permissions to perform this upload.
151 * Dies with usage message on inadequate permissions.
152 * @param $user User The user to check.
153 */
154 protected function checkPermissions( $user ) {
155 // Check whether the user has the appropriate permissions to upload anyway
156 $permission = $this->mUpload->isAllowed( $user );
157
158 if ( $permission !== true ) {
159 if ( !$user->isLoggedIn() ) {
160 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
161 } else {
162 $this->dieUsageMsg( array( 'badaccess-groups' ) );
163 }
164 }
165 }
166
167 /**
168 * Performs file verification, dies on error.
169 */
170 protected function verifyUpload( ) {
171 $verification = $this->mUpload->verifyUpload( );
172 if ( $verification['status'] === UploadBase::OK ) {
173 return;
174 }
175
176 // TODO: Move them to ApiBase's message map
177 switch( $verification['status'] ) {
178 case UploadBase::EMPTY_FILE:
179 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
180 break;
181 case UploadBase::FILE_TOO_LARGE:
182 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
183 break;
184 case UploadBase::FILETYPE_MISSING:
185 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
186 break;
187 case UploadBase::FILETYPE_BADTYPE:
188 global $wgFileExtensions;
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' => null,
322 'comment' => array(
323 ApiBase::PARAM_DFLT => ''
324 ),
325 'text' => null,
326 'token' => null,
327 'watch' => array(
328 ApiBase::PARAM_DFLT => false,
329 ApiBase::PARAM_DEPRECATED => true,
330 ),
331 'watchlist' => array(
332 ApiBase::PARAM_DFLT => 'preferences',
333 ApiBase::PARAM_TYPE => array(
334 'watch',
335 'preferences',
336 'nochange'
337 ),
338 ),
339 'ignorewarnings' => false,
340 'file' => null,
341 'url' => null,
342
343 'sessionkey' => null,
344 );
345
346 global $wgAllowAsyncCopyUploads;
347 if ( $wgAllowAsyncCopyUploads ) {
348 $params += array(
349 'asyncdownload' => false,
350 'leavemessage' => false,
351 );
352 }
353 return $params;
354 }
355
356 public function getParamDescription() {
357 $params = array(
358 'filename' => 'Target filename',
359 'token' => 'Edit token. You can get one of these through prop=info',
360 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
361 'text' => 'Initial page text for new files',
362 'watch' => 'Watch the page',
363 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
364 'ignorewarnings' => 'Ignore any warnings',
365 'file' => 'File contents',
366 'url' => 'Url to fetch the file from',
367 'sessionkey' => 'Session key returned by a previous upload that failed due to warnings',
368 );
369
370 global $wgAllowAsyncCopyUploads;
371 if ( $wgAllowAsyncCopyUploads ) {
372 $params += array(
373 'asyncdownload' => 'Make fetching a URL asynchronous',
374 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
375 );
376 }
377
378 return $params;
379
380 }
381
382 public function getDescription() {
383 return array(
384 'Upload a file, or get the status of pending uploads. Several methods are available:',
385 ' * Upload file contents directly, using the "file" parameter',
386 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
387 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
388 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
389 'sending the "file". Note also that queries using session keys must be',
390 'done in the same login session as the query that originally returned the key (i.e. do not',
391 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
392 );
393 }
394
395 public function getPossibleErrors() {
396 return array_merge( parent::getPossibleErrors(), array(
397 array( 'uploaddisabled' ),
398 array( 'invalid-session-key' ),
399 array( 'uploaddisabled' ),
400 array( 'badaccess-groups' ),
401 array( 'missingparam', 'filename' ),
402 array( 'mustbeloggedin', 'upload' ),
403 array( 'badaccess-groups' ),
404 array( 'badaccess-groups' ),
405 array( 'code' => 'fetchfileerror', 'info' => '' ),
406 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
407 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
408 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
409 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
410 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
411 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
412 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
413 ) );
414 }
415
416 public function getTokenSalt() {
417 return '';
418 }
419
420 protected function getExamples() {
421 return array(
422 'Upload from a URL:',
423 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
424 'Complete an upload that failed due to warnings:',
425 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
426 );
427 }
428
429 public function getVersion() {
430 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';
431 }
432 }