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