3 * Created on Aug 21, 2008
4 * API for MediaWiki 1.8+
6 * Copyright (C) 2008 - 2010 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" );
32 class ApiUpload
extends ApiBase
{
33 protected $mUpload = null;
36 public function __construct( $main, $action ) {
37 parent
::__construct( $main, $action );
40 public function execute() {
41 global $wgUser, $wgAllowCopyUploads;
43 // Check whether upload is enabled
44 if ( !UploadBase
::isEnabled() )
45 $this->dieUsageMsg( array( 'uploaddisabled' ) );
47 $this->mParams
= $this->extractRequestParams();
48 $request = $this->getMain()->getRequest();
51 if ( is_null( $this->mParams
['token'] ) )
52 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
53 if ( !$wgUser->matchEditToken( $this->mParams
['token'] ) )
54 $this->dieUsageMsg( array( 'sessionfailure' ) );
56 // Add the uploaded file to the params array
57 $this->mParams
['file'] = $request->getFileName( 'file' );
59 // One and only one of the following parameters is needed
60 $this->requireOnlyOneParameter( $this->mParams
,
61 'sessionkey', 'file', 'url', 'enablechunks' );
63 // Initialize $this->mUpload
64 if ( $this->mParams
['enablechunks'] ) {
65 $this->mUpload
= new UploadFromChunks();
67 $this->mUpload
->initialize(
68 $request->getVal( 'done', null ),
69 $request->getVal( 'filename', null ),
70 $request->getVal( 'chunksession', null ),
71 $request->getFileTempName( 'chunk' ),
72 $request->getFileSize( 'chunk' ),
73 $request->getSessionData( 'wsUploadData' )
76 if ( !$this->mUpload
->status
->isOK() ) {
77 return $this->dieUsageMsg( $this->mUpload
->status
->getErrorsArray() );
79 } elseif ( $this->mParams
['sessionkey'] ) {
81 * Upload stashed in a previous request
83 // Check the session key
84 if ( !isset( $_SESSION['wsUploadData'][$this->mParams
['sessionkey']] ) )
85 return $this->dieUsageMsg( array( 'invalid-session-key' ) );
87 $this->mUpload
= new UploadFromStash();
88 $this->mUpload
->initialize( $this->mParams
['filename'],
89 $_SESSION['wsUploadData'][$this->mParams
['sessionkey']] );
90 } elseif ( isset( $this->mParams
['filename'] ) ) {
92 * Upload from url, etc
93 * Parameter filename is required
96 if ( isset( $this->mParams
['file'] ) ) {
97 $this->mUpload
= new UploadFromFile();
98 $this->mUpload
->initialize(
99 $this->mParams
['filename'],
100 $request->getFileTempName( 'file' ),
101 $request->getFileSize( 'file' )
103 } elseif ( isset( $this->mParams
['url'] ) ) {
104 // make sure upload by url is enabled:
105 if ( !$wgAllowCopyUploads )
106 $this->dieUsageMsg( array( 'uploaddisabled' ) );
108 // make sure the current user can upload
109 if ( ! $wgUser->isAllowed( 'upload_by_url' ) )
110 $this->dieUsageMsg( array( 'badaccess-groups' ) );
112 $this->mUpload
= new UploadFromUrl();
113 $this->mUpload
->initialize( $this->mParams
['filename'],
114 $this->mParams
['url'] );
116 $status = $this->mUpload
->fetchFile();
117 if ( !$status->isOK() ) {
118 return $this->dieUsage( $status->getWikiText(), 'fetchfileerror' );
121 } else $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
123 if ( !isset( $this->mUpload
) )
124 $this->dieUsage( 'No upload module set', 'nomodule' );
126 // Check whether the user has the appropriate permissions to upload anyway
127 $permission = $this->mUpload
->isAllowed( $wgUser );
129 if ( $permission !== true ) {
130 if ( !$wgUser->isLoggedIn() )
131 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
133 $this->dieUsageMsg( array( 'badaccess-groups' ) );
135 // Perform the upload
136 $result = $this->performUpload();
138 // Cleanup any temporary mess
139 $this->mUpload
->cleanupTempFile();
141 if( isset($result['chunked-output']) ) {
142 foreach ($result['chunked-output'] as $key => $value) {
143 if($value === null) $value = "";
144 $this->getResult()->addValue( null, $key, $value );
147 $this->getResult()->addValue( null, $this->getModuleName(), $result );
151 protected function performUpload() {
154 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
155 if ( $permErrors !== true ) {
156 $this->dieUsageMsg( array( 'badaccess-groups' ) );
159 // TODO: Move them to ApiBase's message map
160 $verification = $this->mUpload
->verifyUpload();
161 if ( $verification['status'] !== UploadBase
::OK
) {
162 $result['result'] = 'Failure';
163 switch( $verification['status'] ) {
164 case UploadBase
::EMPTY_FILE
:
165 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
167 case UploadBase
::FILETYPE_MISSING
:
168 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
170 case UploadBase
::FILETYPE_BADTYPE
:
171 global $wgFileExtensions;
172 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
174 'filetype' => $verification['finalExt'],
175 'allowed' => $wgFileExtensions
178 case UploadBase
::MIN_LENGTH_PARTNAME
:
179 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
181 case UploadBase
::ILLEGAL_FILENAME
:
182 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
183 0, array( 'filename' => $verification['filtered'] ) );
185 case UploadBase
::OVERWRITE_EXISTING_FILE
:
186 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
188 case UploadBase
::VERIFICATION_ERROR
:
189 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
190 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
191 0, array( 'details' => $verification['details'] ) );
193 case UploadBase
::HOOK_ABORTED
:
194 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
195 'hookaborted', 0, array( 'error' => $verification['error'] ) );
198 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
199 0, array( 'code' => $verification['status'] ) );
204 if ( !$this->mParams
['ignorewarnings'] ) {
205 $warnings = $this->mUpload
->checkWarnings();
208 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
210 if ( isset( $warnings['duplicate'] ) ) {
212 foreach ( $warnings['duplicate'] as $key => $dupe )
213 $dupes[] = $dupe->getName();
214 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
215 $warnings['duplicate'] = $dupes;
219 if ( isset( $warnings['exists'] ) ) {
220 $warning = $warnings['exists'];
221 unset( $warnings['exists'] );
222 $warnings[$warning['warning']] = $warning['file']->getName();
225 $result['result'] = 'Warning';
226 $result['warnings'] = $warnings;
228 $sessionKey = $this->mUpload
->stashSession();
230 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
232 $result['sessionkey'] = $sessionKey;
238 // Use comment as initial page text by default
239 if ( is_null( $this->mParams
['text'] ) )
240 $this->mParams
['text'] = $this->mParams
['comment'];
242 // No errors, no warnings: do the upload
243 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
244 $this->mParams
['text'], $this->mParams
['watch'], $wgUser );
246 if ( !$status->isGood() ) {
247 $error = $status->getErrorsArray();
248 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
250 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
251 } elseif( $this->mParams
['enablechunks'] ) {
252 return array("chunked-output" => $status->value
);
255 $file = $this->mUpload
->getLocalFile();
256 $result['result'] = 'Success';
257 $result['filename'] = $file->getName();
258 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
263 public function mustBePosted() {
267 public function isWriteMode() {
271 public function getAllowedParams() {
275 ApiBase
::PARAM_DFLT
=> ''
280 'ignorewarnings' => false,
282 'enablechunks' => null, /* must be null to work with requireOnlyOneParameter */
283 'chunksession' => null,
287 'sessionkey' => null,
290 if ( $this->getMain()->isInternalMode() )
291 $params['internalhttpsession'] = null;
296 public function getParamDescription() {
298 'filename' => 'Target filename',
299 'token' => 'Edit token. You can get one of these through prop=info',
300 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
301 'text' => 'Initial page text for new files',
302 'watch' => 'Watch the page',
303 'ignorewarnings' => 'Ignore any warnings',
304 'file' => 'File contents',
305 'enablechunks' => 'Set to use chunk mode; see http://firefogg.org/dev/chunk_post.html for protocol',
306 'chunksession' => 'The session key, established on the first contact during the chunked upload',
307 'chunk' => 'The data in this chunk of a chunked upload',
308 'done' => 'Set to 1 on the last chunk of a chunked upload',
309 'url' => 'Url to fetch the file from',
310 'sessionkey' => array(
311 'Session key returned by a previous upload that failed due to warnings',
316 public function getDescription() {
318 'Upload a file, or get the status of pending uploads. Several methods are available:',
319 ' * Upload file contents directly, using the "file" parameter',
320 ' * Upload a file in chunks, using the "enablechunks",',
321 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
322 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
323 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
324 'sending the "file" or "chunk" parameters. Note also that queries using session keys must be',
325 'done in the same login session as the query that originally returned the key (i.e. do not',
326 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff.'
330 public function getPossibleErrors() {
331 return array_merge( parent
::getPossibleErrors(), array(
332 array( 'uploaddisabled' ),
333 array( 'missingparam', 'token' ),
334 array( 'sessionfailure' ),
335 array( 'invalid-session-key' ),
336 array( 'uploaddisabled' ),
337 array( 'badaccess-groups' ),
338 array( 'missingparam', 'filename' ),
339 array( 'mustbeloggedin', 'upload' ),
340 array( 'badaccess-groups' ),
341 array( 'badaccess-groups' ),
342 array( 'code' => 'fetchfileerror', 'info' => '' ),
343 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
344 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
345 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
346 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
347 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
348 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
349 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
353 protected function getExamples() {
355 'Upload from a URL:',
356 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
357 'Complete an upload that failed due to warnings:',
358 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
359 'Begin a chunked upload:',
360 ' api.php?action=upload&filename=Wiki.png&enablechunks=1'
364 public function getVersion() {
365 return __CLASS__
. ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';