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