Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / specials / SpecialUpload.php
blob6fb133a89a1beb39a8d0a40e72c04e1a1e994657
1 <?php
2 /**
3 * Implements Special:Upload
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.
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.
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
20 * @file
21 * @ingroup SpecialPage
22 * @ingroup Upload
25 /**
26 * Form for handling uploads and special page.
28 * @ingroup SpecialPage
29 * @ingroup Upload
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 $request WebRequest : data posted.
37 public function __construct( $request = null ) {
38 parent::__construct( 'Upload', 'upload' );
41 /** Misc variables **/
42 public $mRequest; // The WebRequest or FauxRequest this form is supposed to handle
43 public $mSourceType;
45 /**
46 * @var UploadBase
48 public $mUpload;
50 /**
51 * @var LocalFile
53 public $mLocalFile;
54 public $mUploadClicked;
56 /** User input variables from the "description" section **/
57 public $mDesiredDestName; // The requested target file name
58 public $mComment;
59 public $mLicense;
61 /** User input variables from the root section **/
62 public $mIgnoreWarning;
63 public $mWatchThis;
64 public $mCopyrightStatus;
65 public $mCopyrightSource;
67 /** Hidden variables **/
68 public $mDestWarningAck;
69 public $mForReUpload; // The user followed an "overwrite this file" link
70 public $mCancelUpload; // The user clicked "Cancel and return to upload form" button
71 public $mTokenOk;
72 public $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
74 /** Text injection points for hooks not using HTMLForm **/
75 public $uploadFormTextTop;
76 public $uploadFormTextAfterSummary;
78 public $mWatchthis;
80 /**
81 * Initialize instance variables from request and create an Upload handler
83 protected function loadRequest() {
84 $this->mRequest = $request = $this->getRequest();
85 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
86 $this->mUpload = UploadBase::createFromRequest( $request );
87 $this->mUploadClicked = $request->wasPosted()
88 && ( $request->getCheck( 'wpUpload' )
89 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
91 // Guess the desired name from the filename if not provided
92 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
93 if ( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
94 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
96 $this->mComment = $request->getText( 'wpUploadDescription' );
97 $this->mLicense = $request->getText( 'wpLicense' );
99 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
100 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
101 || $request->getCheck( 'wpUploadIgnoreWarning' );
102 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
103 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
104 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
106 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
107 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
108 || $request->getCheck( 'wpReUpload' ); // b/w compat
110 // If it was posted check for the token (no remote POST'ing with user credentials)
111 $token = $request->getVal( 'wpEditToken' );
112 $this->mTokenOk = $this->getUser()->matchEditToken( $token );
114 $this->uploadFormTextTop = '';
115 $this->uploadFormTextAfterSummary = '';
119 * This page can be shown if uploading is enabled.
120 * Handle permission checking elsewhere in order to be able to show
121 * custom error messages.
123 * @param $user User object
124 * @return Boolean
126 public function userCanExecute( User $user ) {
127 return UploadBase::isEnabled() && parent::userCanExecute( $user );
131 * Special page entry point
133 public function execute( $par ) {
134 $this->setHeaders();
135 $this->outputHeader();
137 # Check uploading enabled
138 if ( !UploadBase::isEnabled() ) {
139 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
142 # Check permissions
143 $user = $this->getUser();
144 $permissionRequired = UploadBase::isAllowed( $user );
145 if ( $permissionRequired !== true ) {
146 throw new PermissionsError( $permissionRequired );
149 # Check blocks
150 if ( $user->isBlocked() ) {
151 throw new UserBlockedError( $user->getBlock() );
154 # Check whether we actually want to allow changing stuff
155 $this->checkReadOnly();
157 $this->loadRequest();
159 # Unsave the temporary file in case this was a cancelled upload
160 if ( $this->mCancelUpload ) {
161 if ( !$this->unsaveUploadedFile() ) {
162 # Something went wrong, so unsaveUploadedFile showed a warning
163 return;
167 # Process upload or show a form
168 if (
169 $this->mTokenOk && !$this->mCancelUpload &&
170 ( $this->mUpload && $this->mUploadClicked )
172 $this->processUpload();
173 } else {
174 # Backwards compatibility hook
175 if ( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
176 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
177 return;
179 $this->showUploadForm( $this->getUploadForm() );
182 # Cleanup
183 if ( $this->mUpload ) {
184 $this->mUpload->cleanupTempFile();
189 * Show the main upload form
191 * @param $form Mixed: an HTMLForm instance or HTML string to show
193 protected function showUploadForm( $form ) {
194 # Add links if file was previously deleted
195 if ( $this->mDesiredDestName ) {
196 $this->showViewDeletedLinks();
199 if ( $form instanceof HTMLForm ) {
200 $form->show();
201 } else {
202 $this->getOutput()->addHTML( $form );
208 * Get an UploadForm instance with title and text properly set.
210 * @param string $message HTML string to add to the form
211 * @param string $sessionKey session key in case this is a stashed upload
212 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
213 * @return UploadForm
215 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
216 # Initialize form
217 $form = new UploadForm( array(
218 'watch' => $this->getWatchCheck(),
219 'forreupload' => $this->mForReUpload,
220 'sessionkey' => $sessionKey,
221 'hideignorewarning' => $hideIgnoreWarning,
222 'destwarningack' => (bool)$this->mDestWarningAck,
224 'description' => $this->mComment,
225 'texttop' => $this->uploadFormTextTop,
226 'textaftersummary' => $this->uploadFormTextAfterSummary,
227 'destfile' => $this->mDesiredDestName,
228 ), $this->getContext() );
229 $form->setTitle( $this->getTitle() );
231 # Check the token, but only if necessary
232 if (
233 !$this->mTokenOk && !$this->mCancelUpload &&
234 ( $this->mUpload && $this->mUploadClicked )
236 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
239 # Give a notice if the user is uploading a file that has been deleted or moved
240 # Note that this is independent from the message 'filewasdeleted' that requires JS
241 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
242 $delNotice = ''; // empty by default
243 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
244 LogEventsList::showLogExtract( $delNotice, array( 'delete', 'move' ),
245 $desiredTitleObj,
246 '', array( 'lim' => 10,
247 'conds' => array( "log_action != 'revision'" ),
248 'showIfEmpty' => false,
249 'msgKey' => array( 'upload-recreate-warning' ) )
252 $form->addPreText( $delNotice );
254 # Add text to form
255 $form->addPreText( '<div id="uploadtext">' .
256 $this->msg( 'uploadtext', array( $this->mDesiredDestName ) )->parseAsBlock() .
257 '</div>' );
258 # Add upload error message
259 $form->addPreText( $message );
261 # Add footer to form
262 $uploadFooter = $this->msg( 'uploadfooter' );
263 if ( !$uploadFooter->isDisabled() ) {
264 $form->addPostText( '<div id="mw-upload-footer-message">'
265 . $uploadFooter->parseAsBlock() . "</div>\n" );
268 return $form;
272 * Shows the "view X deleted revivions link""
274 protected function showViewDeletedLinks() {
275 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
276 $user = $this->getUser();
277 // Show a subtitle link to deleted revisions (to sysops et al only)
278 if ( $title instanceof Title ) {
279 $count = $title->isDeleted();
280 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
281 $restorelink = Linker::linkKnown(
282 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
283 $this->msg( 'restorelink' )->numParams( $count )->escaped()
285 $link = $this->msg( $user->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted' )
286 ->rawParams( $restorelink )->parseAsBlock();
287 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
293 * Stashes the upload and shows the main upload form.
295 * Note: only errors that can be handled by changing the name or
296 * description should be redirected here. It should be assumed that the
297 * file itself is sane and has passed UploadBase::verifyFile. This
298 * essentially means that UploadBase::VERIFICATION_ERROR and
299 * UploadBase::EMPTY_FILE should not be passed here.
301 * @param string $message HTML message to be passed to mainUploadForm
303 protected function showRecoverableUploadError( $message ) {
304 $sessionKey = $this->mUpload->stashSession();
305 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
306 '<div class="error">' . $message . "</div>\n";
308 $form = $this->getUploadForm( $message, $sessionKey );
309 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
310 $this->showUploadForm( $form );
313 * Stashes the upload, shows the main form, but adds a "continue anyway button".
314 * Also checks whether there are actually warnings to display.
316 * @param $warnings Array
317 * @return boolean true if warnings were displayed, false if there are no
318 * warnings and it should continue processing
320 protected function showUploadWarning( $warnings ) {
321 # If there are no warnings, or warnings we can ignore, return early.
322 # mDestWarningAck is set when some javascript has shown the warning
323 # to the user. mForReUpload is set when the user clicks the "upload a
324 # new version" link.
325 if ( !$warnings || ( count( $warnings ) == 1 &&
326 isset( $warnings['exists'] ) &&
327 ( $this->mDestWarningAck || $this->mForReUpload ) ) )
329 return false;
332 $sessionKey = $this->mUpload->stashSession();
334 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
335 . '<ul class="warning">';
336 foreach ( $warnings as $warning => $args ) {
337 if ( $warning == 'badfilename' ) {
338 $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
340 if ( $warning == 'exists' ) {
341 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
342 } elseif ( $warning == 'duplicate' ) {
343 $msg = self::getDupeWarning( $args );
344 } elseif ( $warning == 'duplicate-archive' ) {
345 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
346 Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
347 . "</li>\n";
348 } else {
349 if ( $args === true ) {
350 $args = array();
351 } elseif ( !is_array( $args ) ) {
352 $args = array( $args );
354 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
356 $warningHtml .= $msg;
358 $warningHtml .= "</ul>\n";
359 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
361 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
362 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
363 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
364 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
366 $this->showUploadForm( $form );
368 # Indicate that we showed a form
369 return true;
373 * Show the upload form with error message, but do not stash the file.
375 * @param string $message HTML string
377 protected function showUploadError( $message ) {
378 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
379 '<div class="error">' . $message . "</div>\n";
380 $this->showUploadForm( $this->getUploadForm( $message ) );
384 * Do the upload.
385 * Checks are made in SpecialUpload::execute()
387 protected function processUpload() {
388 // Fetch the file if required
389 $status = $this->mUpload->fetchFile();
390 if ( !$status->isOK() ) {
391 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
392 return;
395 if ( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
396 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
397 // This code path is deprecated. If you want to break upload processing
398 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
399 // and UploadBase::verifyFile.
400 // If you use this hook to break uploading, the user will be returned
401 // an empty form with no error message whatsoever.
402 return;
405 // Upload verification
406 $details = $this->mUpload->verifyUpload();
407 if ( $details['status'] != UploadBase::OK ) {
408 $this->processVerificationError( $details );
409 return;
412 // Verify permissions for this title
413 $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
414 if ( $permErrors !== true ) {
415 $code = array_shift( $permErrors[0] );
416 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
417 return;
420 $this->mLocalFile = $this->mUpload->getLocalFile();
422 // Check warnings if necessary
423 if ( !$this->mIgnoreWarning ) {
424 $warnings = $this->mUpload->checkWarnings();
425 if ( $this->showUploadWarning( $warnings ) ) {
426 return;
430 // Get the page text if this is not a reupload
431 if ( !$this->mForReUpload ) {
432 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
433 $this->mCopyrightStatus, $this->mCopyrightSource );
434 } else {
435 $pageText = false;
437 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $this->getUser() );
438 if ( !$status->isGood() ) {
439 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
440 return;
443 // Success, redirect to description page
444 $this->mUploadSuccessful = true;
445 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
446 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
450 * Get the initial image page text based on a comment and optional file status information
451 * @param $comment string
452 * @param $license string
453 * @param $copyStatus string
454 * @param $source string
455 * @return string
457 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
458 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
459 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
461 $msg = array();
462 /* These messages are transcluded into the actual text of the description page.
463 * Thus, forcing them as content messages makes the upload to produce an int: template
464 * instead of hardcoding it there in the uploader language.
466 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
467 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
468 $msg[$msgName] = "{{int:$msgName}}";
469 } else {
470 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
474 if ( $wgUseCopyrightUpload ) {
475 $licensetxt = '';
476 if ( $license != '' ) {
477 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
479 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
480 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
481 "$licensetxt" .
482 '== ' . $msg['filesource'] . " ==\n" . $source;
483 } else {
484 if ( $license != '' ) {
485 $filedesc = $comment == '' ? '' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
486 $pageText = $filedesc .
487 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
488 } else {
489 $pageText = $comment;
492 return $pageText;
496 * See if we should check the 'watch this page' checkbox on the form
497 * based on the user's preferences and whether we're being asked
498 * to create a new file or update an existing one.
500 * In the case where 'watch edits' is off but 'watch creations' is on,
501 * we'll leave the box unchecked.
503 * Note that the page target can be changed *on the form*, so our check
504 * state can get out of sync.
505 * @return Bool|String
507 protected function getWatchCheck() {
508 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
509 // Watch all edits!
510 return true;
513 $local = wfLocalFile( $this->mDesiredDestName );
514 if ( $local && $local->exists() ) {
515 // We're uploading a new version of an existing file.
516 // No creation, so don't watch it if we're not already.
517 return $this->getUser()->isWatched( $local->getTitle() );
518 } else {
519 // New page should get watched if that's our option.
520 return $this->getUser()->getOption( 'watchcreations' );
525 * Provides output to the user for a result of UploadBase::verifyUpload
527 * @param array $details result of UploadBase::verifyUpload
528 * @throws MWException
530 protected function processVerificationError( $details ) {
531 global $wgFileExtensions;
533 switch( $details['status'] ) {
535 /** Statuses that only require name changing **/
536 case UploadBase::MIN_LENGTH_PARTNAME:
537 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
538 break;
539 case UploadBase::ILLEGAL_FILENAME:
540 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
541 $details['filtered'] )->parse() );
542 break;
543 case UploadBase::FILENAME_TOO_LONG:
544 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
545 break;
546 case UploadBase::FILETYPE_MISSING:
547 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
548 break;
549 case UploadBase::WINDOWS_NONASCII_FILENAME:
550 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
551 break;
553 /** Statuses that require reuploading **/
554 case UploadBase::EMPTY_FILE:
555 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
556 break;
557 case UploadBase::FILE_TOO_LARGE:
558 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
559 break;
560 case UploadBase::FILETYPE_BADTYPE:
561 $msg = $this->msg( 'filetype-banned-type' );
562 if ( isset( $details['blacklistedExt'] ) ) {
563 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
564 } else {
565 $msg->params( $details['finalExt'] );
567 $msg->params( $this->getLanguage()->commaList( $wgFileExtensions ),
568 count( $wgFileExtensions ) );
570 // Add PLURAL support for the first parameter. This results
571 // in a bit unlogical parameter sequence, but does not break
572 // old translations
573 if ( isset( $details['blacklistedExt'] ) ) {
574 $msg->params( count( $details['blacklistedExt'] ) );
575 } else {
576 $msg->params( 1 );
579 $this->showUploadError( $msg->parse() );
580 break;
581 case UploadBase::VERIFICATION_ERROR:
582 unset( $details['status'] );
583 $code = array_shift( $details['details'] );
584 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
585 break;
586 case UploadBase::HOOK_ABORTED:
587 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
588 $args = $details['error'];
589 $error = array_shift( $args );
590 } else {
591 $error = $details['error'];
592 $args = null;
595 $this->showUploadError( $this->msg( $error, $args )->parse() );
596 break;
597 default:
598 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
603 * Remove a temporarily kept file stashed by saveTempUploadedFile().
605 * @return Boolean: success
607 protected function unsaveUploadedFile() {
608 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
609 return true;
611 $success = $this->mUpload->unsaveUploadedFile();
612 if ( !$success ) {
613 $this->getOutput()->showFileDeleteError( $this->mUpload->getTempPath() );
614 return false;
615 } else {
616 return true;
620 /*** Functions for formatting warnings ***/
623 * Formats a result of UploadBase::getExistsWarning as HTML
624 * This check is static and can be done pre-upload via AJAX
626 * @param array $exists the result of UploadBase::getExistsWarning
627 * @return String: empty string if there is no warning or an HTML fragment
629 public static function getExistsWarning( $exists ) {
630 if ( !$exists ) {
631 return '';
634 $file = $exists['file'];
635 $filename = $file->getTitle()->getPrefixedText();
636 $warning = '';
638 if ( $exists['warning'] == 'exists' ) {
639 // Exact match
640 $warning = wfMessage( 'fileexists', $filename )->parse();
641 } elseif ( $exists['warning'] == 'page-exists' ) {
642 // Page exists but file does not
643 $warning = wfMessage( 'filepageexists', $filename )->parse();
644 } elseif ( $exists['warning'] == 'exists-normalized' ) {
645 $warning = wfMessage( 'fileexists-extension', $filename,
646 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
647 } elseif ( $exists['warning'] == 'thumb' ) {
648 // Swapped argument order compared with other messages for backwards compatibility
649 $warning = wfMessage( 'fileexists-thumbnail-yes',
650 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
651 } elseif ( $exists['warning'] == 'thumb-name' ) {
652 // Image w/o '180px-' does not exists, but we do not like these filenames
653 $name = $file->getName();
654 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
655 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
656 } elseif ( $exists['warning'] == 'bad-prefix' ) {
657 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
658 } elseif ( $exists['warning'] == 'was-deleted' ) {
659 # If the file existed before and was deleted, warn the user of this
660 $ltitle = SpecialPage::getTitleFor( 'Log' );
661 $llink = Linker::linkKnown(
662 $ltitle,
663 wfMessage( 'deletionlog' )->escaped(),
664 array(),
665 array(
666 'type' => 'delete',
667 'page' => $filename
670 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
673 return $warning;
677 * Get a list of warnings
679 * @param string $filename local filename, e.g. 'file exists', 'non-descriptive filename'
680 * @return Array: list of warning messages
682 public static function ajaxGetExistsWarning( $filename ) {
683 $file = wfFindFile( $filename );
684 if ( !$file ) {
685 // Force local file so we have an object to do further checks against
686 // if there isn't an exact match...
687 $file = wfLocalFile( $filename );
689 $s = '&#160;';
690 if ( $file ) {
691 $exists = UploadBase::getExistsWarning( $file );
692 $warning = self::getExistsWarning( $exists );
693 if ( $warning !== '' ) {
694 $s = "<div>$warning</div>";
697 return $s;
701 * Construct a warning and a gallery from an array of duplicate files.
702 * @param $dupes array
703 * @return string
705 public static function getDupeWarning( $dupes ) {
706 if ( !$dupes ) {
707 return '';
710 $gallery = new ImageGallery;
711 $gallery->setShowBytes( false );
712 foreach ( $dupes as $file ) {
713 $gallery->add( $file->getTitle() );
715 return '<li>' .
716 wfMessage( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
717 $gallery->toHtml() . "</li>\n";
720 protected function getGroupName() {
721 return 'media';
726 * Sub class of HTMLForm that provides the form section of SpecialUpload
728 class UploadForm extends HTMLForm {
729 protected $mWatch;
730 protected $mForReUpload;
731 protected $mSessionKey;
732 protected $mHideIgnoreWarning;
733 protected $mDestWarningAck;
734 protected $mDestFile;
736 protected $mComment;
737 protected $mTextTop;
738 protected $mTextAfterSummary;
740 protected $mSourceIds;
742 protected $mMaxFileSize = array();
744 protected $mMaxUploadSize = array();
746 public function __construct( array $options = array(), IContextSource $context = null ) {
747 $this->mWatch = !empty( $options['watch'] );
748 $this->mForReUpload = !empty( $options['forreupload'] );
749 $this->mSessionKey = isset( $options['sessionkey'] )
750 ? $options['sessionkey'] : '';
751 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
752 $this->mDestWarningAck = !empty( $options['destwarningack'] );
753 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
755 $this->mComment = isset( $options['description'] ) ?
756 $options['description'] : '';
758 $this->mTextTop = isset( $options['texttop'] )
759 ? $options['texttop'] : '';
761 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
762 ? $options['textaftersummary'] : '';
764 $sourceDescriptor = $this->getSourceSection();
765 $descriptor = $sourceDescriptor
766 + $this->getDescriptionSection()
767 + $this->getOptionsSection();
769 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
770 parent::__construct( $descriptor, $context, 'upload' );
772 # Set some form properties
773 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
774 $this->setSubmitName( 'wpUpload' );
775 # Used message keys: 'accesskey-upload', 'tooltip-upload'
776 $this->setSubmitTooltip( 'upload' );
777 $this->setId( 'mw-upload-form' );
779 # Build a list of IDs for javascript insertion
780 $this->mSourceIds = array();
781 foreach ( $sourceDescriptor as $field ) {
782 if ( !empty( $field['id'] ) ) {
783 $this->mSourceIds[] = $field['id'];
790 * Get the descriptor of the fieldset that contains the file source
791 * selection. The section is 'source'
793 * @return Array: descriptor array
795 protected function getSourceSection() {
796 global $wgCopyUploadsFromSpecialUpload;
798 if ( $this->mSessionKey ) {
799 return array(
800 'SessionKey' => array(
801 'type' => 'hidden',
802 'default' => $this->mSessionKey,
804 'SourceType' => array(
805 'type' => 'hidden',
806 'default' => 'Stash',
811 $canUploadByUrl = UploadFromUrl::isEnabled()
812 && UploadFromUrl::isAllowed( $this->getUser() )
813 && $wgCopyUploadsFromSpecialUpload;
814 $radio = $canUploadByUrl;
815 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
817 $descriptor = array();
818 if ( $this->mTextTop ) {
819 $descriptor['UploadFormTextTop'] = array(
820 'type' => 'info',
821 'section' => 'source',
822 'default' => $this->mTextTop,
823 'raw' => true,
827 $this->mMaxUploadSize['file'] = UploadBase::getMaxUploadSize( 'file' );
828 # Limit to upload_max_filesize unless we are running under HipHop and
829 # that setting doesn't exist
830 if ( !wfIsHipHop() ) {
831 $this->mMaxUploadSize['file'] = min( $this->mMaxUploadSize['file'],
832 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
833 wfShorthandToInteger( ini_get( 'post_max_size' ) )
837 $descriptor['UploadFile'] = array(
838 'class' => 'UploadSourceField',
839 'section' => 'source',
840 'type' => 'file',
841 'id' => 'wpUploadFile',
842 'label-message' => 'sourcefilename',
843 'upload-type' => 'File',
844 'radio' => &$radio,
845 'help' => $this->msg( 'upload-maxfilesize',
846 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] ) )
847 ->parse() .
848 $this->msg( 'word-separator' )->escaped() .
849 $this->msg( 'upload_source_file' )->escaped(),
850 'checked' => $selectedSourceType == 'file',
853 if ( $canUploadByUrl ) {
854 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
855 $descriptor['UploadFileURL'] = array(
856 'class' => 'UploadSourceField',
857 'section' => 'source',
858 'id' => 'wpUploadFileURL',
859 'label-message' => 'sourceurl',
860 'upload-type' => 'url',
861 'radio' => &$radio,
862 'help' => $this->msg( 'upload-maxfilesize',
863 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] ) )
864 ->parse() .
865 $this->msg( 'word-separator' )->escaped() .
866 $this->msg( 'upload_source_url' )->escaped(),
867 'checked' => $selectedSourceType == 'url',
870 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
872 $descriptor['Extensions'] = array(
873 'type' => 'info',
874 'section' => 'source',
875 'default' => $this->getExtensionsMessage(),
876 'raw' => true,
878 return $descriptor;
882 * Get the messages indicating which extensions are preferred and prohibitted.
884 * @return String: HTML string containing the message
886 protected function getExtensionsMessage() {
887 # Print a list of allowed file extensions, if so configured. We ignore
888 # MIME type here, it's incomprehensible to most people and too long.
889 global $wgCheckFileExtensions, $wgStrictFileExtensions,
890 $wgFileExtensions, $wgFileBlacklist;
892 if ( $wgCheckFileExtensions ) {
893 if ( $wgStrictFileExtensions ) {
894 # Everything not permitted is banned
895 $extensionsList =
896 '<div id="mw-upload-permitted">' .
897 $this->msg( 'upload-permitted', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) )->parseAsBlock() .
898 "</div>\n";
899 } else {
900 # We have to list both preferred and prohibited
901 $extensionsList =
902 '<div id="mw-upload-preferred">' .
903 $this->msg( 'upload-preferred', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) )->parseAsBlock() .
904 "</div>\n" .
905 '<div id="mw-upload-prohibited">' .
906 $this->msg( 'upload-prohibited', $this->getContext()->getLanguage()->commaList( $wgFileBlacklist ) )->parseAsBlock() .
907 "</div>\n";
909 } else {
910 # Everything is permitted.
911 $extensionsList = '';
913 return $extensionsList;
917 * Get the descriptor of the fieldset that contains the file description
918 * input. The section is 'description'
920 * @return Array: descriptor array
922 protected function getDescriptionSection() {
923 if ( $this->mSessionKey ) {
924 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
925 try {
926 $file = $stash->getFile( $this->mSessionKey );
927 } catch ( MWException $e ) {
928 $file = null;
930 if ( $file ) {
931 global $wgContLang;
933 $mto = $file->transform( array( 'width' => 120 ) );
934 $this->addHeaderText(
935 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
936 Html::element( 'img', array(
937 'src' => $mto->getUrl(),
938 'class' => 'thumbimage',
939 ) ) . '</div>', 'description' );
943 $descriptor = array(
944 'DestFile' => array(
945 'type' => 'text',
946 'section' => 'description',
947 'id' => 'wpDestFile',
948 'label-message' => 'destfilename',
949 'size' => 60,
950 'default' => $this->mDestFile,
951 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
952 'nodata' => strval( $this->mDestFile ) !== '',
954 'UploadDescription' => array(
955 'type' => 'textarea',
956 'section' => 'description',
957 'id' => 'wpUploadDescription',
958 'label-message' => $this->mForReUpload
959 ? 'filereuploadsummary'
960 : 'fileuploadsummary',
961 'default' => $this->mComment,
962 'cols' => $this->getUser()->getIntOption( 'cols' ),
963 'rows' => 8,
966 if ( $this->mTextAfterSummary ) {
967 $descriptor['UploadFormTextAfterSummary'] = array(
968 'type' => 'info',
969 'section' => 'description',
970 'default' => $this->mTextAfterSummary,
971 'raw' => true,
975 $descriptor += array(
976 'EditTools' => array(
977 'type' => 'edittools',
978 'section' => 'description',
979 'message' => 'edittools-upload',
983 if ( $this->mForReUpload ) {
984 $descriptor['DestFile']['readonly'] = true;
985 } else {
986 $descriptor['License'] = array(
987 'type' => 'select',
988 'class' => 'Licenses',
989 'section' => 'description',
990 'id' => 'wpLicense',
991 'label-message' => 'license',
995 global $wgUseCopyrightUpload;
996 if ( $wgUseCopyrightUpload ) {
997 $descriptor['UploadCopyStatus'] = array(
998 'type' => 'text',
999 'section' => 'description',
1000 'id' => 'wpUploadCopyStatus',
1001 'label-message' => 'filestatus',
1003 $descriptor['UploadSource'] = array(
1004 'type' => 'text',
1005 'section' => 'description',
1006 'id' => 'wpUploadSource',
1007 'label-message' => 'filesource',
1011 return $descriptor;
1015 * Get the descriptor of the fieldset that contains the upload options,
1016 * such as "watch this file". The section is 'options'
1018 * @return Array: descriptor array
1020 protected function getOptionsSection() {
1021 $user = $this->getUser();
1022 if ( $user->isLoggedIn() ) {
1023 $descriptor = array(
1024 'Watchthis' => array(
1025 'type' => 'check',
1026 'id' => 'wpWatchthis',
1027 'label-message' => 'watchthisupload',
1028 'section' => 'options',
1029 'default' => $user->getOption( 'watchcreations' ),
1033 if ( !$this->mHideIgnoreWarning ) {
1034 $descriptor['IgnoreWarning'] = array(
1035 'type' => 'check',
1036 'id' => 'wpIgnoreWarning',
1037 'label-message' => 'ignorewarnings',
1038 'section' => 'options',
1042 $descriptor['DestFileWarningAck'] = array(
1043 'type' => 'hidden',
1044 'id' => 'wpDestFileWarningAck',
1045 'default' => $this->mDestWarningAck ? '1' : '',
1048 if ( $this->mForReUpload ) {
1049 $descriptor['ForReUpload'] = array(
1050 'type' => 'hidden',
1051 'id' => 'wpForReUpload',
1052 'default' => '1',
1056 return $descriptor;
1060 * Add the upload JS and show the form.
1062 public function show() {
1063 $this->addUploadJS();
1064 parent::show();
1068 * Add upload JS to the OutputPage
1070 protected function addUploadJS() {
1071 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1073 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1074 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1075 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1077 $scriptVars = array(
1078 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1079 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1080 'wgUploadAutoFill' => !$this->mForReUpload &&
1081 // If we received mDestFile from the request, don't autofill
1082 // the wpDestFile textbox
1083 $this->mDestFile === '',
1084 'wgUploadSourceIds' => $this->mSourceIds,
1085 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1086 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1087 'wgMaxUploadSize' => $this->mMaxUploadSize,
1090 $out = $this->getOutput();
1091 $out->addJsConfigVars( $scriptVars );
1093 $out->addModules( array(
1094 'mediawiki.action.edit', // For <charinsert> support
1095 'mediawiki.legacy.upload', // Old form stuff...
1096 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1097 ) );
1101 * Empty function; submission is handled elsewhere.
1103 * @return bool false
1105 function trySubmit() {
1106 return false;
1112 * A form field that contains a radio box in the label
1114 class UploadSourceField extends HTMLTextField {
1117 * @param $cellAttributes array
1118 * @return string
1120 function getLabelHtml( $cellAttributes = array() ) {
1121 $id = $this->mParams['id'];
1122 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1124 if ( !empty( $this->mParams['radio'] ) ) {
1125 $attribs = array(
1126 'name' => 'wpSourceType',
1127 'type' => 'radio',
1128 'id' => $id,
1129 'value' => $this->mParams['upload-type'],
1131 if ( !empty( $this->mParams['checked'] ) ) {
1132 $attribs['checked'] = 'checked';
1134 $label .= Html::element( 'input', $attribs );
1137 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1141 * @return int
1143 function getSize() {
1144 return isset( $this->mParams['size'] )
1145 ? $this->mParams['size']
1146 : 60;