Rewrote Special:Upload to allow easier extension. Mostly backwards compatible towards...
[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 (C) 2008 - 2009 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;
42
43 $this->getMain()->isWriteMode();
44 $this->mParams = $this->extractRequestParams();
45 $request = $this->getMain()->getRequest();
46
47 // Do token checks:
48 if ( is_null( $this->mParams['token'] ) )
49 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
50 if ( !$wgUser->matchEditToken( $this->mParams['token'] ) )
51 $this->dieUsageMsg( array( 'sessionfailure' ) );
52
53
54 // Add the uploaded file to the params array
55 $this->mParams['file'] = $request->getFileName( 'file' );
56
57 // Check whether upload is enabled
58 if ( !UploadBase::isEnabled() )
59 $this->dieUsageMsg( array( 'uploaddisabled' ) );
60
61 // One and only one of the following parameters is needed
62 $this->requireOnlyOneParameter( $this->mParams,
63 'sessionkey', 'file', 'url', 'enablechunks' );
64
65 if ( $this->mParams['enablechunks'] ) {
66 /**
67 * Chunked upload mode
68 */
69
70 $this->mUpload = new UploadFromChunks();
71 $status = $this->mUpload->initializeFromParams( $this->mParams, $request );
72
73 if( isset( $status['error'] ) )
74 $this->dieUsageMsg( $status['error'] );
75
76 } elseif ( isset( $this->mParams['internalhttpsession'] ) && $this->mParams['internalhttpsession'] ) {
77 $sd = & $_SESSION['wsDownload'][ $this->mParams['internalhttpsession'] ];
78
79 //wfDebug("InternalHTTP:: " . print_r($this->mParams, true));
80 // get the params from the init session:
81 $this->mUpload = new UploadFromFile();
82
83 $this->mUpload->initialize( $this->mParams['filename'],
84 $sd['target_file_path'],
85 filesize( $sd['target_file_path'] )
86 );
87 } elseif ( $this->mParams['httpstatus'] && $this->mParams['sessionkey'] ) {
88 /**
89 * Return the status of the given background upload session_key:
90 */
91 // Check the session key
92 if( !isset( $_SESSION['wsDownload'][$this->mParams['sessionkey']] ) )
93 return $this->dieUsageMsg( array( 'invalid-session-key' ) );
94
95 $sd =& $_SESSION['wsDownload'][$this->mParams['sessionkey']];
96 // Keep passing down the upload sessionkey
97 $statusResult = array(
98 'upload_session_key' => $this->mParams['sessionkey']
99 );
100
101 // put values into the final apiResult if available
102 if( isset( $sd['apiUploadResult'] ) )
103 $statusResult['apiUploadResult'] = $sd['apiUploadResult'];
104 if( isset( $sd['loaded'] ) )
105 $statusResult['loaded'] = $sd['loaded'];
106 if( isset( $sd['content_length'] ) )
107 $statusResult['content_length'] = $sd['content_length'];
108
109 return $this->getResult()->addValue( null,
110 $this->getModuleName(), $statusResult );
111
112 } elseif( $this->mParams['sessionkey'] ) {
113 /**
114 * Upload stashed in a previous request
115 */
116 $this->mUpload = new UploadFromStash();
117 $this->mUpload->initialize( $this->mParams['filename'],
118 $_SESSION['wsUploadData'][$this->mParams['sessionkey']] );
119 } else {
120 /**
121 * Upload from url or file
122 * Parameter filename is required
123 */
124 if ( !isset( $this->mParams['filename'] ) )
125 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
126
127 // Initialize $this->mUpload
128 if ( isset( $this->mParams['file'] ) ) {
129 $this->mUpload = new UploadFromFile();
130 $this->mUpload->initialize(
131 $this->mParams['filename'],
132 $request->getFileTempName( 'file' ),
133 $request->getFileSize( 'file' )
134 );
135 } elseif ( isset( $this->mParams['url'] ) ) {
136 $this->mUpload = new UploadFromUrl();
137 $this->mUpload->initialize( $this->mParams['filename'],
138 $this->mParams['url'], $this->mParams['asyncdownload'] );
139
140 $status = $this->mUpload->fetchFile();
141 if( !$status->isOK() ) {
142 return $this->dieUsage( 'fetchfileerror', $status->getWikiText() );
143 }
144
145 // check if we doing a async request set session info and return the upload_session_key)
146 if( $this->mUpload->isAsync() ){
147 $upload_session_key = $status->value;
148 // update the session with anything with the params we will need to finish up the upload later on:
149 if( !isset( $_SESSION['wsDownload'][$upload_session_key] ) )
150 $_SESSION['wsDownload'][$upload_session_key] = array();
151
152 $sd =& $_SESSION['wsDownload'][$upload_session_key];
153
154 // copy mParams for finishing up after:
155 $sd['mParams'] = $this->mParams;
156
157 return $this->getResult()->addValue( null, $this->getModuleName(),
158 array( 'upload_session_key' => $upload_session_key
159 ));
160 }
161 }
162 }
163
164 if( !isset( $this->mUpload ) )
165 $this->dieUsage( 'No upload module set', 'nomodule' );
166
167
168 // Finish up the exec command:
169 $this->doExecUpload();
170
171 }
172
173 protected function doExecUpload(){
174 global $wgUser;
175 // Check whether the user has the appropriate permissions to upload anyway
176 $permission = $this->mUpload->isAllowed( $wgUser );
177
178 if( $permission !== true ) {
179 if( !$wgUser->isLoggedIn() )
180 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
181 else
182 $this->dieUsageMsg( array( 'badaccess-groups' ) );
183 }
184 // Perform the upload
185 $result = $this->performUpload();
186 // Cleanup any temporary mess
187 $this->mUpload->cleanupTempFile();
188 $this->getResult()->addValue( null, $this->getModuleName(), $result );
189 }
190
191 protected function performUpload() {
192 global $wgUser;
193 $result = array();
194 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
195 if( $permErrors !== true ) {
196 $this->dieUsageMsg( array( 'baddaccess-groups' ) );
197 }
198
199 // TODO: Move them to ApiBase's message map
200 $verification = $this->mUpload->verifyUpload();
201 if( $verification['status'] !== UploadBase::OK ) {
202 $result['result'] = 'Failure';
203 switch( $verification['status'] ) {
204 case UploadBase::EMPTY_FILE:
205 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
206 break;
207 case UploadBase::FILETYPE_MISSING:
208 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
209 break;
210 case UploadBase::FILETYPE_BADTYPE:
211 global $wgFileExtensions;
212 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
213 0, array(
214 'filetype' => $verification['finalExt'],
215 'allowed' => $wgFileExtensions
216 ) );
217 break;
218 case UploadBase::MIN_LENGHT_PARTNAME:
219 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
220 break;
221 case UploadBase::ILLEGAL_FILENAME:
222 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
223 0, array( 'filename' => $verification['filtered'] ) );
224 break;
225 case UploadBase::OVERWRITE_EXISTING_FILE:
226 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
227 break;
228 case UploadBase::VERIFICATION_ERROR:
229 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
230 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
231 0, array( 'details' => $verification['details'] ) );
232 break;
233 case UploadBase::HOOK_ABORTED:
234 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
235 'hookaborted', 0, array( 'error' => $verification['error'] ) );
236 break;
237 default:
238 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
239 0, array( 'code' => $verification['status'] ) );
240 break;
241 }
242 return $result;
243 }
244 if( !$this->mParams['ignorewarnings'] ) {
245 $warnings = $this->mUpload->checkWarnings();
246 if( $warnings ) {
247 // Add indices
248 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
249
250 if( isset( $warnings['duplicate'] ) ) {
251 $dupes = array();
252 foreach( $warnings['duplicate'] as $key => $dupe )
253 $dupes[] = $dupe->getName();
254 $this->getResult()->setIndexedTagName( $dupes, 'duplicate');
255 $warnings['duplicate'] = $dupes;
256 }
257
258
259 if( isset( $warnings['exists'] ) ) {
260 $warning = $warnings['exists'];
261 unset( $warnings['exists'] );
262 $warnings[$warning['warning']] = $warning['file']->getName();
263 }
264
265 $result['result'] = 'Warning';
266 $result['warnings'] = $warnings;
267
268 $sessionKey = $this->mUpload->stashSession();
269 if ( !$sessionKey )
270 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
271
272 $result['sessionkey'] = $sessionKey;
273
274 return $result;
275 }
276 }
277
278 // No errors, no warnings: do the upload
279 $status = $this->mUpload->performUpload( $this->mParams['comment'],
280 $this->mParams['comment'], $this->mParams['watch'], $wgUser );
281
282 if( !$status->isGood() ) {
283 $error = $status->getErrorsArray();
284 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
285
286 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
287 }
288
289 $file = $this->mUpload->getLocalFile();
290 $result['result'] = 'Success';
291 $result['filename'] = $file->getName();
292
293 // Append imageinfo to the result
294 $imParam = ApiQueryImageInfo::getPropertyNames();
295 $result['imageinfo'] = ApiQueryImageInfo::getInfo( $file,
296 array_flip( $imParam ), $this->getResult() );
297
298 return $result;
299 }
300
301 public function mustBePosted() {
302 return true;
303 }
304
305 public function isWriteMode() {
306 return true;
307 }
308
309 public function getAllowedParams() {
310 global $wgEnableAsyncDownload;
311 $params = array(
312 'filename' => null,
313 'comment' => array(
314 ApiBase::PARAM_DFLT => ''
315 ),
316 'token' => null,
317 'watch' => false,
318 'ignorewarnings' => false,
319 'file' => null,
320 'enablechunks' => null,
321 'chunksessionkey' => null,
322 'chunk' => null,
323 'done' => false,
324 'url' => null,
325 'httpstatus' => false,
326 'sessionkey' => null,
327 );
328
329 if ( $this->getMain()->isInternalMode() )
330 $params['internalhttpsession'] = null;
331 if($wgEnableAsyncDownload){
332 $params['asyncdownload'] = false;
333 }
334 return $params;
335
336 }
337
338 public function getParamDescription() {
339 return array(
340 'filename' => 'Target filename',
341 'token' => 'Edit token. You can get one of these through prop=info',
342 'comment' => 'Upload comment. Also used as the initial page text for new files',
343 'watch' => 'Watch the page',
344 'ignorewarnings' => 'Ignore any warnings',
345 'file' => 'File contents',
346 'enablechunks' => 'Set to use chunk mode; see http://firefogg.org/dev/chunk_post.html for protocol',
347 'chunksessionkey' => 'Used to sync uploading of chunks',
348 'chunk' => 'Chunk contents',
349 'done' => 'Set when the last chunk is being uploaded',
350 'url' => 'Url to fetch the file from',
351 'asyncdownload' => 'Set to download the url asynchronously. Useful for large files that will take more than php max_execution_time to download',
352 'httpstatus' => 'Set to return the status of an asynchronous upload (specify the key in sessionkey)',
353 'sessionkey' => array(
354 'Session key returned by a previous upload that failed due to warnings, or',
355 '(with httpstatus) The upload_session_key of an asynchronous upload',
356 ),
357 'internalhttpsession' => 'Used internally',
358 );
359 }
360
361 public function getDescription() {
362 return array(
363 'Upload a file, or get the status of pending uploads. Several methods are available:',
364 ' * Upload file contents directly, using the "file" parameter',
365 ' * Upload a file in chunks, using the "enablechunks", "chunk", and "chunksessionkey", and "done" parameters',
366 ' * Have the MediaWiki server fetch a file from a URL, using the "url" and "asyncdownload" parameters',
367 ' * Retrieve the status of an asynchronous upload, using the "httpstatus" and "sessionkey" parameters',
368 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
369 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
370 'sending the "file" or "chunk" parameters. Note also that queries using session keys must be',
371 'done in the same login session as the query that originally returned the key (i.e. do not',
372 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff.'
373 );
374 }
375
376 protected function getExamples() {
377 return array(
378 'Upload from a URL:',
379 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
380 'Get the status of an asynchronous upload:',
381 ' api.php?action=upload&filename=Wiki.png&httpstatus=1&sessionkey=upload_session_key',
382 'Complete an upload that failed due to warnings:',
383 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
384 'Begin a chunked upload:',
385 ' api.php?action=upload&filename=Wiki.png&enablechunks=1'
386 );
387 }
388
389 public function getVersion() {
390 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';
391 }
392 }
393
394