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' ) );
54 // Add the uploaded file to the params array
55 $this->mParams
['file'] = $request->getFileName( 'file' );
57 // Check whether upload is enabled
58 if ( !UploadBase
::isEnabled() )
59 $this->dieUsageMsg( array( 'uploaddisabled' ) );
61 // One and only one of the following parameters is needed
62 $this->requireOnlyOneParameter( $this->mParams
,
63 'sessionkey', 'file', 'url' );
65 if( $this->mParams
['sessionkey'] ) {
67 * Upload stashed in a previous request
69 // Check the session key
70 if( !isset( $_SESSION['wsUploadData'][$this->mParams
['sessionkey']] ) )
71 return $this->dieUsageMsg( array( 'invalid-session-key' ) );
73 $this->mUpload
= new UploadFromStash();
74 $this->mUpload
->initialize( $this->mParams
['filename'],
75 $_SESSION['wsUploadData'][$this->mParams
['sessionkey']] );
78 * Upload from url or file
79 * Parameter filename is required
81 if ( !isset( $this->mParams
['filename'] ) )
82 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
84 // Initialize $this->mUpload
85 if ( isset( $this->mParams
['file'] ) ) {
86 $this->mUpload
= new UploadFromFile();
87 $this->mUpload
->initialize(
88 $this->mParams
['filename'],
89 $request->getFileTempName( 'file' ),
90 $request->getFileSize( 'file' )
92 } elseif ( isset( $this->mParams
['url'] ) ) {
93 //make sure upload by url is enabled:
94 if( !$wgAllowCopyUploads )
95 $this->dieUsageMsg( array( 'uploaddisabled' ) );
97 //make sure the current user can upload
98 if(! $wgUser->isAllowed('upload_by_url') )
99 $this->dieUsageMsg( array( 'badaccess-groups' ) );
102 $this->mUpload
= new UploadFromUrl();
103 $this->mUpload
->initialize( $this->mParams
['filename'],
104 $this->mParams
['url'] );
106 $status = $this->mUpload
->fetchFile();
107 if( !$status->isOK() ) {
108 return $this->dieUsage( $status->getWikiText(), 'fetchfileerror' );
113 if( !isset( $this->mUpload
) )
114 $this->dieUsage( 'No upload module set', 'nomodule' );
117 // Finish up the exec command:
118 $this->doExecUpload();
122 protected function doExecUpload(){
124 // Check whether the user has the appropriate permissions to upload anyway
125 $permission = $this->mUpload
->isAllowed( $wgUser );
127 if( $permission !== true ) {
128 if( !$wgUser->isLoggedIn() )
129 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
131 $this->dieUsageMsg( array( 'badaccess-groups' ) );
133 // Perform the upload
134 $result = $this->performUpload();
135 // Cleanup any temporary mess
136 // FIXME: This should be in a try .. finally block with performUpload
137 $this->mUpload
->cleanupTempFile();
138 $this->getResult()->addValue( null, $this->getModuleName(), $result );
141 protected function performUpload() {
144 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
145 if( $permErrors !== true ) {
146 $this->dieUsageMsg( array( 'badaccess-groups' ) );
149 // TODO: Move them to ApiBase's message map
150 $verification = $this->mUpload
->verifyUpload();
151 if( $verification['status'] !== UploadBase
::OK
) {
152 $result['result'] = 'Failure';
153 switch( $verification['status'] ) {
154 case UploadBase
::EMPTY_FILE
:
155 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
157 case UploadBase
::FILETYPE_MISSING
:
158 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
160 case UploadBase
::FILETYPE_BADTYPE
:
161 global $wgFileExtensions;
162 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
164 'filetype' => $verification['finalExt'],
165 'allowed' => $wgFileExtensions
168 case UploadBase
::MIN_LENGTH_PARTNAME
:
169 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
171 case UploadBase
::ILLEGAL_FILENAME
:
172 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
173 0, array( 'filename' => $verification['filtered'] ) );
175 case UploadBase
::OVERWRITE_EXISTING_FILE
:
176 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
178 case UploadBase
::VERIFICATION_ERROR
:
179 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
180 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
181 0, array( 'details' => $verification['details'] ) );
183 case UploadBase
::HOOK_ABORTED
:
184 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
185 'hookaborted', 0, array( 'error' => $verification['error'] ) );
188 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
189 0, array( 'code' => $verification['status'] ) );
194 if( !$this->mParams
['ignorewarnings'] ) {
195 $warnings = $this->mUpload
->checkWarnings();
198 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
200 if( isset( $warnings['duplicate'] ) ) {
202 foreach( $warnings['duplicate'] as $key => $dupe )
203 $dupes[] = $dupe->getName();
204 $this->getResult()->setIndexedTagName( $dupes, 'duplicate');
205 $warnings['duplicate'] = $dupes;
209 if( isset( $warnings['exists'] ) ) {
210 $warning = $warnings['exists'];
211 unset( $warnings['exists'] );
212 $warnings[$warning['warning']] = $warning['file']->getName();
215 $result['result'] = 'Warning';
216 $result['warnings'] = $warnings;
218 $sessionKey = $this->mUpload
->stashSession();
220 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
222 $result['sessionkey'] = $sessionKey;
228 // Use comment as initial page text by default
229 if (is_null($this->mParams
['text']))
230 $this->mParams
['text'] = $this->mParams
['comment'];
232 // No errors, no warnings: do the upload
233 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
234 $this->mParams
['text'], $this->mParams
['watch'], $wgUser );
236 if( !$status->isGood() ) {
237 $error = $status->getErrorsArray();
238 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
240 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
243 $file = $this->mUpload
->getLocalFile();
244 $result['result'] = 'Success';
245 $result['filename'] = $file->getName();
247 // Append imageinfo to the result
248 $imParam = ApiQueryImageInfo
::getPropertyNames();
249 $result['imageinfo'] = ApiQueryImageInfo
::getInfo( $file,
250 array_flip( $imParam ), $this->getResult() );
255 public function mustBePosted() {
259 public function isWriteMode() {
263 public function getAllowedParams() {
267 ApiBase
::PARAM_DFLT
=> ''
272 'ignorewarnings' => false,
275 'sessionkey' => null,
278 if ( $this->getMain()->isInternalMode() )
279 $params['internalhttpsession'] = null;
284 public function getParamDescription() {
286 'filename' => 'Target filename',
287 'token' => 'Edit token. You can get one of these through prop=info',
288 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
289 'text' => 'Initial page text for new files',
290 'watch' => 'Watch the page',
291 'ignorewarnings' => 'Ignore any warnings',
292 'file' => 'File contents',
293 'url' => 'Url to fetch the file from',
294 'sessionkey' => array(
295 'Session key returned by a previous upload that failed due to warnings',
300 public function getDescription() {
302 'Upload a file, or get the status of pending uploads. Several methods are available:',
303 ' * Upload file contents directly, using the "file" parameter',
304 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
305 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
306 'sending the "file" parameter. Note also that queries using session keys must be',
307 'done in the same login session as the query that originally returned the key (i.e. do not',
308 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff.'
312 protected function getExamples() {
314 'Upload from a URL:',
315 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
316 'Complete an upload that failed due to warnings:',
317 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
321 public function getVersion() {
322 return __CLASS__
. ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';