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