follow-up r62498 — use the new functionality of requireOnlyOneParameter of allowing...
[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 ( !$wgUser->matchEditToken( $this->mParams['token'] ) )
52 $this->dieUsageMsg( array( 'sessionfailure' ) );
53
54 // Add the uploaded file to the params array
55 $this->mParams['file'] = $request->getFileName( 'file' );
56
57 // One and only one of the following parameters is needed
58 $this->requireOnlyOneParameter( $this->mParams,
59 'sessionkey', 'file', 'url', 'enablechunks' );
60
61 // Initialize $this->mUpload
62 if ( $this->mParams['enablechunks'] ) {
63 $this->mUpload = new UploadFromChunks();
64
65 $this->mUpload->initialize(
66 $request->getVal( 'done', null ),
67 $request->getVal( 'filename', null ),
68 $request->getVal( 'chunksession', null ),
69 $request->getFileTempName( 'chunk' ),
70 $request->getFileSize( 'chunk' ),
71 $request->getSessionData( 'wsUploadData' )
72 );
73
74 if ( !$this->mUpload->status->isOK() ) {
75 return $this->dieUsageMsg( $this->mUpload->status->getErrorsArray() );
76 }
77 } elseif ( $this->mParams['sessionkey'] ) {
78 /**
79 * Upload stashed in a previous request
80 */
81 // Check the session key
82 if ( !isset( $_SESSION['wsUploadData'][$this->mParams['sessionkey']] ) )
83 return $this->dieUsageMsg( array( 'invalid-session-key' ) );
84
85 $this->mUpload = new UploadFromStash();
86 $this->mUpload->initialize( $this->mParams['filename'],
87 $_SESSION['wsUploadData'][$this->mParams['sessionkey']] );
88 } elseif ( isset( $this->mParams['filename'] ) ) {
89 /**
90 * Upload from url, etc
91 * Parameter filename is required
92 */
93
94 if ( isset( $this->mParams['file'] ) ) {
95 $this->mUpload = new UploadFromFile();
96 $this->mUpload->initialize(
97 $this->mParams['filename'],
98 $request->getFileTempName( 'file' ),
99 $request->getFileSize( 'file' )
100 );
101 } elseif ( isset( $this->mParams['url'] ) ) {
102 // make sure upload by url is enabled:
103 if ( !$wgAllowCopyUploads )
104 $this->dieUsageMsg( array( 'uploaddisabled' ) );
105
106 // make sure the current user can upload
107 if ( ! $wgUser->isAllowed( 'upload_by_url' ) )
108 $this->dieUsageMsg( array( 'badaccess-groups' ) );
109
110 $this->mUpload = new UploadFromUrl();
111 $this->mUpload->initialize( $this->mParams['filename'],
112 $this->mParams['url'] );
113
114 $status = $this->mUpload->fetchFile();
115 if ( !$status->isOK() ) {
116 return $this->dieUsage( $status->getWikiText(), 'fetchfileerror' );
117 }
118 }
119 } else $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
120
121 if ( !isset( $this->mUpload ) )
122 $this->dieUsage( 'No upload module set', 'nomodule' );
123
124 // Check whether the user has the appropriate permissions to upload anyway
125 $permission = $this->mUpload->isAllowed( $wgUser );
126
127 if ( $permission !== true ) {
128 if ( !$wgUser->isLoggedIn() )
129 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
130 else
131 $this->dieUsageMsg( array( 'badaccess-groups' ) );
132 }
133 // Perform the upload
134 $result = $this->performUpload();
135
136 // Cleanup any temporary mess
137 $this->mUpload->cleanupTempFile();
138
139 if ( isset( $result['chunked-output'] ) ) {
140 foreach ( $result['chunked-output'] as $key => $value ) {
141 if ( $value === null ) $value = "";
142 $this->getResult()->addValue( null, $key, $value );
143 }
144 } else {
145 $this->getResult()->addValue( null, $this->getModuleName(), $result );
146 }
147 }
148
149 protected function performUpload() {
150 global $wgUser;
151 $result = array();
152 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
153 if ( $permErrors !== true ) {
154 $this->dieUsageMsg( array( 'badaccess-groups' ) );
155 }
156
157 // TODO: Move them to ApiBase's message map
158 $verification = $this->mUpload->verifyUpload();
159 if ( $verification['status'] !== UploadBase::OK ) {
160 $result['result'] = 'Failure';
161 switch( $verification['status'] ) {
162 case UploadBase::EMPTY_FILE:
163 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
164 break;
165 case UploadBase::FILETYPE_MISSING:
166 $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
167 break;
168 case UploadBase::FILETYPE_BADTYPE:
169 global $wgFileExtensions;
170 $this->dieUsage( 'This type of file is banned', 'filetype-banned',
171 0, array(
172 'filetype' => $verification['finalExt'],
173 'allowed' => $wgFileExtensions
174 ) );
175 break;
176 case UploadBase::MIN_LENGTH_PARTNAME:
177 $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
178 break;
179 case UploadBase::ILLEGAL_FILENAME:
180 $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
181 0, array( 'filename' => $verification['filtered'] ) );
182 break;
183 case UploadBase::OVERWRITE_EXISTING_FILE:
184 $this->dieUsage( 'Overwriting an existing file is not allowed', 'overwrite' );
185 break;
186 case UploadBase::VERIFICATION_ERROR:
187 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
188 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
189 0, array( 'details' => $verification['details'] ) );
190 break;
191 case UploadBase::HOOK_ABORTED:
192 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
193 'hookaborted', 0, array( 'error' => $verification['error'] ) );
194 break;
195 default:
196 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
197 0, array( 'code' => $verification['status'] ) );
198 break;
199 }
200 return $result;
201 }
202 if ( !$this->mParams['ignorewarnings'] ) {
203 $warnings = $this->mUpload->checkWarnings();
204 if ( $warnings ) {
205 // Add indices
206 $this->getResult()->setIndexedTagName( $warnings, 'warning' );
207
208 if ( isset( $warnings['duplicate'] ) ) {
209 $dupes = array();
210 foreach ( $warnings['duplicate'] as $key => $dupe )
211 $dupes[] = $dupe->getName();
212 $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
213 $warnings['duplicate'] = $dupes;
214 }
215
216
217 if ( isset( $warnings['exists'] ) ) {
218 $warning = $warnings['exists'];
219 unset( $warnings['exists'] );
220 $warnings[$warning['warning']] = $warning['file']->getName();
221 }
222
223 $result['result'] = 'Warning';
224 $result['warnings'] = $warnings;
225
226 $sessionKey = $this->mUpload->stashSession();
227 if ( !$sessionKey )
228 $this->dieUsage( 'Stashing temporary file failed', 'stashfailed' );
229
230 $result['sessionkey'] = $sessionKey;
231
232 return $result;
233 }
234 }
235
236 // Use comment as initial page text by default
237 if ( is_null( $this->mParams['text'] ) )
238 $this->mParams['text'] = $this->mParams['comment'];
239
240 // No errors, no warnings: do the upload
241 $status = $this->mUpload->performUpload( $this->mParams['comment'],
242 $this->mParams['text'], $this->mParams['watch'], $wgUser );
243
244 if ( !$status->isGood() ) {
245 $error = $status->getErrorsArray();
246 $this->getResult()->setIndexedTagName( $result['details'], 'error' );
247
248 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
249 } elseif ( $this->mParams['enablechunks'] ) {
250 return array( "chunked-output" => $status->value );
251 }
252
253 $file = $this->mUpload->getLocalFile();
254 $result['result'] = 'Success';
255 $result['filename'] = $file->getName();
256 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
257
258 return $result;
259 }
260
261 public function mustBePosted() {
262 return true;
263 }
264
265 public function isWriteMode() {
266 return true;
267 }
268
269 public function getAllowedParams() {
270 $params = array(
271 'filename' => null,
272 'comment' => array(
273 ApiBase::PARAM_DFLT => ''
274 ),
275 'text' => null,
276 'token' => null,
277 'watch' => false,
278 'ignorewarnings' => false,
279 'file' => null,
280 'enablechunks' => false,
281 'chunksession' => null,
282 'chunk' => null,
283 'done' => false,
284 'url' => null,
285 'sessionkey' => null,
286 );
287
288 if ( $this->getMain()->isInternalMode() )
289 $params['internalhttpsession'] = null;
290 return $params;
291
292 }
293
294 public function getParamDescription() {
295 return array(
296 'filename' => 'Target filename',
297 'token' => 'Edit token. You can get one of these through prop=info',
298 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
299 'text' => 'Initial page text for new files',
300 'watch' => 'Watch the page',
301 'ignorewarnings' => 'Ignore any warnings',
302 'file' => 'File contents',
303 'enablechunks' => 'Set to use chunk mode; see http://firefogg.org/dev/chunk_post.html for protocol',
304 'chunksession' => 'The session key, established on the first contact during the chunked upload',
305 'chunk' => 'The data in this chunk of a chunked upload',
306 'done' => 'Set to 1 on the last chunk of a chunked upload',
307 'url' => 'Url to fetch the file from',
308 'sessionkey' => array(
309 'Session key returned by a previous upload that failed due to warnings',
310 ),
311 );
312 }
313
314 public function getDescription() {
315 return array(
316 'Upload a file, or get the status of pending uploads. Several methods are available:',
317 ' * Upload file contents directly, using the "file" parameter',
318 ' * Upload a file in chunks, using the "enablechunks",',
319 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
320 ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
321 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
322 'sending the "file" or "chunk" parameters. Note also that queries using session keys must be',
323 'done in the same login session as the query that originally returned the key (i.e. do not',
324 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff.'
325 );
326 }
327
328 public function getPossibleErrors() {
329 return array_merge( parent::getPossibleErrors(), array(
330 array( 'uploaddisabled' ),
331 array( 'sessionfailure' ),
332 array( 'invalid-session-key' ),
333 array( 'uploaddisabled' ),
334 array( 'badaccess-groups' ),
335 array( 'missingparam', 'filename' ),
336 array( 'mustbeloggedin', 'upload' ),
337 array( 'badaccess-groups' ),
338 array( 'badaccess-groups' ),
339 array( 'code' => 'fetchfileerror', 'info' => '' ),
340 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
341 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
342 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
343 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
344 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
345 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
346 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
347 ) );
348 }
349
350 public function requiresToken() {
351 return true;
352 }
353
354 protected function getExamples() {
355 return array(
356 'Upload from a URL:',
357 ' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
358 'Complete an upload that failed due to warnings:',
359 ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
360 'Begin a chunked upload:',
361 ' api.php?action=upload&filename=Wiki.png&enablechunks=1'
362 );
363 }
364
365 public function getVersion() {
366 return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';
367 }
368 }