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