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" );
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 $this->getMain()->isWriteMode();
44 $this->mParams
= $this->extractRequestParams();
45 $request = $this->getMain()->getRequest();
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' ) );
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 // One and only one of the following parameters is needed
61 $this->requireOnlyOneParameter( $this->mParams
,
62 'sessionkey', 'file', 'url', 'enablechunks' );
64 if ( $this->mParams
['sessionkey'] ) {
66 * Upload stashed in a previous request
68 // Check the session key
69 if ( !isset( $_SESSION['wsUploadData'][$this->mParams
['sessionkey']] ) )
70 return $this->dieUsageMsg( array( 'invalid-session-key' ) );
72 $this->mUpload
= new UploadFromStash();
73 $this->mUpload
->initialize( $this->mParams
['filename'],
74 $_SESSION['wsUploadData'][$this->mParams
['sessionkey']] );
77 * Upload from url, etc
78 * Parameter filename is required
80 if ( !isset( $this->mParams
['filename'] ) )
81 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
83 // Initialize $this->mUpload
84 if ( $this->mParams
['enablechunks'] ) {
85 $this->mUpload
= new UploadFromChunks();
86 $this->mUpload
->initialize(
87 $request->getText( 'done' ),
88 $request->getText( 'filename' ),
89 $request->getText( 'chunksessionkey' ),
90 $request->getFileTempName( 'chunk' ),
91 $request->getFileSize( 'chunk' ),
92 $request->getSessionData( 'wsUploadData' )
95 if ( !$this->mUpload
->status
->isOK() ) {
96 return $this->dieUsageMsg( $this->mUpload
->status
->getWikiText(),
99 } elseif ( isset( $this->mParams
['file'] ) ) {
100 $this->mUpload
= new UploadFromFile();
101 $this->mUpload
->initialize(
102 $this->mParams
['filename'],
103 $request->getFileTempName( 'file' ),
104 $request->getFileSize( 'file' )
106 } elseif ( isset( $this->mParams
['url'] ) ) {
107 // make sure upload by url is enabled:
108 if ( !$wgAllowCopyUploads )
109 $this->dieUsageMsg( array( 'uploaddisabled' ) );
111 // make sure the current user can upload
112 if ( ! $wgUser->isAllowed( 'upload_by_url' ) )
113 $this->dieUsageMsg( array( 'badaccess-groups' ) );
115 $this->mUpload
= new UploadFromUrl();
116 $this->mUpload
->initialize( $this->mParams
['filename'],
117 $this->mParams
['url'] );
119 $status = $this->mUpload
->fetchFile();
120 if ( !$status->isOK() ) {
121 return $this->dieUsage( $status->getWikiText(), 'fetchfileerror' );
126 if ( !isset( $this->mUpload
) )
127 $this->dieUsage( 'No upload module set', 'nomodule' );
130 // Finish up the exec command:
131 $this->doExecUpload();
134 protected function doExecUpload() {
136 // Check whether the user has the appropriate permissions to upload anyway
137 $permission = $this->mUpload
->isAllowed( $wgUser );
139 if ( $permission !== true ) {
140 if ( !$wgUser->isLoggedIn() )
141 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
143 $this->dieUsageMsg( array( 'badaccess-groups' ) );
145 // Perform the upload
146 $result = $this->performUpload();
147 // Cleanup any temporary mess
148 // FIXME: This should be in a try .. finally block with performUpload
149 $this->mUpload
->cleanupTempFile();
150 $this->getResult()->addValue( null, $this->getModuleName(), $result );
153 protected function performUpload() {
156 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
157 if ( $permErrors !== true ) {
158 $this->dieUsageMsg( array( 'badaccess-groups' ) );
161 // TODO: Move them to ApiBase's message map
162 $verification = $this->mUpload
->verifyUpload();
163 if ( $verification['status'] !== UploadBase
::OK
) {
164 $result['result'] = 'Failure';
165 switch( $verification['status'] ) {
166 case UploadBase
::EMPTY_FILE
:
167 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
169 case UploadBase
::FILETYPE_MISSING
:
170 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
172 case UploadBase
::FILETYPE_BADTYPE
:
173 global $wgFileExtensions;
174 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
176 'filetype' => $verification['finalExt'],
177 'allowed' => $wgFileExtensions
180 case UploadBase
::MIN_LENGTH_PARTNAME
:
181 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
183 case UploadBase
::ILLEGAL_FILENAME
:
184 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
185 0, array( 'filename' => $verification['filtered'] ) );
187 case UploadBase
::OVERWRITE_EXISTING_FILE
:
188 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
190 case UploadBase
::VERIFICATION_ERROR
:
191 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
192 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
193 0, array( 'details' => $verification['details'] ) );
195 case UploadBase
::HOOK_ABORTED
:
196 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
197 'hookaborted', 0, array( 'error' => $verification['error'] ) );
200 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
201 0, array( 'code' => $verification['status'] ) );
206 if ( !$this->mParams
['ignorewarnings'] ) {
207 $warnings = $this->mUpload
->checkWarnings();
210 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
212 if ( isset( $warnings['duplicate'] ) ) {
214 foreach ( $warnings['duplicate'] as $key => $dupe )
215 $dupes[] = $dupe->getName();
216 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
217 $warnings['duplicate'] = $dupes;
221 if ( isset( $warnings['exists'] ) ) {
222 $warning = $warnings['exists'];
223 unset( $warnings['exists'] );
224 $warnings[$warning['warning']] = $warning['file']->getName();
227 $result['result'] = 'Warning';
228 $result['warnings'] = $warnings;
230 $sessionKey = $this->mUpload
->stashSession();
232 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
234 $result['sessionkey'] = $sessionKey;
240 // Use comment as initial page text by default
241 if ( is_null( $this->mParams
['text'] ) )
242 $this->mParams
['text'] = $this->mParams
['comment'];
244 // No errors, no warnings: do the upload
245 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
246 $this->mParams
['text'], $this->mParams
['watch'], $wgUser );
248 if ( !$status->isGood() ) {
249 $error = $status->getErrorsArray();
250 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
252 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
255 $file = $this->mUpload
->getLocalFile();
256 $result['result'] = 'Success';
257 $result['filename'] = $file->getName();
259 // Append imageinfo to the result
260 $imParam = ApiQueryImageInfo
::getPropertyNames();
261 $result['imageinfo'] = ApiQueryImageInfo
::getInfo( $file,
262 array_flip( $imParam ), $this->getResult() );
267 public function mustBePosted() {
271 public function isWriteMode() {
275 public function getAllowedParams() {
279 ApiBase
::PARAM_DFLT
=> ''
284 'ignorewarnings' => false,
286 'enablechunks' => false,
287 'chunksessionkey' => null,
291 'sessionkey' => null,
294 if ( $this->getMain()->isInternalMode() )
295 $params['internalhttpsession'] = null;
300 public function getParamDescription() {
302 'filename' => 'Target filename',
303 'token' => 'Edit token. You can get one of these through prop=info',
304 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
305 'text' => 'Initial page text for new files',
306 'watch' => 'Watch the page',
307 'ignorewarnings' => 'Ignore any warnings',
308 'file' => 'File contents',
309 'enablechunks' => 'Set to use chunk mode; see http://firefogg.org/dev/chunk_post.html for protocol',
310 'chunksessionkey' => 'The session key, established on the first contact during the chunked upload',
311 'chunk' => 'The data in this chunk of a chunked upload',
312 'done' => 'Set to 1 on the last chunk of a chunked upload',
313 'url' => 'Url to fetch the file from',
314 'sessionkey' => array(
315 'Session key returned by a previous upload that failed due to warnings',
320 public function getDescription() {
322 'Upload a file, or get the status of pending uploads. Several methods are available:',
323 ' * Upload file contents directly, using the "file" parameter',
324 ' * Upload a file in chunks, using the "enablechunks",',
325 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
326 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
327 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
328 'sending the "file" or "chunk" parameters. Note also that queries using session keys must be',
329 'done in the same login session as the query that originally returned the key (i.e. do not',
330 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff.'
334 protected function getExamples() {
336 'Upload from a URL:',
337 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
338 'Complete an upload that failed due to warnings:',
339 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
340 'Begin a chunked upload:',
341 ' api.php?action=upload&filename=Wiki.png&enablechunks=1'
345 public function getVersion() {
346 return __CLASS__
. ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';