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