Better file size limit message display logic
[lhc/web/wiklou.git] / includes / specials / SpecialUpload.php
1 <?php
2 /**
3 * Implements Special:Upload
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 * @ingroup Upload
23 */
24
25 /**
26 * Form for handling uploads and special page.
27 *
28 * @ingroup SpecialPage
29 * @ingroup Upload
30 */
31 class SpecialUpload extends SpecialPage {
32 /**
33 * Constructor : initialise object
34 * Get data POSTed through the form and assign them to the object
35 * @param WebRequest $request Data posted.
36 */
37 public function __construct( $request = null ) {
38 parent::__construct( 'Upload', 'upload' );
39 }
40
41 /** Misc variables **/
42
43 /** @var WebRequest|FauxRequest The request this form is supposed to handle */
44 public $mRequest;
45 public $mSourceType;
46
47 /** @var UploadBase */
48 public $mUpload;
49
50 /** @var LocalFile */
51 public $mLocalFile;
52 public $mUploadClicked;
53
54 /** User input variables from the "description" section **/
55
56 /** @var string The requested target file name */
57 public $mDesiredDestName;
58 public $mComment;
59 public $mLicense;
60
61 /** User input variables from the root section **/
62
63 public $mIgnoreWarning;
64 public $mWatchthis;
65 public $mCopyrightStatus;
66 public $mCopyrightSource;
67
68 /** Hidden variables **/
69
70 public $mDestWarningAck;
71
72 /** @var bool The user followed an "overwrite this file" link */
73 public $mForReUpload;
74
75 /** @var bool The user clicked "Cancel and return to upload form" button */
76 public $mCancelUpload;
77 public $mTokenOk;
78
79 /** @var bool Subclasses can use this to determine whether a file was uploaded */
80 public $mUploadSuccessful = false;
81
82 /** Text injection points for hooks not using HTMLForm **/
83 public $uploadFormTextTop;
84 public $uploadFormTextAfterSummary;
85
86 /**
87 * Initialize instance variables from request and create an Upload handler
88 */
89 protected function loadRequest() {
90 $this->mRequest = $request = $this->getRequest();
91 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
92 $this->mUpload = UploadBase::createFromRequest( $request );
93 $this->mUploadClicked = $request->wasPosted()
94 && ( $request->getCheck( 'wpUpload' )
95 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
96
97 // Guess the desired name from the filename if not provided
98 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
99 if ( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
100 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
101 }
102 $this->mLicense = $request->getText( 'wpLicense' );
103
104 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
105 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
106 || $request->getCheck( 'wpUploadIgnoreWarning' );
107 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
108 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
109 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
110
111 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
112
113 $commentDefault = '';
114 $commentMsg = wfMessage( 'upload-default-description' )->inContentLanguage();
115 if ( !$this->mForReUpload && !$commentMsg->isDisabled() ) {
116 $commentDefault = $commentMsg->plain();
117 }
118 $this->mComment = $request->getText( 'wpUploadDescription', $commentDefault );
119
120 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
121 || $request->getCheck( 'wpReUpload' ); // b/w compat
122
123 // If it was posted check for the token (no remote POST'ing with user credentials)
124 $token = $request->getVal( 'wpEditToken' );
125 $this->mTokenOk = $this->getUser()->matchEditToken( $token );
126
127 $this->uploadFormTextTop = '';
128 $this->uploadFormTextAfterSummary = '';
129 }
130
131 /**
132 * This page can be shown if uploading is enabled.
133 * Handle permission checking elsewhere in order to be able to show
134 * custom error messages.
135 *
136 * @param User $user
137 * @return bool
138 */
139 public function userCanExecute( User $user ) {
140 return UploadBase::isEnabled() && parent::userCanExecute( $user );
141 }
142
143 /**
144 * Special page entry point
145 * @param string $par
146 * @throws ErrorPageError
147 * @throws Exception
148 * @throws FatalError
149 * @throws MWException
150 * @throws PermissionsError
151 * @throws ReadOnlyError
152 * @throws UserBlockedError
153 */
154 public function execute( $par ) {
155 $this->setHeaders();
156 $this->outputHeader();
157
158 # Check uploading enabled
159 if ( !UploadBase::isEnabled() ) {
160 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
161 }
162
163 $this->getOutput()->addHelpLink( 'Help:Managing files' );
164
165 # Check permissions
166 $user = $this->getUser();
167 $permissionRequired = UploadBase::isAllowed( $user );
168 if ( $permissionRequired !== true ) {
169 throw new PermissionsError( $permissionRequired );
170 }
171
172 # Check blocks
173 if ( $user->isBlocked() ) {
174 throw new UserBlockedError( $user->getBlock() );
175 }
176
177 # Check whether we actually want to allow changing stuff
178 $this->checkReadOnly();
179
180 $this->loadRequest();
181
182 # Unsave the temporary file in case this was a cancelled upload
183 if ( $this->mCancelUpload ) {
184 if ( !$this->unsaveUploadedFile() ) {
185 # Something went wrong, so unsaveUploadedFile showed a warning
186 return;
187 }
188 }
189
190 # Process upload or show a form
191 if (
192 $this->mTokenOk && !$this->mCancelUpload &&
193 ( $this->mUpload && $this->mUploadClicked )
194 ) {
195 $this->processUpload();
196 } else {
197 # Backwards compatibility hook
198 if ( !Hooks::run( 'UploadForm:initial', array( &$this ) ) ) {
199 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
200
201 return;
202 }
203 $this->showUploadForm( $this->getUploadForm() );
204 }
205
206 # Cleanup
207 if ( $this->mUpload ) {
208 $this->mUpload->cleanupTempFile();
209 }
210 }
211
212 /**
213 * Show the main upload form
214 *
215 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
216 */
217 protected function showUploadForm( $form ) {
218 # Add links if file was previously deleted
219 if ( $this->mDesiredDestName ) {
220 $this->showViewDeletedLinks();
221 }
222
223 if ( $form instanceof HTMLForm ) {
224 $form->show();
225 } else {
226 $this->getOutput()->addHTML( $form );
227 }
228 }
229
230 /**
231 * Get an UploadForm instance with title and text properly set.
232 *
233 * @param string $message HTML string to add to the form
234 * @param string $sessionKey Session key in case this is a stashed upload
235 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
236 * @return UploadForm
237 */
238 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
239 # Initialize form
240 $context = new DerivativeContext( $this->getContext() );
241 $context->setTitle( $this->getPageTitle() ); // Remove subpage
242 $form = new UploadForm( array(
243 'watch' => $this->getWatchCheck(),
244 'forreupload' => $this->mForReUpload,
245 'sessionkey' => $sessionKey,
246 'hideignorewarning' => $hideIgnoreWarning,
247 'destwarningack' => (bool)$this->mDestWarningAck,
248
249 'description' => $this->mComment,
250 'texttop' => $this->uploadFormTextTop,
251 'textaftersummary' => $this->uploadFormTextAfterSummary,
252 'destfile' => $this->mDesiredDestName,
253 ), $context );
254
255 # Check the token, but only if necessary
256 if (
257 !$this->mTokenOk && !$this->mCancelUpload &&
258 ( $this->mUpload && $this->mUploadClicked )
259 ) {
260 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
261 }
262
263 # Give a notice if the user is uploading a file that has been deleted or moved
264 # Note that this is independent from the message 'filewasdeleted' that requires JS
265 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
266 $delNotice = ''; // empty by default
267 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
268 LogEventsList::showLogExtract( $delNotice, array( 'delete', 'move' ),
269 $desiredTitleObj,
270 '', array( 'lim' => 10,
271 'conds' => array( "log_action != 'revision'" ),
272 'showIfEmpty' => false,
273 'msgKey' => array( 'upload-recreate-warning' ) )
274 );
275 }
276 $form->addPreText( $delNotice );
277
278 # Add text to form
279 $form->addPreText( '<div id="uploadtext">' .
280 $this->msg( 'uploadtext', array( $this->mDesiredDestName ) )->parseAsBlock() .
281 '</div>' );
282 # Add upload error message
283 $form->addPreText( $message );
284
285 # Add footer to form
286 $uploadFooter = $this->msg( 'uploadfooter' );
287 if ( !$uploadFooter->isDisabled() ) {
288 $form->addPostText( '<div id="mw-upload-footer-message">'
289 . $uploadFooter->parseAsBlock() . "</div>\n" );
290 }
291
292 return $form;
293 }
294
295 /**
296 * Shows the "view X deleted revivions link""
297 */
298 protected function showViewDeletedLinks() {
299 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
300 $user = $this->getUser();
301 // Show a subtitle link to deleted revisions (to sysops et al only)
302 if ( $title instanceof Title ) {
303 $count = $title->isDeleted();
304 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
305 $restorelink = Linker::linkKnown(
306 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
307 $this->msg( 'restorelink' )->numParams( $count )->escaped()
308 );
309 $link = $this->msg( $user->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted' )
310 ->rawParams( $restorelink )->parseAsBlock();
311 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
312 }
313 }
314 }
315
316 /**
317 * Stashes the upload and shows the main upload form.
318 *
319 * Note: only errors that can be handled by changing the name or
320 * description should be redirected here. It should be assumed that the
321 * file itself is sane and has passed UploadBase::verifyFile. This
322 * essentially means that UploadBase::VERIFICATION_ERROR and
323 * UploadBase::EMPTY_FILE should not be passed here.
324 *
325 * @param string $message HTML message to be passed to mainUploadForm
326 */
327 protected function showRecoverableUploadError( $message ) {
328 $sessionKey = $this->mUpload->stashSession();
329 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
330 '<div class="error">' . $message . "</div>\n";
331
332 $form = $this->getUploadForm( $message, $sessionKey );
333 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
334 $this->showUploadForm( $form );
335 }
336
337 /**
338 * Stashes the upload, shows the main form, but adds a "continue anyway button".
339 * Also checks whether there are actually warnings to display.
340 *
341 * @param array $warnings
342 * @return bool True if warnings were displayed, false if there are no
343 * warnings and it should continue processing
344 */
345 protected function showUploadWarning( $warnings ) {
346 # If there are no warnings, or warnings we can ignore, return early.
347 # mDestWarningAck is set when some javascript has shown the warning
348 # to the user. mForReUpload is set when the user clicks the "upload a
349 # new version" link.
350 if ( !$warnings || ( count( $warnings ) == 1
351 && isset( $warnings['exists'] )
352 && ( $this->mDestWarningAck || $this->mForReUpload ) )
353 ) {
354 return false;
355 }
356
357 $sessionKey = $this->mUpload->stashSession();
358
359 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
360 . '<ul class="warning">';
361 foreach ( $warnings as $warning => $args ) {
362 if ( $warning == 'badfilename' ) {
363 $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
364 }
365 if ( $warning == 'exists' ) {
366 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
367 } elseif ( $warning == 'duplicate' ) {
368 $msg = $this->getDupeWarning( $args );
369 } elseif ( $warning == 'duplicate-archive' ) {
370 if ( $args === '' ) {
371 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
372 . "</li>\n";
373 } else {
374 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
375 Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
376 . "</li>\n";
377 }
378 } else {
379 if ( $args === true ) {
380 $args = array();
381 } elseif ( !is_array( $args ) ) {
382 $args = array( $args );
383 }
384 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
385 }
386 $warningHtml .= $msg;
387 }
388 $warningHtml .= "</ul>\n";
389 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
390
391 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
392 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
393 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
394 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
395
396 $this->showUploadForm( $form );
397
398 # Indicate that we showed a form
399 return true;
400 }
401
402 /**
403 * Show the upload form with error message, but do not stash the file.
404 *
405 * @param string $message HTML string
406 */
407 protected function showUploadError( $message ) {
408 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
409 '<div class="error">' . $message . "</div>\n";
410 $this->showUploadForm( $this->getUploadForm( $message ) );
411 }
412
413 /**
414 * Do the upload.
415 * Checks are made in SpecialUpload::execute()
416 */
417 protected function processUpload() {
418 // Fetch the file if required
419 $status = $this->mUpload->fetchFile();
420 if ( !$status->isOK() ) {
421 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
422
423 return;
424 }
425
426 if ( !Hooks::run( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
427 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
428 // This code path is deprecated. If you want to break upload processing
429 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
430 // and UploadBase::verifyFile.
431 // If you use this hook to break uploading, the user will be returned
432 // an empty form with no error message whatsoever.
433 return;
434 }
435
436 // Upload verification
437 $details = $this->mUpload->verifyUpload();
438 if ( $details['status'] != UploadBase::OK ) {
439 $this->processVerificationError( $details );
440
441 return;
442 }
443
444 // Verify permissions for this title
445 $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
446 if ( $permErrors !== true ) {
447 $code = array_shift( $permErrors[0] );
448 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
449
450 return;
451 }
452
453 $this->mLocalFile = $this->mUpload->getLocalFile();
454
455 // Check warnings if necessary
456 if ( !$this->mIgnoreWarning ) {
457 $warnings = $this->mUpload->checkWarnings();
458 if ( $this->showUploadWarning( $warnings ) ) {
459 return;
460 }
461 }
462
463 // Get the page text if this is not a reupload
464 if ( !$this->mForReUpload ) {
465 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
466 $this->mCopyrightStatus, $this->mCopyrightSource, $this->getConfig() );
467 } else {
468 $pageText = false;
469 }
470
471 $status = $this->mUpload->performUpload(
472 $this->mComment,
473 $pageText,
474 $this->mWatchthis,
475 $this->getUser()
476 );
477
478 if ( !$status->isGood() ) {
479 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
480
481 return;
482 }
483
484 // Success, redirect to description page
485 $this->mUploadSuccessful = true;
486 Hooks::run( 'SpecialUploadComplete', array( &$this ) );
487 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
488 }
489
490 /**
491 * Get the initial image page text based on a comment and optional file status information
492 * @param string $comment
493 * @param string $license
494 * @param string $copyStatus
495 * @param string $source
496 * @param Config $config Configuration object to load data from
497 * @return string
498 */
499 public static function getInitialPageText( $comment = '', $license = '',
500 $copyStatus = '', $source = '', Config $config = null
501 ) {
502 if ( $config === null ) {
503 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
504 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
505 }
506
507 $msg = array();
508 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
509 /* These messages are transcluded into the actual text of the description page.
510 * Thus, forcing them as content messages makes the upload to produce an int: template
511 * instead of hardcoding it there in the uploader language.
512 */
513 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
514 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
515 $msg[$msgName] = "{{int:$msgName}}";
516 } else {
517 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
518 }
519 }
520
521 if ( $config->get( 'UseCopyrightUpload' ) ) {
522 $licensetxt = '';
523 if ( $license != '' ) {
524 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
525 }
526 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
527 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
528 "$licensetxt" .
529 '== ' . $msg['filesource'] . " ==\n" . $source;
530 } else {
531 if ( $license != '' ) {
532 $filedesc = $comment == '' ? '' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
533 $pageText = $filedesc .
534 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
535 } else {
536 $pageText = $comment;
537 }
538 }
539
540 return $pageText;
541 }
542
543 /**
544 * See if we should check the 'watch this page' checkbox on the form
545 * based on the user's preferences and whether we're being asked
546 * to create a new file or update an existing one.
547 *
548 * In the case where 'watch edits' is off but 'watch creations' is on,
549 * we'll leave the box unchecked.
550 *
551 * Note that the page target can be changed *on the form*, so our check
552 * state can get out of sync.
553 * @return bool|string
554 */
555 protected function getWatchCheck() {
556 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
557 // Watch all edits!
558 return true;
559 }
560
561 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
562 if ( $desiredTitleObj instanceof Title && $this->getUser()->isWatched( $desiredTitleObj ) ) {
563 // Already watched, don't change that
564 return true;
565 }
566
567 $local = wfLocalFile( $this->mDesiredDestName );
568 if ( $local && $local->exists() ) {
569 // We're uploading a new version of an existing file.
570 // No creation, so don't watch it if we're not already.
571 return false;
572 } else {
573 // New page should get watched if that's our option.
574 return $this->getUser()->getOption( 'watchcreations' );
575 }
576 }
577
578 /**
579 * Provides output to the user for a result of UploadBase::verifyUpload
580 *
581 * @param array $details Result of UploadBase::verifyUpload
582 * @throws MWException
583 */
584 protected function processVerificationError( $details ) {
585 switch ( $details['status'] ) {
586
587 /** Statuses that only require name changing **/
588 case UploadBase::MIN_LENGTH_PARTNAME:
589 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
590 break;
591 case UploadBase::ILLEGAL_FILENAME:
592 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
593 $details['filtered'] )->parse() );
594 break;
595 case UploadBase::FILENAME_TOO_LONG:
596 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
597 break;
598 case UploadBase::FILETYPE_MISSING:
599 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
600 break;
601 case UploadBase::WINDOWS_NONASCII_FILENAME:
602 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
603 break;
604
605 /** Statuses that require reuploading **/
606 case UploadBase::EMPTY_FILE:
607 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
608 break;
609 case UploadBase::FILE_TOO_LARGE:
610 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
611 break;
612 case UploadBase::FILETYPE_BADTYPE:
613 $msg = $this->msg( 'filetype-banned-type' );
614 if ( isset( $details['blacklistedExt'] ) ) {
615 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
616 } else {
617 $msg->params( $details['finalExt'] );
618 }
619 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
620 $msg->params( $this->getLanguage()->commaList( $extensions ),
621 count( $extensions ) );
622
623 // Add PLURAL support for the first parameter. This results
624 // in a bit unlogical parameter sequence, but does not break
625 // old translations
626 if ( isset( $details['blacklistedExt'] ) ) {
627 $msg->params( count( $details['blacklistedExt'] ) );
628 } else {
629 $msg->params( 1 );
630 }
631
632 $this->showUploadError( $msg->parse() );
633 break;
634 case UploadBase::VERIFICATION_ERROR:
635 unset( $details['status'] );
636 $code = array_shift( $details['details'] );
637 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
638 break;
639 case UploadBase::HOOK_ABORTED:
640 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
641 $args = $details['error'];
642 $error = array_shift( $args );
643 } else {
644 $error = $details['error'];
645 $args = null;
646 }
647
648 $this->showUploadError( $this->msg( $error, $args )->parse() );
649 break;
650 default:
651 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
652 }
653 }
654
655 /**
656 * Remove a temporarily kept file stashed by saveTempUploadedFile().
657 *
658 * @return bool Success
659 */
660 protected function unsaveUploadedFile() {
661 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
662 return true;
663 }
664 $success = $this->mUpload->unsaveUploadedFile();
665 if ( !$success ) {
666 $this->getOutput()->showFileDeleteError( $this->mUpload->getTempPath() );
667
668 return false;
669 } else {
670 return true;
671 }
672 }
673
674 /*** Functions for formatting warnings ***/
675
676 /**
677 * Formats a result of UploadBase::getExistsWarning as HTML
678 * This check is static and can be done pre-upload via AJAX
679 *
680 * @param array $exists The result of UploadBase::getExistsWarning
681 * @return string Empty string if there is no warning or an HTML fragment
682 */
683 public static function getExistsWarning( $exists ) {
684 if ( !$exists ) {
685 return '';
686 }
687
688 $file = $exists['file'];
689 $filename = $file->getTitle()->getPrefixedText();
690 $warning = '';
691
692 if ( $exists['warning'] == 'exists' ) {
693 // Exact match
694 $warning = wfMessage( 'fileexists', $filename )->parse();
695 } elseif ( $exists['warning'] == 'page-exists' ) {
696 // Page exists but file does not
697 $warning = wfMessage( 'filepageexists', $filename )->parse();
698 } elseif ( $exists['warning'] == 'exists-normalized' ) {
699 $warning = wfMessage( 'fileexists-extension', $filename,
700 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
701 } elseif ( $exists['warning'] == 'thumb' ) {
702 // Swapped argument order compared with other messages for backwards compatibility
703 $warning = wfMessage( 'fileexists-thumbnail-yes',
704 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
705 } elseif ( $exists['warning'] == 'thumb-name' ) {
706 // Image w/o '180px-' does not exists, but we do not like these filenames
707 $name = $file->getName();
708 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
709 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
710 } elseif ( $exists['warning'] == 'bad-prefix' ) {
711 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
712 } elseif ( $exists['warning'] == 'was-deleted' ) {
713 # If the file existed before and was deleted, warn the user of this
714 $ltitle = SpecialPage::getTitleFor( 'Log' );
715 $llink = Linker::linkKnown(
716 $ltitle,
717 wfMessage( 'deletionlog' )->escaped(),
718 array(),
719 array(
720 'type' => 'delete',
721 'page' => $filename
722 )
723 );
724 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
725 }
726
727 return $warning;
728 }
729
730 /**
731 * Construct a warning and a gallery from an array of duplicate files.
732 * @param array $dupes
733 * @return string
734 */
735 public function getDupeWarning( $dupes ) {
736 if ( !$dupes ) {
737 return '';
738 }
739
740 $gallery = ImageGalleryBase::factory( false, $this->getContext() );
741 $gallery->setShowBytes( false );
742 foreach ( $dupes as $file ) {
743 $gallery->add( $file->getTitle() );
744 }
745
746 return '<li>' .
747 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
748 $gallery->toHTML() . "</li>\n";
749 }
750
751 protected function getGroupName() {
752 return 'media';
753 }
754
755 /**
756 * Should we rotate images in the preview on Special:Upload.
757 *
758 * This controls js: mw.config.get( 'wgFileCanRotate' )
759 *
760 * @todo What about non-BitmapHandler handled files?
761 */
762 public static function rotationEnabled() {
763 $bitmapHandler = new BitmapHandler();
764 return $bitmapHandler->autoRotateEnabled();
765 }
766 }
767
768 /**
769 * Sub class of HTMLForm that provides the form section of SpecialUpload
770 */
771 class UploadForm extends HTMLForm {
772 protected $mWatch;
773 protected $mForReUpload;
774 protected $mSessionKey;
775 protected $mHideIgnoreWarning;
776 protected $mDestWarningAck;
777 protected $mDestFile;
778
779 protected $mComment;
780 protected $mTextTop;
781 protected $mTextAfterSummary;
782
783 protected $mSourceIds;
784
785 protected $mMaxFileSize = array();
786
787 protected $mMaxUploadSize = array();
788
789 public function __construct( array $options = array(), IContextSource $context = null ) {
790 $this->mWatch = !empty( $options['watch'] );
791 $this->mForReUpload = !empty( $options['forreupload'] );
792 $this->mSessionKey = isset( $options['sessionkey'] ) ? $options['sessionkey'] : '';
793 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
794 $this->mDestWarningAck = !empty( $options['destwarningack'] );
795 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
796
797 $this->mComment = isset( $options['description'] ) ?
798 $options['description'] : '';
799
800 $this->mTextTop = isset( $options['texttop'] )
801 ? $options['texttop'] : '';
802
803 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
804 ? $options['textaftersummary'] : '';
805
806 $sourceDescriptor = $this->getSourceSection();
807 $descriptor = $sourceDescriptor
808 + $this->getDescriptionSection()
809 + $this->getOptionsSection();
810
811 Hooks::run( 'UploadFormInitDescriptor', array( &$descriptor ) );
812 parent::__construct( $descriptor, $context, 'upload' );
813
814 # Add a link to edit MediaWik:Licenses
815 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
816 $licensesLink = Linker::link(
817 Title::makeTitle( NS_MEDIAWIKI, 'Licenses' ),
818 $this->msg( 'licenses-edit' )->escaped(),
819 array(),
820 array( 'action' => 'edit' )
821 );
822 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
823 $this->addFooterText( $editLicenses, 'description' );
824 }
825
826 # Set some form properties
827 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
828 $this->setSubmitName( 'wpUpload' );
829 # Used message keys: 'accesskey-upload', 'tooltip-upload'
830 $this->setSubmitTooltip( 'upload' );
831 $this->setId( 'mw-upload-form' );
832
833 # Build a list of IDs for javascript insertion
834 $this->mSourceIds = array();
835 foreach ( $sourceDescriptor as $field ) {
836 if ( !empty( $field['id'] ) ) {
837 $this->mSourceIds[] = $field['id'];
838 }
839 }
840 }
841
842 /**
843 * Get the descriptor of the fieldset that contains the file source
844 * selection. The section is 'source'
845 *
846 * @return array Descriptor array
847 */
848 protected function getSourceSection() {
849 if ( $this->mSessionKey ) {
850 return array(
851 'SessionKey' => array(
852 'type' => 'hidden',
853 'default' => $this->mSessionKey,
854 ),
855 'SourceType' => array(
856 'type' => 'hidden',
857 'default' => 'Stash',
858 ),
859 );
860 }
861
862 $canUploadByUrl = UploadFromUrl::isEnabled()
863 && ( UploadFromUrl::isAllowed( $this->getUser() ) === true )
864 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
865 $radio = $canUploadByUrl;
866 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
867
868 $descriptor = array();
869 if ( $this->mTextTop ) {
870 $descriptor['UploadFormTextTop'] = array(
871 'type' => 'info',
872 'section' => 'source',
873 'default' => $this->mTextTop,
874 'raw' => true,
875 );
876 }
877
878 $this->mMaxUploadSize['file'] = UploadBase::getMaxUploadSize( 'file' );
879 # Limit to upload_max_filesize unless we are running under HipHop and
880 # that setting doesn't exist
881 if ( !wfIsHHVM() ) {
882 $this->mMaxUploadSize['file'] = min( $this->mMaxUploadSize['file'],
883 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
884 wfShorthandToInteger( ini_get( 'post_max_size' ) )
885 );
886 }
887
888 $help = $this->msg( 'upload-maxfilesize',
889 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] )
890 )->parse();
891
892 // If the user can also upload by URL, there are 2 different file size limits.
893 // This extra message helps stress which limit corresponds to what.
894 if ( $canUploadByUrl ) {
895 $help .= $this->msg( 'word-separator' )->escaped();
896 $help .= $this->msg( 'upload_source_file' )->parse();
897 }
898
899 $descriptor['UploadFile'] = array(
900 'class' => 'UploadSourceField',
901 'section' => 'source',
902 'type' => 'file',
903 'id' => 'wpUploadFile',
904 'radio-id' => 'wpSourceTypeFile',
905 'label-message' => 'sourcefilename',
906 'upload-type' => 'File',
907 'radio' => &$radio,
908 'help' => $help,
909 'checked' => $selectedSourceType == 'file',
910 );
911
912 if ( $canUploadByUrl ) {
913 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
914 $descriptor['UploadFileURL'] = array(
915 'class' => 'UploadSourceField',
916 'section' => 'source',
917 'id' => 'wpUploadFileURL',
918 'radio-id' => 'wpSourceTypeurl',
919 'label-message' => 'sourceurl',
920 'upload-type' => 'url',
921 'radio' => &$radio,
922 'help' => $this->msg( 'upload-maxfilesize',
923 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] )
924 )->parse() .
925 $this->msg( 'word-separator' )->escaped() .
926 $this->msg( 'upload_source_url' )->parse(),
927 'checked' => $selectedSourceType == 'url',
928 );
929 }
930 Hooks::run( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
931
932 $descriptor['Extensions'] = array(
933 'type' => 'info',
934 'section' => 'source',
935 'default' => $this->getExtensionsMessage(),
936 'raw' => true,
937 );
938
939 return $descriptor;
940 }
941
942 /**
943 * Get the messages indicating which extensions are preferred and prohibitted.
944 *
945 * @return string HTML string containing the message
946 */
947 protected function getExtensionsMessage() {
948 # Print a list of allowed file extensions, if so configured. We ignore
949 # MIME type here, it's incomprehensible to most people and too long.
950 $config = $this->getConfig();
951
952 if ( $config->get( 'CheckFileExtensions' ) ) {
953 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
954 if ( $config->get( 'StrictFileExtensions' ) ) {
955 # Everything not permitted is banned
956 $extensionsList =
957 '<div id="mw-upload-permitted">' .
958 $this->msg( 'upload-permitted' )
959 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
960 ->numParams( count( $fileExtensions ) )
961 ->parseAsBlock() .
962 "</div>\n";
963 } else {
964 # We have to list both preferred and prohibited
965 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
966 $extensionsList =
967 '<div id="mw-upload-preferred">' .
968 $this->msg( 'upload-preferred' )
969 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
970 ->numParams( count( $fileExtensions ) )
971 ->parseAsBlock() .
972 "</div>\n" .
973 '<div id="mw-upload-prohibited">' .
974 $this->msg( 'upload-prohibited' )
975 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
976 ->numParams( count( $fileBlacklist ) )
977 ->parseAsBlock() .
978 "</div>\n";
979 }
980 } else {
981 # Everything is permitted.
982 $extensionsList = '';
983 }
984
985 return $extensionsList;
986 }
987
988 /**
989 * Get the descriptor of the fieldset that contains the file description
990 * input. The section is 'description'
991 *
992 * @return array Descriptor array
993 */
994 protected function getDescriptionSection() {
995 $config = $this->getConfig();
996 if ( $this->mSessionKey ) {
997 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
998 try {
999 $file = $stash->getFile( $this->mSessionKey );
1000 } catch ( Exception $e ) {
1001 $file = null;
1002 }
1003 if ( $file ) {
1004 global $wgContLang;
1005
1006 $mto = $file->transform( array( 'width' => 120 ) );
1007 $this->addHeaderText(
1008 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1009 Html::element( 'img', array(
1010 'src' => $mto->getUrl(),
1011 'class' => 'thumbimage',
1012 ) ) . '</div>', 'description' );
1013 }
1014 }
1015
1016 $descriptor = array(
1017 'DestFile' => array(
1018 'type' => 'text',
1019 'section' => 'description',
1020 'id' => 'wpDestFile',
1021 'label-message' => 'destfilename',
1022 'size' => 60,
1023 'default' => $this->mDestFile,
1024 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1025 'nodata' => strval( $this->mDestFile ) !== '',
1026 ),
1027 'UploadDescription' => array(
1028 'type' => 'textarea',
1029 'section' => 'description',
1030 'id' => 'wpUploadDescription',
1031 'label-message' => $this->mForReUpload
1032 ? 'filereuploadsummary'
1033 : 'fileuploadsummary',
1034 'default' => $this->mComment,
1035 'cols' => $this->getUser()->getIntOption( 'cols' ),
1036 'rows' => 8,
1037 )
1038 );
1039 if ( $this->mTextAfterSummary ) {
1040 $descriptor['UploadFormTextAfterSummary'] = array(
1041 'type' => 'info',
1042 'section' => 'description',
1043 'default' => $this->mTextAfterSummary,
1044 'raw' => true,
1045 );
1046 }
1047
1048 $descriptor += array(
1049 'EditTools' => array(
1050 'type' => 'edittools',
1051 'section' => 'description',
1052 'message' => 'edittools-upload',
1053 )
1054 );
1055
1056 if ( $this->mForReUpload ) {
1057 $descriptor['DestFile']['readonly'] = true;
1058 } else {
1059 $descriptor['License'] = array(
1060 'type' => 'select',
1061 'class' => 'Licenses',
1062 'section' => 'description',
1063 'id' => 'wpLicense',
1064 'label-message' => 'license',
1065 );
1066 }
1067
1068 if ( $config->get( 'UseCopyrightUpload' ) ) {
1069 $descriptor['UploadCopyStatus'] = array(
1070 'type' => 'text',
1071 'section' => 'description',
1072 'id' => 'wpUploadCopyStatus',
1073 'label-message' => 'filestatus',
1074 );
1075 $descriptor['UploadSource'] = array(
1076 'type' => 'text',
1077 'section' => 'description',
1078 'id' => 'wpUploadSource',
1079 'label-message' => 'filesource',
1080 );
1081 }
1082
1083 return $descriptor;
1084 }
1085
1086 /**
1087 * Get the descriptor of the fieldset that contains the upload options,
1088 * such as "watch this file". The section is 'options'
1089 *
1090 * @return array Descriptor array
1091 */
1092 protected function getOptionsSection() {
1093 $user = $this->getUser();
1094 if ( $user->isLoggedIn() ) {
1095 $descriptor = array(
1096 'Watchthis' => array(
1097 'type' => 'check',
1098 'id' => 'wpWatchthis',
1099 'label-message' => 'watchthisupload',
1100 'section' => 'options',
1101 'default' => $this->mWatch,
1102 )
1103 );
1104 }
1105 if ( !$this->mHideIgnoreWarning ) {
1106 $descriptor['IgnoreWarning'] = array(
1107 'type' => 'check',
1108 'id' => 'wpIgnoreWarning',
1109 'label-message' => 'ignorewarnings',
1110 'section' => 'options',
1111 );
1112 }
1113
1114 $descriptor['DestFileWarningAck'] = array(
1115 'type' => 'hidden',
1116 'id' => 'wpDestFileWarningAck',
1117 'default' => $this->mDestWarningAck ? '1' : '',
1118 );
1119
1120 if ( $this->mForReUpload ) {
1121 $descriptor['ForReUpload'] = array(
1122 'type' => 'hidden',
1123 'id' => 'wpForReUpload',
1124 'default' => '1',
1125 );
1126 }
1127
1128 return $descriptor;
1129 }
1130
1131 /**
1132 * Add the upload JS and show the form.
1133 */
1134 public function show() {
1135 $this->addUploadJS();
1136 parent::show();
1137 }
1138
1139 /**
1140 * Add upload JS to the OutputPage
1141 */
1142 protected function addUploadJS() {
1143 $config = $this->getConfig();
1144
1145 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1146 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1147 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1148 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1149
1150 $scriptVars = array(
1151 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1152 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1153 'wgUploadAutoFill' => !$this->mForReUpload &&
1154 // If we received mDestFile from the request, don't autofill
1155 // the wpDestFile textbox
1156 $this->mDestFile === '',
1157 'wgUploadSourceIds' => $this->mSourceIds,
1158 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1159 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1160 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1161 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1162 'wgMaxUploadSize' => $this->mMaxUploadSize,
1163 'wgFileCanRotate' => SpecialUpload::rotationEnabled(),
1164 );
1165
1166 $out = $this->getOutput();
1167 $out->addJsConfigVars( $scriptVars );
1168
1169 $out->addModules( array(
1170 'mediawiki.action.edit', // For <charinsert> support
1171 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1172 ) );
1173 }
1174
1175 /**
1176 * Empty function; submission is handled elsewhere.
1177 *
1178 * @return bool False
1179 */
1180 function trySubmit() {
1181 return false;
1182 }
1183 }
1184
1185 /**
1186 * A form field that contains a radio box in the label
1187 */
1188 class UploadSourceField extends HTMLTextField {
1189
1190 /**
1191 * @param array $cellAttributes
1192 * @return string
1193 */
1194 function getLabelHtml( $cellAttributes = array() ) {
1195 $id = $this->mParams['id'];
1196 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1197
1198 if ( !empty( $this->mParams['radio'] ) ) {
1199 if ( isset( $this->mParams['radio-id'] ) ) {
1200 $radioId = $this->mParams['radio-id'];
1201 } else {
1202 // Old way. For the benefit of extensions that do not define
1203 // the 'radio-id' key.
1204 $radioId = 'wpSourceType' . $this->mParams['upload-type'];
1205 }
1206
1207 $attribs = array(
1208 'name' => 'wpSourceType',
1209 'type' => 'radio',
1210 'id' => $radioId,
1211 'value' => $this->mParams['upload-type'],
1212 );
1213
1214 if ( !empty( $this->mParams['checked'] ) ) {
1215 $attribs['checked'] = 'checked';
1216 }
1217
1218 $label .= Html::element( 'input', $attribs );
1219 }
1220
1221 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1222 }
1223
1224 /**
1225 * @return int
1226 */
1227 function getSize() {
1228 return isset( $this->mParams['size'] )
1229 ? $this->mParams['size']
1230 : 60;
1231 }
1232 }