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