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