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