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