Was occassionally failing due to race condition caused by mt_rand behaviour:
[mediawiki.git] / includes / api / ApiUpload.php
blob62ff21aa72c415a4ab848635956beafde8c4402f
1 <?php
2 /*
3 * Created on Aug 21, 2008
4 * API for MediaWiki 1.8+
6 * Copyright (C) 2008 - 2009 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
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.
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.
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
24 if ( !defined( 'MEDIAWIKI' ) ) {
25 // Eclipse helper - will be ignored in production
26 require_once("ApiBase.php");
29 /**
30 * @ingroup API
32 class ApiUpload extends ApiBase {
33 var $mUpload = null;
35 public function __construct( $main, $action ) {
36 parent::__construct( $main, $action );
39 public function execute() {
40 global $wgUser;
42 $this->getMain()->isWriteMode();
43 $this->mParams = $this->extractRequestParams();
44 $request = $this->getMain()->getRequest();
46 // do token checks:
47 if( is_null( $this->mParams['token'] ) )
48 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
49 if( !$wgUser->matchEditToken( $this->mParams['token'] ) )
50 $this->dieUsageMsg( array( 'sessionfailure' ) );
53 // Add the uploaded file to the params array
54 $this->mParams['file'] = $request->getFileName( 'file' );
56 // Check whether upload is enabled
57 if( !UploadBase::isEnabled() )
58 $this->dieUsageMsg( array( 'uploaddisabled' ) );
60 wfDebug( __METHOD__ . "running require param\n" );
61 // One and only one of the following parameters is needed
62 $this->requireOnlyOneParameter( $this->mParams,
63 'sessionkey', 'file', 'url', 'enablechunks' );
65 if( $this->mParams['enablechunks'] ){
66 // chunks upload enabled
67 $this->mUpload = new UploadFromChunks();
68 $this->mUpload->initializeFromParams( $this->mParams, $request );
70 //if getAPIresult did not exit report the status error:
71 if( isset( $this->mUpload->status['error'] ) )
72 $this->dieUsageMsg( $this->mUpload->status['error'] );
74 } else if( $this->mParams['internalhttpsession'] ){
75 $sd = & $_SESSION['wsDownload'][ $this->mParams['internalhttpsession'] ];
77 wfDebug("InternalHTTP:: " . print_r($this->mParams, true));
78 // get the params from the init session:
79 $this->mUpload = new UploadFromFile();
81 $this->mUpload->initialize( $this->mParams['filename'],
82 $sd['target_file_path'],
83 filesize( $sd['target_file_path'] )
86 if( !isset( $this->mUpload ) )
87 $this->dieUsage( 'No upload module set', 'nomodule' );
89 } else if( $this->mParams['httpstatus'] && $this->mParams['sessionkey'] ){
90 // return the status of the given upload session_key:
91 if( !isset( $_SESSION['wsDownload'][ $this->mParams['sessionkey'] ] ) ){
92 return $this->dieUsageMsg( array( 'invalid-session-key' ) );
94 $sd = & $_SESSION['wsDownload'][$this->mParams['sessionkey']];
95 // keep passing down the upload sessionkey
96 $statusResult = array(
97 'upload_session_key' => $this->mParams['sessionkey']
100 // put values into the final apiResult if available
101 if( isset( $sd['apiUploadResult'] ) ) $statusResult['apiUploadResult'] = $sd['apiUploadResult'];
102 if( isset( $sd['loaded'] ) ) $statusResult['loaded'] = $sd['loaded'];
103 if( isset( $sd['content_length'] ) ) $statusResult['content_length'] = $sd['content_length'];
105 return $this->getResult()->addValue( null, $this->getModuleName(),
106 $statusResult
108 } else if( $this->mParams['sessionkey'] ) {
109 // Stashed upload
110 $this->mUpload = new UploadFromStash();
111 $this->mUpload->initialize( $this->mParams['filename'], $_SESSION['wsUploadData'][$this->mParams['sessionkey']] );
112 } else {
113 // Upload from url or file
114 // Parameter filename is required
115 if( !isset( $this->mParams['filename'] ) )
116 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
118 // Initialize $this->mUpload
119 if( isset( $this->mParams['file'] ) ) {
120 $this->mUpload = new UploadFromFile();
121 $this->mUpload->initialize(
122 $request->getFileName( 'file' ),
123 $request->getFileTempName( 'file' ),
124 $request->getFileSize( 'file' )
126 } elseif( isset( $this->mParams['url'] ) ) {
128 $this->mUpload = new UploadFromUrl();
129 $this->mUpload->initialize( $this->mParams['filename'], $this->mParams['url'], $this->mParams['asyncdownload'] );
131 $status = $this->mUpload->fetchFile();
132 if( !$status->isOK() ){
133 return $this->dieUsage( 'fetchfileerror', $status->getWikiText() );
135 //check if we doing a async request set session info and return the upload_session_key)
136 if( $this->mUpload->isAsync() ){
137 $upload_session_key = $status->value;
138 // update the session with anything with the params we will need to finish up the upload later on:
139 if( !isset( $_SESSION['wsDownload'][$upload_session_key] ) )
140 $_SESSION['wsDownload'][$upload_session_key] = array();
142 $sd =& $_SESSION['wsDownload'][$upload_session_key];
144 // copy mParams for finishing up after:
145 $sd['mParams'] = $this->mParams;
147 return $this->getResult()->addValue( null, $this->getModuleName(),
148 array( 'upload_session_key' => $upload_session_key
151 //else the file downloaded in place continue with validation:
155 if( !isset( $this->mUpload ) )
156 $this->dieUsage( 'No upload module set', 'nomodule' );
158 //finish up the exec command:
159 $this->doExecUpload();
162 function doExecUpload(){
163 global $wgUser;
164 // Check whether the user has the appropriate permissions to upload anyway
165 $permission = $this->mUpload->isAllowed( $wgUser );
167 if( $permission !== true ) {
168 if( !$wgUser->isLoggedIn() )
169 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
170 else
171 $this->dieUsageMsg( array( 'badaccess-groups' ) );
173 // Perform the upload
174 $result = $this->performUpload();
175 // Cleanup any temporary mess
176 $this->mUpload->cleanupTempFile();
177 $this->getResult()->addValue( null, $this->getModuleName(), $result );
180 private function performUpload() {
181 global $wgUser;
182 $result = array();
183 $resultDetails = null;
184 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
185 if( $permErrors !== true ) {
186 $result['result'] = 'Failure';
187 $result['error'] = 'permission-denied';
188 return $result;
190 $verification = $this->mUpload->verifyUpload( $resultDetails );
191 if( $verification != UploadBase::OK ) {
192 $result['result'] = 'Failure';
193 switch( $verification ) {
194 case UploadBase::EMPTY_FILE:
195 $result['error'] = 'empty-file';
196 break;
197 case UploadBase::FILETYPE_MISSING:
198 $result['error'] = 'filetype-missing';
199 break;
200 case UploadBase::FILETYPE_BADTYPE:
201 global $wgFileExtensions;
202 $result['error'] = 'filetype-banned';
203 $result['filetype'] = $resultDetails['finalExt'];
204 $result['allowed-filetypes'] = $wgFileExtensions;
205 break;
206 case UploadBase::MIN_LENGHT_PARTNAME:
207 $result['error'] = 'filename-tooshort';
208 break;
209 case UploadBase::ILLEGAL_FILENAME:
210 $result['error'] = 'illegal-filename';
211 $result['filename'] = $resultDetails['filtered'];
212 break;
213 case UploadBase::OVERWRITE_EXISTING_FILE:
214 $result['error'] = 'overwrite';
215 break;
216 case UploadBase::VERIFICATION_ERROR:
217 $result['error'] = 'verification-error';
218 $args = $resultDetails['veri'];
219 $code = array_shift( $args );
220 $result['verification-error'] = $code;
221 $result['args'] = $args;
222 $this->getResult()->setIndexedTagName( $result['args'], 'arg' );
223 break;
224 case UploadBase::UPLOAD_VERIFICATION_ERROR:
225 $result['error'] = 'upload-verification-error';
226 $result['upload-verification-error'] = $resultDetails['error'];
227 break;
228 default:
229 $result['error'] = 'unknown-error';
230 $result['code'] = $verification;
231 break;
233 return $result;
236 if( !$this->mParams['ignorewarnings'] ) {
237 $warnings = $this->mUpload->checkWarnings();
238 if( $warnings ) {
239 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
241 $result['result'] = 'Warning';
242 $result['warnings'] = $warnings;
243 if( isset( $result['filewasdeleted'] ) )
244 $result['filewasdeleted'] = $result['filewasdeleted']->getDBkey();
246 $sessionKey = $this->mUpload->stashSession();
247 if( $sessionKey )
248 $result['sessionkey'] = $sessionKey;
249 return $result;
253 // do the upload
254 $status = $this->mUpload->performUpload( $this->mParams['comment'],
255 $this->mParams['comment'], $this->mParams['watch'], $wgUser );
257 if( !$status->isGood() ) {
258 $result['result'] = 'Failure';
259 $result['error'] = 'internal-error';
260 $result['details'] = $status->getErrorsArray();
261 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
262 return $result;
265 $file = $this->mUpload->getLocalFile();
266 $result['result'] = 'Success';
267 $result['filename'] = $file->getName();
269 // Append imageinfo to the result
271 // might be a cleaner way to call this:
272 $imParam = ApiQueryImageInfo::getAllowedParams();
273 $imProp = $imParam['prop'][ApiBase::PARAM_TYPE];
274 $result['imageinfo'] = ApiQueryImageInfo::getInfo( $file,
275 array_flip( $imProp ),
276 $this->getResult() );
278 return $result;
281 public function mustBePosted() {
282 return true;
285 public function isWriteMode() {
286 return true;
289 public function getAllowedParams() {
290 return array(
291 'filename' => null,
292 'comment' => array(
293 ApiBase::PARAM_DFLT => ''
295 'token' => null,
296 'watch' => false,
297 'ignorewarnings' => false,
298 'file' => null,
299 'enablechunks' => null,
300 'chunksessionkey' => null,
301 'chunk' => null,
302 'done' => false,
303 'url' => null,
304 'asyncdownload' => false,
305 'httpstatus' => false,
306 'sessionkey' => null,
307 'internalhttpsession' => null,
311 public function getParamDescription() {
312 return array(
313 'filename' => 'Target filename',
314 'token' => 'Edit token. You can get one of these through prop=info',
315 'comment' => 'Upload comment. Also used as the initial page text for new files',
316 'watch' => 'Watch the page',
317 'ignorewarnings' => 'Ignore any warnings',
318 'file' => 'File contents',
319 'enablechunks' => 'Set to use chunk mode; see http://firefogg.org/dev/chunk_post.html for protocol',
320 'chunksessionkey' => 'Used to sync uploading of chunks',
321 'chunk' => 'Chunk contents',
322 'done' => 'Set when the last chunk is being uploaded',
323 'url' => 'Url to fetch the file from',
324 'asyncdownload' => 'Set to download the url asynchronously. Useful for large files that will take more than php max_execution_time to download',
325 'httpstatus' => 'Set to return the status of an asynchronous upload (specify the key in sessionkey)',
326 'sessionkey' => array(
327 'Session key returned by a previous upload that failed due to warnings, or',
328 '(with httpstatus) The upload_session_key of an asynchronous upload',
330 'internalhttpsession' => 'Used internally',
334 public function getDescription() {
335 return array(
336 'Upload a file, or get the status of pending uploads. Several methods are available:',
337 ' * Upload file contents directly, using the "file" parameter',
338 ' * Upload a file in chunks, using the "enablechunks", "chunk", and "chunksessionkey", and "done" parameters',
339 ' * Have the MediaWiki server fetch a file from a URL, using the "url" and "asyncdownload" parameters',
340 ' * Retrieve the status of an asynchronous upload, using the "httpstatus" and "sessionkey" parameters',
341 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
342 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
343 'sending the "file" or "chunk" parameters. Note also that queries using session keys must be',
344 'done in the same login session as the query that originally returned the key (i.e. do not',
345 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff.'
349 protected function getExamples() {
350 return array(
351 'Upload from a URL:',
352 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
353 'Get the status of an asynchronous upload:',
354 ' api.php?action=upload&filename=Wiki.png&httpstatus=1&sessionkey=upload_session_key',
355 'Complete an upload that failed due to warnings:',
356 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
357 'Begin a chunked upload:',
358 ' api.php?action=upload&filename=Wiki.png&enablechunks=1'
362 public function getVersion() {
363 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';