Refactor some code out of execute into selectUploadModule. Fixed an undefined variable.
[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 // 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 // Check permission to upload this file
63 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
64 if ( $permErrors !== true ) {
65 // Todo: more specific error message
66 $this->dieUsageMsg( array( 'badaccess-groups' ) );
67 }
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 warnings if necessary
81 $warnings = $this->checkForWarnings();
82 if ( $warnings ) {
83 $this->getResult()->addValue( null, $this->getModuleName(), $warnings );
84 } else {
85 // Perform the upload
86 $result = $this->performUpload();
87 $this->getResult()->addValue( null, $this->getModuleName(), $result );
88 }
89
90 // Cleanup any temporary mess
91 $this->mUpload->cleanupTempFile();
92 }
93
94 /**
95 * Select an upload module and set it to mUpload. Dies on failure.
96 */
97 protected function selectUploadModule() {
98 $request = $this->getMain()->getRequest();
99
100 // One and only one of the following parameters is needed
101 $this->requireOnlyOneParameter( $this->mParams,
102 'sessionkey', 'file', 'url' );
103 // And this one is needed
104 if ( !isset( $this->mParams['filename'] ) ) {
105 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
106 }
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 $verification = $this->mUpload->verifyUpload( );
171 if ( $verification['status'] === UploadBase::OK ) {
172 return;
173 }
174
175 // TODO: Move them to ApiBase's message map
176 switch( $verification['status'] ) {
177 case UploadBase::EMPTY_FILE:
178 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
179 break;
180 case UploadBase::FILE_TOO_LARGE:
181 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
182 break;
183 case UploadBase::FILETYPE_MISSING:
184 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
185 break;
186 case UploadBase::FILETYPE_BADTYPE:
187 global $wgFileExtensions;
188 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
189 0, array(
190 'filetype' => $verification['finalExt'],
191 'allowed' => $wgFileExtensions
192 ) );
193 break;
194 case UploadBase::MIN_LENGTH_PARTNAME:
195 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
196 break;
197 case UploadBase::ILLEGAL_FILENAME:
198 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
199 0, array( 'filename' => $verification['filtered'] ) );
200 break;
201 case UploadBase::OVERWRITE_EXISTING_FILE:
202 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
203 break;
204 case UploadBase::VERIFICATION_ERROR:
205 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
206 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
207 0, array( 'details' => $verification['details'] ) );
208 break;
209 case UploadBase::HOOK_ABORTED:
210 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
211 'hookaborted', 0, array( 'error' => $verification['error'] ) );
212 break;
213 default:
214 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
215 0, array( 'code' => $verification['status'] ) );
216 break;
217 }
218 }
219
220 /**
221 * Check warnings if ignorewarnings is not set.
222 * Returns a suitable result array if there were warnings
223 */
224 protected function checkForWarnings() {
225 $result = array();
226
227 if ( !$this->mParams['ignorewarnings'] ) {
228 $warnings = $this->mUpload->checkWarnings();
229 if ( $warnings ) {
230 // Add indices
231 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
232
233 if ( isset( $warnings['duplicate'] ) ) {
234 $dupes = array();
235 foreach ( $warnings['duplicate'] as $key => $dupe )
236 $dupes[] = $dupe->getName();
237 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
238 $warnings['duplicate'] = $dupes;
239 }
240
241 if ( isset( $warnings['exists'] ) ) {
242 $warning = $warnings['exists'];
243 unset( $warnings['exists'] );
244 $warnings[$warning['warning']] = $warning['file']->getName();
245 }
246
247 $result['result'] = 'Warning';
248 $result['warnings'] = $warnings;
249
250 $sessionKey = $this->mUpload->stashSession();
251 if ( !$sessionKey ) {
252 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
253 }
254
255 $result['sessionkey'] = $sessionKey;
256
257 return $result;
258 }
259 }
260 return;
261 }
262
263 /**
264 * Perform the actual upload. Returns a suitable result array on success;
265 * dies on failure.
266 */
267 protected function performUpload() {
268 global $wgUser;
269
270 // Use comment as initial page text by default
271 if ( is_null( $this->mParams['text'] ) ) {
272 $this->mParams['text'] = $this->mParams['comment'];
273 }
274
275 $file = $this->mUpload->getLocalFile();
276 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
277
278 // Deprecated parameters
279 if ( $this->mParams['watch'] ) {
280 $watch = true;
281 }
282
283 // No errors, no warnings: do the upload
284 $status = $this->mUpload->performUpload( $this->mParams['comment'],
285 $this->mParams['text'], $watch, $wgUser );
286
287 if ( !$status->isGood() ) {
288 $error = $status->getErrorsArray();
289 $this->getResult()->setIndexedTagName( $error, 'error' );
290
291 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
292 }
293
294 $file = $this->mUpload->getLocalFile();
295
296 $result['result'] = 'Success';
297 $result['filename'] = $file->getName();
298 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
299
300 return $result;
301 }
302
303 public function mustBePosted() {
304 return true;
305 }
306
307 public function isWriteMode() {
308 return true;
309 }
310
311 public function getAllowedParams() {
312 $params = array(
313 'filename' => null,
314 'comment' => array(
315 ApiBase::PARAM_DFLT => ''
316 ),
317 'text' => null,
318 'token' => null,
319 'watch' => array(
320 ApiBase::PARAM_DFLT => false,
321 ApiBase::PARAM_DEPRECATED => true,
322 ),
323 'watchlist' => array(
324 ApiBase::PARAM_DFLT => 'preferences',
325 ApiBase::PARAM_TYPE => array(
326 'watch',
327 'preferences',
328 'nochange'
329 ),
330 ),
331 'ignorewarnings' => false,
332 'file' => null,
333 'url' => null,
334 'asyncdownload' => false,
335 'leavemessage' => false,
336 'sessionkey' => null,
337 );
338 return $params;
339 }
340
341 public function getParamDescription() {
342 return array(
343 'filename' => 'Target filename',
344 'token' => 'Edit token. You can get one of these through prop=info',
345 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
346 'text' => 'Initial page text for new files',
347 'watch' => 'Watch the page',
348 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
349 'ignorewarnings' => 'Ignore any warnings',
350 'file' => 'File contents',
351 'url' => 'Url to fetch the file from',
352 'asyncdownload' => 'Make fetching a URL asyncronous',
353 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
354 'sessionkey' => 'Session key returned by a previous upload that failed due to warnings',
355 );
356 }
357
358 public function getDescription() {
359 return array(
360 'Upload a file, or get the status of pending uploads. Several methods are available:',
361 ' * Upload file contents directly, using the "file" parameter',
362 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
363 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
364 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
365 'sending the "file". Note also that queries using session keys must be',
366 'done in the same login session as the query that originally returned the key (i.e. do not',
367 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
368 );
369 }
370
371 public function getPossibleErrors() {
372 return array_merge( parent::getPossibleErrors(), array(
373 array( 'uploaddisabled' ),
374 array( 'invalid-session-key' ),
375 array( 'uploaddisabled' ),
376 array( 'badaccess-groups' ),
377 array( 'missingparam', 'filename' ),
378 array( 'mustbeloggedin', 'upload' ),
379 array( 'badaccess-groups' ),
380 array( 'badaccess-groups' ),
381 array( 'code' => 'fetchfileerror', 'info' => '' ),
382 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
383 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
384 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
385 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
386 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
387 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
388 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
389 ) );
390 }
391
392 public function getTokenSalt() {
393 return '';
394 }
395
396 protected function getExamples() {
397 return array(
398 'Upload from a URL:',
399 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
400 'Complete an upload that failed due to warnings:',
401 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
402 );
403 }
404
405 public function getVersion() {
406 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';
407 }
408 }