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