Start of blanket coverage of dieUsageMsg in getPossibleErrors
[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 - 2010 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 // Check whether upload is enabled
44 if ( !UploadBase::isEnabled() )
45 $this->dieUsageMsg( array( 'uploaddisabled' ) );
46
47 $this->mParams = $this->extractRequestParams();
48 $request = $this->getMain()->getRequest();
49
50 // Do token checks:
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' ) );
55
56 // Add the uploaded file to the params array
57 $this->mParams['file'] = $request->getFileName( 'file' );
58
59 // One and only one of the following parameters is needed
60 $this->requireOnlyOneParameter( $this->mParams,
61 'sessionkey', 'file', 'url', 'enablechunks' );
62
63 // Initialize $this->mUpload
64 if ( $this->mParams['enablechunks'] ) {
65 $this->mUpload = new UploadFromChunks();
66
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' )
74 );
75
76 if ( !$this->mUpload->status->isOK() ) {
77 return $this->dieUsageMsg( $this->mUpload->status->getErrorsArray() );
78 }
79 } elseif ( $this->mParams['sessionkey'] ) {
80 /**
81 * Upload stashed in a previous request
82 */
83 // Check the session key
84 if ( !isset( $_SESSION['wsUploadData'][$this->mParams['sessionkey']] ) )
85 return $this->dieUsageMsg( array( 'invalid-session-key' ) );
86
87 $this->mUpload = new UploadFromStash();
88 $this->mUpload->initialize( $this->mParams['filename'],
89 $_SESSION['wsUploadData'][$this->mParams['sessionkey']] );
90 } elseif ( isset( $this->mParams['filename'] ) ) {
91 /**
92 * Upload from url, etc
93 * Parameter filename is required
94 */
95
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' )
102 );
103 } elseif ( isset( $this->mParams['url'] ) ) {
104 // make sure upload by url is enabled:
105 if ( !$wgAllowCopyUploads )
106 $this->dieUsageMsg( array( 'uploaddisabled' ) );
107
108 // make sure the current user can upload
109 if ( ! $wgUser->isAllowed( 'upload_by_url' ) )
110 $this->dieUsageMsg( array( 'badaccess-groups' ) );
111
112 $this->mUpload = new UploadFromUrl();
113 $this->mUpload->initialize( $this->mParams['filename'],
114 $this->mParams['url'] );
115
116 $status = $this->mUpload->fetchFile();
117 if ( !$status->isOK() ) {
118 return $this->dieUsage( $status->getWikiText(), 'fetchfileerror' );
119 }
120 }
121 } else $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
122
123 if ( !isset( $this->mUpload ) )
124 $this->dieUsage( 'No upload module set', 'nomodule' );
125
126 // Check whether the user has the appropriate permissions to upload anyway
127 $permission = $this->mUpload->isAllowed( $wgUser );
128
129 if ( $permission !== true ) {
130 if ( !$wgUser->isLoggedIn() )
131 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
132 else
133 $this->dieUsageMsg( array( 'badaccess-groups' ) );
134 }
135 // Perform the upload
136 $result = $this->performUpload();
137
138 // Cleanup any temporary mess
139 $this->mUpload->cleanupTempFile();
140
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 );
145 }
146 } else {
147 $this->getResult()->addValue( null, $this->getModuleName(), $result );
148 }
149 }
150
151 protected function performUpload() {
152 global $wgUser;
153 $result = array();
154 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
155 if ( $permErrors !== true ) {
156 $this->dieUsageMsg( array( 'badaccess-groups' ) );
157 }
158
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' );
166 break;
167 case UploadBase::FILETYPE_MISSING:
168 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
169 break;
170 case UploadBase::FILETYPE_BADTYPE:
171 global $wgFileExtensions;
172 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
173 0, array(
174 'filetype' => $verification['finalExt'],
175 'allowed' => $wgFileExtensions
176 ) );
177 break;
178 case UploadBase::MIN_LENGTH_PARTNAME:
179 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
180 break;
181 case UploadBase::ILLEGAL_FILENAME:
182 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
183 0, array( 'filename' => $verification['filtered'] ) );
184 break;
185 case UploadBase::OVERWRITE_EXISTING_FILE:
186 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
187 break;
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'] ) );
192 break;
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'] ) );
196 break;
197 default:
198 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
199 0, array( 'code' => $verification['status'] ) );
200 break;
201 }
202 return $result;
203 }
204 if ( !$this->mParams['ignorewarnings'] ) {
205 $warnings = $this->mUpload->checkWarnings();
206 if ( $warnings ) {
207 // Add indices
208 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
209
210 if ( isset( $warnings['duplicate'] ) ) {
211 $dupes = array();
212 foreach ( $warnings['duplicate'] as $key => $dupe )
213 $dupes[] = $dupe->getName();
214 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
215 $warnings['duplicate'] = $dupes;
216 }
217
218
219 if ( isset( $warnings['exists'] ) ) {
220 $warning = $warnings['exists'];
221 unset( $warnings['exists'] );
222 $warnings[$warning['warning']] = $warning['file']->getName();
223 }
224
225 $result['result'] = 'Warning';
226 $result['warnings'] = $warnings;
227
228 $sessionKey = $this->mUpload->stashSession();
229 if ( !$sessionKey )
230 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
231
232 $result['sessionkey'] = $sessionKey;
233
234 return $result;
235 }
236 }
237
238 // Use comment as initial page text by default
239 if ( is_null( $this->mParams['text'] ) )
240 $this->mParams['text'] = $this->mParams['comment'];
241
242 // No errors, no warnings: do the upload
243 $status = $this->mUpload->performUpload( $this->mParams['comment'],
244 $this->mParams['text'], $this->mParams['watch'], $wgUser );
245
246 if ( !$status->isGood() ) {
247 $error = $status->getErrorsArray();
248 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
249
250 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
251 } elseif( $this->mParams['enablechunks'] ) {
252 return array("chunked-output" => $status->value);
253 }
254
255 $file = $this->mUpload->getLocalFile();
256 $result['result'] = 'Success';
257 $result['filename'] = $file->getName();
258 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
259
260 return $result;
261 }
262
263 public function mustBePosted() {
264 return true;
265 }
266
267 public function isWriteMode() {
268 return true;
269 }
270
271 public function getAllowedParams() {
272 $params = array(
273 'filename' => null,
274 'comment' => array(
275 ApiBase::PARAM_DFLT => ''
276 ),
277 'text' => null,
278 'token' => null,
279 'watch' => false,
280 'ignorewarnings' => false,
281 'file' => null,
282 'enablechunks' => null, /* must be null to work with requireOnlyOneParameter */
283 'chunksession' => null,
284 'chunk' => null,
285 'done' => false,
286 'url' => null,
287 'sessionkey' => null,
288 );
289
290 if ( $this->getMain()->isInternalMode() )
291 $params['internalhttpsession'] = null;
292 return $params;
293
294 }
295
296 public function getParamDescription() {
297 return array(
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',
312 ),
313 );
314 }
315
316 public function getDescription() {
317 return array(
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.'
327 );
328 }
329
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 ) );
343 }
344
345 protected function getExamples() {
346 return array(
347 'Upload from a URL:',
348 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
349 'Complete an upload that failed due to warnings:',
350 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
351 'Begin a chunked upload:',
352 ' api.php?action=upload&filename=Wiki.png&enablechunks=1'
353 );
354 }
355
356 public function getVersion() {
357 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';
358 }
359 }