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