Remove cols and rows preferences
[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 LogEventsList::showLogExtract( $delNotice, [ 'delete', 'move' ],
285 $desiredTitleObj,
286 '', [ 'lim' => 10,
287 'conds' => [ "log_action != 'revision'" ],
288 'showIfEmpty' => false,
289 'msgKey' => [ 'upload-recreate-warning' ] ]
290 );
291 }
292 $form->addPreText( $delNotice );
293
294 # Add text to form
295 $form->addPreText( '<div id="uploadtext">' .
296 $this->msg( 'uploadtext', [ $this->mDesiredDestName ] )->parseAsBlock() .
297 '</div>' );
298 # Add upload error message
299 $form->addPreText( $message );
300
301 # Add footer to form
302 $uploadFooter = $this->msg( 'uploadfooter' );
303 if ( !$uploadFooter->isDisabled() ) {
304 $form->addPostText( '<div id="mw-upload-footer-message">'
305 . $uploadFooter->parseAsBlock() . "</div>\n" );
306 }
307
308 return $form;
309 }
310
311 /**
312 * Shows the "view X deleted revivions link""
313 */
314 protected function showViewDeletedLinks() {
315 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
316 $user = $this->getUser();
317 // Show a subtitle link to deleted revisions (to sysops et al only)
318 if ( $title instanceof Title ) {
319 $count = $title->isDeleted();
320 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
321 $restorelink = $this->getLinkRenderer()->makeKnownLink(
322 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
323 $this->msg( 'restorelink' )->numParams( $count )->text()
324 );
325 $link = $this->msg( $user->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted' )
326 ->rawParams( $restorelink )->parseAsBlock();
327 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
328 }
329 }
330 }
331
332 /**
333 * Stashes the upload and shows the main upload form.
334 *
335 * Note: only errors that can be handled by changing the name or
336 * description should be redirected here. It should be assumed that the
337 * file itself is sane and has passed UploadBase::verifyFile. This
338 * essentially means that UploadBase::VERIFICATION_ERROR and
339 * UploadBase::EMPTY_FILE should not be passed here.
340 *
341 * @param string $message HTML message to be passed to mainUploadForm
342 */
343 protected function showRecoverableUploadError( $message ) {
344 $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
345 if ( $stashStatus->isGood() ) {
346 $sessionKey = $stashStatus->getValue()->getFileKey();
347 } else {
348 $sessionKey = null;
349 // TODO Add a warning message about the failure to stash here?
350 }
351 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
352 '<div class="error">' . $message . "</div>\n";
353
354 $form = $this->getUploadForm( $message, $sessionKey );
355 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
356 $this->showUploadForm( $form );
357 }
358
359 /**
360 * Stashes the upload, shows the main form, but adds a "continue anyway button".
361 * Also checks whether there are actually warnings to display.
362 *
363 * @param array $warnings
364 * @return bool True if warnings were displayed, false if there are no
365 * warnings and it should continue processing
366 */
367 protected function showUploadWarning( $warnings ) {
368 # If there are no warnings, or warnings we can ignore, return early.
369 # mDestWarningAck is set when some javascript has shown the warning
370 # to the user. mForReUpload is set when the user clicks the "upload a
371 # new version" link.
372 if ( !$warnings || ( count( $warnings ) == 1
373 && isset( $warnings['exists'] )
374 && ( $this->mDestWarningAck || $this->mForReUpload ) )
375 ) {
376 return false;
377 }
378
379 $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
380 if ( $stashStatus->isGood() ) {
381 $sessionKey = $stashStatus->getValue()->getFileKey();
382 } else {
383 $sessionKey = null;
384 // TODO Add a warning message about the failure to stash here?
385 }
386
387 // Add styles for the warning, reused from the live preview
388 $this->getOutput()->addModuleStyles( 'mediawiki.special.upload.styles' );
389
390 $linkRenderer = $this->getLinkRenderer();
391 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
392 . '<div class="mw-destfile-warning"><ul>';
393 foreach ( $warnings as $warning => $args ) {
394 if ( $warning == 'badfilename' ) {
395 $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
396 }
397 if ( $warning == 'exists' ) {
398 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
399 } elseif ( $warning == 'no-change' ) {
400 $file = $args;
401 $filename = $file->getTitle()->getPrefixedText();
402 $msg = "\t<li>" . wfMessage( 'fileexists-no-change', $filename )->parse() . "</li>\n";
403 } elseif ( $warning == 'duplicate-version' ) {
404 $file = $args[0];
405 $count = count( $args );
406 $filename = $file->getTitle()->getPrefixedText();
407 $message = wfMessage( 'fileexists-duplicate-version' )
408 ->params( $filename )
409 ->numParams( $count );
410 $msg = "\t<li>" . $message->parse() . "</li>\n";
411 } elseif ( $warning == 'was-deleted' ) {
412 # If the file existed before and was deleted, warn the user of this
413 $ltitle = SpecialPage::getTitleFor( 'Log' );
414 $llink = $linkRenderer->makeKnownLink(
415 $ltitle,
416 wfMessage( 'deletionlog' )->text(),
417 [],
418 [
419 'type' => 'delete',
420 'page' => Title::makeTitle( NS_FILE, $args )->getPrefixedText(),
421 ]
422 );
423 $msg = "\t<li>" . wfMessage( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
424 } elseif ( $warning == 'duplicate' ) {
425 $msg = $this->getDupeWarning( $args );
426 } elseif ( $warning == 'duplicate-archive' ) {
427 if ( $args === '' ) {
428 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
429 . "</li>\n";
430 } else {
431 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
432 Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
433 . "</li>\n";
434 }
435 } else {
436 if ( $args === true ) {
437 $args = [];
438 } elseif ( !is_array( $args ) ) {
439 $args = [ $args ];
440 }
441 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
442 }
443 $warningHtml .= $msg;
444 }
445 $warningHtml .= "</ul></div>\n";
446 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
447
448 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
449 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
450 $form->addButton( [
451 'name' => 'wpUploadIgnoreWarning',
452 'value' => $this->msg( 'ignorewarning' )->text()
453 ] );
454 $form->addButton( [
455 'name' => 'wpCancelUpload',
456 'value' => $this->msg( 'reuploaddesc' )->text()
457 ] );
458
459 $this->showUploadForm( $form );
460
461 # Indicate that we showed a form
462 return true;
463 }
464
465 /**
466 * Show the upload form with error message, but do not stash the file.
467 *
468 * @param string $message HTML string
469 */
470 protected function showUploadError( $message ) {
471 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
472 '<div class="error">' . $message . "</div>\n";
473 $this->showUploadForm( $this->getUploadForm( $message ) );
474 }
475
476 /**
477 * Do the upload.
478 * Checks are made in SpecialUpload::execute()
479 */
480 protected function processUpload() {
481 // Fetch the file if required
482 $status = $this->mUpload->fetchFile();
483 if ( !$status->isOK() ) {
484 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
485
486 return;
487 }
488 // Avoid PHP 7.1 warning of passing $this by reference
489 $upload = $this;
490 if ( !Hooks::run( 'UploadForm:BeforeProcessing', [ &$upload ] ) ) {
491 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
492 // This code path is deprecated. If you want to break upload processing
493 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
494 // and UploadBase::verifyFile.
495 // If you use this hook to break uploading, the user will be returned
496 // an empty form with no error message whatsoever.
497 return;
498 }
499
500 // Upload verification
501 $details = $this->mUpload->verifyUpload();
502 if ( $details['status'] != UploadBase::OK ) {
503 $this->processVerificationError( $details );
504
505 return;
506 }
507
508 // Verify permissions for this title
509 $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
510 if ( $permErrors !== true ) {
511 $code = array_shift( $permErrors[0] );
512 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
513
514 return;
515 }
516
517 $this->mLocalFile = $this->mUpload->getLocalFile();
518
519 // Check warnings if necessary
520 if ( !$this->mIgnoreWarning ) {
521 $warnings = $this->mUpload->checkWarnings();
522 if ( $this->showUploadWarning( $warnings ) ) {
523 return;
524 }
525 }
526
527 // This is as late as we can throttle, after expected issues have been handled
528 if ( UploadBase::isThrottled( $this->getUser() ) ) {
529 $this->showRecoverableUploadError(
530 $this->msg( 'actionthrottledtext' )->escaped()
531 );
532 return;
533 }
534
535 // Get the page text if this is not a reupload
536 if ( !$this->mForReUpload ) {
537 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
538 $this->mCopyrightStatus, $this->mCopyrightSource, $this->getConfig() );
539 } else {
540 $pageText = false;
541 }
542
543 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
544 if ( is_null( $changeTags ) || $changeTags === '' ) {
545 $changeTags = [];
546 } else {
547 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
548 }
549
550 if ( $changeTags ) {
551 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
552 $changeTags, $this->getUser() );
553 if ( !$changeTagsStatus->isOK() ) {
554 $this->showUploadError( $this->getOutput()->parse( $changeTagsStatus->getWikiText() ) );
555
556 return;
557 }
558 }
559
560 $status = $this->mUpload->performUpload(
561 $this->mComment,
562 $pageText,
563 $this->mWatchthis,
564 $this->getUser(),
565 $changeTags
566 );
567
568 if ( !$status->isGood() ) {
569 $this->showRecoverableUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
570
571 return;
572 }
573
574 // Success, redirect to description page
575 $this->mUploadSuccessful = true;
576 // Avoid PHP 7.1 warning of passing $this by reference
577 $upload = $this;
578 Hooks::run( 'SpecialUploadComplete', [ &$upload ] );
579 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
580 }
581
582 /**
583 * Get the initial image page text based on a comment and optional file status information
584 * @param string $comment
585 * @param string $license
586 * @param string $copyStatus
587 * @param string $source
588 * @param Config $config Configuration object to load data from
589 * @return string
590 */
591 public static function getInitialPageText( $comment = '', $license = '',
592 $copyStatus = '', $source = '', Config $config = null
593 ) {
594 if ( $config === null ) {
595 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
596 $config = MediaWikiServices::getInstance()->getMainConfig();
597 }
598
599 $msg = [];
600 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
601 /* These messages are transcluded into the actual text of the description page.
602 * Thus, forcing them as content messages makes the upload to produce an int: template
603 * instead of hardcoding it there in the uploader language.
604 */
605 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
606 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
607 $msg[$msgName] = "{{int:$msgName}}";
608 } else {
609 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
610 }
611 }
612
613 if ( $config->get( 'UseCopyrightUpload' ) ) {
614 $licensetxt = '';
615 if ( $license != '' ) {
616 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
617 }
618 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
619 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
620 "$licensetxt" .
621 '== ' . $msg['filesource'] . " ==\n" . $source;
622 } else {
623 if ( $license != '' ) {
624 $filedesc = $comment == '' ? '' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
625 $pageText = $filedesc .
626 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
627 } else {
628 $pageText = $comment;
629 }
630 }
631
632 return $pageText;
633 }
634
635 /**
636 * See if we should check the 'watch this page' checkbox on the form
637 * based on the user's preferences and whether we're being asked
638 * to create a new file or update an existing one.
639 *
640 * In the case where 'watch edits' is off but 'watch creations' is on,
641 * we'll leave the box unchecked.
642 *
643 * Note that the page target can be changed *on the form*, so our check
644 * state can get out of sync.
645 * @return bool|string
646 */
647 protected function getWatchCheck() {
648 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
649 // Watch all edits!
650 return true;
651 }
652
653 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
654 if ( $desiredTitleObj instanceof Title && $this->getUser()->isWatched( $desiredTitleObj ) ) {
655 // Already watched, don't change that
656 return true;
657 }
658
659 $local = wfLocalFile( $this->mDesiredDestName );
660 if ( $local && $local->exists() ) {
661 // We're uploading a new version of an existing file.
662 // No creation, so don't watch it if we're not already.
663 return false;
664 } else {
665 // New page should get watched if that's our option.
666 return $this->getUser()->getOption( 'watchcreations' ) ||
667 $this->getUser()->getOption( 'watchuploads' );
668 }
669 }
670
671 /**
672 * Provides output to the user for a result of UploadBase::verifyUpload
673 *
674 * @param array $details Result of UploadBase::verifyUpload
675 * @throws MWException
676 */
677 protected function processVerificationError( $details ) {
678 switch ( $details['status'] ) {
679
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 foreach ( $dupes as $file ) {
823 $gallery->add( $file->getTitle() );
824 }
825
826 return '<li>' .
827 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
828 $gallery->toHTML() . "</li>\n";
829 }
830
831 protected function getGroupName() {
832 return 'media';
833 }
834
835 /**
836 * Should we rotate images in the preview on Special:Upload.
837 *
838 * This controls js: mw.config.get( 'wgFileCanRotate' )
839 *
840 * @todo What about non-BitmapHandler handled files?
841 */
842 public static function rotationEnabled() {
843 $bitmapHandler = new BitmapHandler();
844 return $bitmapHandler->autoRotateEnabled();
845 }
846 }
847
848 /**
849 * Sub class of HTMLForm that provides the form section of SpecialUpload
850 */
851 class UploadForm extends HTMLForm {
852 protected $mWatch;
853 protected $mForReUpload;
854 protected $mSessionKey;
855 protected $mHideIgnoreWarning;
856 protected $mDestWarningAck;
857 protected $mDestFile;
858
859 protected $mComment;
860 protected $mTextTop;
861 protected $mTextAfterSummary;
862
863 protected $mSourceIds;
864
865 protected $mMaxFileSize = [];
866
867 protected $mMaxUploadSize = [];
868
869 public function __construct( array $options = [], IContextSource $context = null,
870 LinkRenderer $linkRenderer = null
871 ) {
872 if ( $context instanceof IContextSource ) {
873 $this->setContext( $context );
874 }
875
876 if ( !$linkRenderer ) {
877 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
878 }
879
880 $this->mWatch = !empty( $options['watch'] );
881 $this->mForReUpload = !empty( $options['forreupload'] );
882 $this->mSessionKey = isset( $options['sessionkey'] ) ? $options['sessionkey'] : '';
883 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
884 $this->mDestWarningAck = !empty( $options['destwarningack'] );
885 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
886
887 $this->mComment = isset( $options['description'] ) ?
888 $options['description'] : '';
889
890 $this->mTextTop = isset( $options['texttop'] )
891 ? $options['texttop'] : '';
892
893 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
894 ? $options['textaftersummary'] : '';
895
896 $sourceDescriptor = $this->getSourceSection();
897 $descriptor = $sourceDescriptor
898 + $this->getDescriptionSection()
899 + $this->getOptionsSection();
900
901 Hooks::run( 'UploadFormInitDescriptor', [ &$descriptor ] );
902 parent::__construct( $descriptor, $context, 'upload' );
903
904 # Add a link to edit MediaWiki:Licenses
905 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
906 $this->getOutput()->addModuleStyles( 'mediawiki.special.upload.styles' );
907 $licensesLink = $linkRenderer->makeKnownLink(
908 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
909 $this->msg( 'licenses-edit' )->text(),
910 [],
911 [ 'action' => 'edit' ]
912 );
913 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
914 $this->addFooterText( $editLicenses, 'description' );
915 }
916
917 # Set some form properties
918 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
919 $this->setSubmitName( 'wpUpload' );
920 # Used message keys: 'accesskey-upload', 'tooltip-upload'
921 $this->setSubmitTooltip( 'upload' );
922 $this->setId( 'mw-upload-form' );
923
924 # Build a list of IDs for javascript insertion
925 $this->mSourceIds = [];
926 foreach ( $sourceDescriptor as $field ) {
927 if ( !empty( $field['id'] ) ) {
928 $this->mSourceIds[] = $field['id'];
929 }
930 }
931 }
932
933 /**
934 * Get the descriptor of the fieldset that contains the file source
935 * selection. The section is 'source'
936 *
937 * @return array Descriptor array
938 */
939 protected function getSourceSection() {
940 if ( $this->mSessionKey ) {
941 return [
942 'SessionKey' => [
943 'type' => 'hidden',
944 'default' => $this->mSessionKey,
945 ],
946 'SourceType' => [
947 'type' => 'hidden',
948 'default' => 'Stash',
949 ],
950 ];
951 }
952
953 $canUploadByUrl = UploadFromUrl::isEnabled()
954 && ( UploadFromUrl::isAllowed( $this->getUser() ) === true )
955 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
956 $radio = $canUploadByUrl;
957 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
958
959 $descriptor = [];
960 if ( $this->mTextTop ) {
961 $descriptor['UploadFormTextTop'] = [
962 'type' => 'info',
963 'section' => 'source',
964 'default' => $this->mTextTop,
965 'raw' => true,
966 ];
967 }
968
969 $this->mMaxUploadSize['file'] = min(
970 UploadBase::getMaxUploadSize( 'file' ),
971 UploadBase::getMaxPhpUploadSize()
972 );
973
974 $help = $this->msg( 'upload-maxfilesize',
975 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] )
976 )->parse();
977
978 // If the user can also upload by URL, there are 2 different file size limits.
979 // This extra message helps stress which limit corresponds to what.
980 if ( $canUploadByUrl ) {
981 $help .= $this->msg( 'word-separator' )->escaped();
982 $help .= $this->msg( 'upload_source_file' )->parse();
983 }
984
985 $descriptor['UploadFile'] = [
986 'class' => 'UploadSourceField',
987 'section' => 'source',
988 'type' => 'file',
989 'id' => 'wpUploadFile',
990 'radio-id' => 'wpSourceTypeFile',
991 'label-message' => 'sourcefilename',
992 'upload-type' => 'File',
993 'radio' => &$radio,
994 'help' => $help,
995 'checked' => $selectedSourceType == 'file',
996 ];
997
998 if ( $canUploadByUrl ) {
999 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
1000 $descriptor['UploadFileURL'] = [
1001 'class' => 'UploadSourceField',
1002 'section' => 'source',
1003 'id' => 'wpUploadFileURL',
1004 'radio-id' => 'wpSourceTypeurl',
1005 'label-message' => 'sourceurl',
1006 'upload-type' => 'url',
1007 'radio' => &$radio,
1008 'help' => $this->msg( 'upload-maxfilesize',
1009 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] )
1010 )->parse() .
1011 $this->msg( 'word-separator' )->escaped() .
1012 $this->msg( 'upload_source_url' )->parse(),
1013 'checked' => $selectedSourceType == 'url',
1014 ];
1015 }
1016 Hooks::run( 'UploadFormSourceDescriptors', [ &$descriptor, &$radio, $selectedSourceType ] );
1017
1018 $descriptor['Extensions'] = [
1019 'type' => 'info',
1020 'section' => 'source',
1021 'default' => $this->getExtensionsMessage(),
1022 'raw' => true,
1023 ];
1024
1025 return $descriptor;
1026 }
1027
1028 /**
1029 * Get the messages indicating which extensions are preferred and prohibitted.
1030 *
1031 * @return string HTML string containing the message
1032 */
1033 protected function getExtensionsMessage() {
1034 # Print a list of allowed file extensions, if so configured. We ignore
1035 # MIME type here, it's incomprehensible to most people and too long.
1036 $config = $this->getConfig();
1037
1038 if ( $config->get( 'CheckFileExtensions' ) ) {
1039 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
1040 if ( $config->get( 'StrictFileExtensions' ) ) {
1041 # Everything not permitted is banned
1042 $extensionsList =
1043 '<div id="mw-upload-permitted">' .
1044 $this->msg( 'upload-permitted' )
1045 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1046 ->numParams( count( $fileExtensions ) )
1047 ->parseAsBlock() .
1048 "</div>\n";
1049 } else {
1050 # We have to list both preferred and prohibited
1051 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
1052 $extensionsList =
1053 '<div id="mw-upload-preferred">' .
1054 $this->msg( 'upload-preferred' )
1055 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1056 ->numParams( count( $fileExtensions ) )
1057 ->parseAsBlock() .
1058 "</div>\n" .
1059 '<div id="mw-upload-prohibited">' .
1060 $this->msg( 'upload-prohibited' )
1061 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
1062 ->numParams( count( $fileBlacklist ) )
1063 ->parseAsBlock() .
1064 "</div>\n";
1065 }
1066 } else {
1067 # Everything is permitted.
1068 $extensionsList = '';
1069 }
1070
1071 return $extensionsList;
1072 }
1073
1074 /**
1075 * Get the descriptor of the fieldset that contains the file description
1076 * input. The section is 'description'
1077 *
1078 * @return array Descriptor array
1079 */
1080 protected function getDescriptionSection() {
1081 $config = $this->getConfig();
1082 if ( $this->mSessionKey ) {
1083 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1084 try {
1085 $file = $stash->getFile( $this->mSessionKey );
1086 } catch ( Exception $e ) {
1087 $file = null;
1088 }
1089 if ( $file ) {
1090 global $wgContLang;
1091
1092 $mto = $file->transform( [ 'width' => 120 ] );
1093 $this->addHeaderText(
1094 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1095 Html::element( 'img', [
1096 'src' => $mto->getUrl(),
1097 'class' => 'thumbimage',
1098 ] ) . '</div>', 'description' );
1099 }
1100 }
1101
1102 $descriptor = [
1103 'DestFile' => [
1104 'type' => 'text',
1105 'section' => 'description',
1106 'id' => 'wpDestFile',
1107 'label-message' => 'destfilename',
1108 'size' => 60,
1109 'default' => $this->mDestFile,
1110 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1111 'nodata' => strval( $this->mDestFile ) !== '',
1112 ],
1113 'UploadDescription' => [
1114 'type' => 'textarea',
1115 'section' => 'description',
1116 'id' => 'wpUploadDescription',
1117 'label-message' => $this->mForReUpload
1118 ? 'filereuploadsummary'
1119 : 'fileuploadsummary',
1120 'default' => $this->mComment,
1121 'cols' => 80,
1122 'rows' => 8,
1123 ]
1124 ];
1125 if ( $this->mTextAfterSummary ) {
1126 $descriptor['UploadFormTextAfterSummary'] = [
1127 'type' => 'info',
1128 'section' => 'description',
1129 'default' => $this->mTextAfterSummary,
1130 'raw' => true,
1131 ];
1132 }
1133
1134 $descriptor += [
1135 'EditTools' => [
1136 'type' => 'edittools',
1137 'section' => 'description',
1138 'message' => 'edittools-upload',
1139 ]
1140 ];
1141
1142 if ( $this->mForReUpload ) {
1143 $descriptor['DestFile']['readonly'] = true;
1144 } else {
1145 $descriptor['License'] = [
1146 'type' => 'select',
1147 'class' => 'Licenses',
1148 'section' => 'description',
1149 'id' => 'wpLicense',
1150 'label-message' => 'license',
1151 ];
1152 }
1153
1154 if ( $config->get( 'UseCopyrightUpload' ) ) {
1155 $descriptor['UploadCopyStatus'] = [
1156 'type' => 'text',
1157 'section' => 'description',
1158 'id' => 'wpUploadCopyStatus',
1159 'label-message' => 'filestatus',
1160 ];
1161 $descriptor['UploadSource'] = [
1162 'type' => 'text',
1163 'section' => 'description',
1164 'id' => 'wpUploadSource',
1165 'label-message' => 'filesource',
1166 ];
1167 }
1168
1169 return $descriptor;
1170 }
1171
1172 /**
1173 * Get the descriptor of the fieldset that contains the upload options,
1174 * such as "watch this file". The section is 'options'
1175 *
1176 * @return array Descriptor array
1177 */
1178 protected function getOptionsSection() {
1179 $user = $this->getUser();
1180 if ( $user->isLoggedIn() ) {
1181 $descriptor = [
1182 'Watchthis' => [
1183 'type' => 'check',
1184 'id' => 'wpWatchthis',
1185 'label-message' => 'watchthisupload',
1186 'section' => 'options',
1187 'default' => $this->mWatch,
1188 ]
1189 ];
1190 }
1191 if ( !$this->mHideIgnoreWarning ) {
1192 $descriptor['IgnoreWarning'] = [
1193 'type' => 'check',
1194 'id' => 'wpIgnoreWarning',
1195 'label-message' => 'ignorewarnings',
1196 'section' => 'options',
1197 ];
1198 }
1199
1200 $descriptor['DestFileWarningAck'] = [
1201 'type' => 'hidden',
1202 'id' => 'wpDestFileWarningAck',
1203 'default' => $this->mDestWarningAck ? '1' : '',
1204 ];
1205
1206 if ( $this->mForReUpload ) {
1207 $descriptor['ForReUpload'] = [
1208 'type' => 'hidden',
1209 'id' => 'wpForReUpload',
1210 'default' => '1',
1211 ];
1212 }
1213
1214 return $descriptor;
1215 }
1216
1217 /**
1218 * Add the upload JS and show the form.
1219 */
1220 public function show() {
1221 $this->addUploadJS();
1222 parent::show();
1223 }
1224
1225 /**
1226 * Add upload JS to the OutputPage
1227 */
1228 protected function addUploadJS() {
1229 $config = $this->getConfig();
1230
1231 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1232 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1233 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1234 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1235
1236 $scriptVars = [
1237 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1238 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1239 'wgUploadAutoFill' => !$this->mForReUpload &&
1240 // If we received mDestFile from the request, don't autofill
1241 // the wpDestFile textbox
1242 $this->mDestFile === '',
1243 'wgUploadSourceIds' => $this->mSourceIds,
1244 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1245 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1246 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1247 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1248 'wgMaxUploadSize' => $this->mMaxUploadSize,
1249 'wgFileCanRotate' => SpecialUpload::rotationEnabled(),
1250 ];
1251
1252 $out = $this->getOutput();
1253 $out->addJsConfigVars( $scriptVars );
1254
1255 $out->addModules( [
1256 'mediawiki.action.edit', // For <charinsert> support
1257 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1258 ] );
1259 }
1260
1261 /**
1262 * Empty function; submission is handled elsewhere.
1263 *
1264 * @return bool False
1265 */
1266 function trySubmit() {
1267 return false;
1268 }
1269 }
1270
1271 /**
1272 * A form field that contains a radio box in the label
1273 */
1274 class UploadSourceField extends HTMLTextField {
1275
1276 /**
1277 * @param array $cellAttributes
1278 * @return string
1279 */
1280 function getLabelHtml( $cellAttributes = [] ) {
1281 $id = $this->mParams['id'];
1282 $label = Html::rawElement( 'label', [ 'for' => $id ], $this->mLabel );
1283
1284 if ( !empty( $this->mParams['radio'] ) ) {
1285 if ( isset( $this->mParams['radio-id'] ) ) {
1286 $radioId = $this->mParams['radio-id'];
1287 } else {
1288 // Old way. For the benefit of extensions that do not define
1289 // the 'radio-id' key.
1290 $radioId = 'wpSourceType' . $this->mParams['upload-type'];
1291 }
1292
1293 $attribs = [
1294 'name' => 'wpSourceType',
1295 'type' => 'radio',
1296 'id' => $radioId,
1297 'value' => $this->mParams['upload-type'],
1298 ];
1299
1300 if ( !empty( $this->mParams['checked'] ) ) {
1301 $attribs['checked'] = 'checked';
1302 }
1303
1304 $label .= Html::element( 'input', $attribs );
1305 }
1306
1307 return Html::rawElement( 'td', [ 'class' => 'mw-label' ] + $cellAttributes, $label );
1308 }
1309
1310 /**
1311 * @return int
1312 */
1313 function getSize() {
1314 return isset( $this->mParams['size'] )
1315 ? $this->mParams['size']
1316 : 60;
1317 }
1318 }