Merge "maintenance: Script to rename titles for Unicode uppercasing changes"
[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\MediaWikiServices;
26
27 /**
28 * Form for handling uploads and special page.
29 *
30 * @ingroup SpecialPage
31 * @ingroup Upload
32 */
33 class SpecialUpload extends SpecialPage {
34 /**
35 * Get data POSTed through the form and assign them to the object
36 * @param WebRequest|null $request Data posted.
37 */
38 public function __construct( $request = null ) {
39 parent::__construct( 'Upload', 'upload' );
40 }
41
42 public function doesWrites() {
43 return true;
44 }
45
46 /** Misc variables **/
47
48 /** @var WebRequest|FauxRequest The request this form is supposed to handle */
49 public $mRequest;
50 public $mSourceType;
51
52 /** @var UploadBase */
53 public $mUpload;
54
55 /** @var LocalFile */
56 public $mLocalFile;
57 public $mUploadClicked;
58
59 /** User input variables from the "description" section **/
60
61 /** @var string The requested target file name */
62 public $mDesiredDestName;
63 public $mComment;
64 public $mLicense;
65
66 /** User input variables from the root section **/
67
68 public $mIgnoreWarning;
69 public $mWatchthis;
70 public $mCopyrightStatus;
71 public $mCopyrightSource;
72
73 /** Hidden variables **/
74
75 public $mDestWarningAck;
76
77 /** @var bool The user followed an "overwrite this file" link */
78 public $mForReUpload;
79
80 /** @var bool The user clicked "Cancel and return to upload form" button */
81 public $mCancelUpload;
82 public $mTokenOk;
83
84 /** @var bool Subclasses can use this to determine whether a file was uploaded */
85 public $mUploadSuccessful = false;
86
87 /** Text injection points for hooks not using HTMLForm **/
88 public $uploadFormTextTop;
89 public $uploadFormTextAfterSummary;
90
91 /**
92 * Initialize instance variables from request and create an Upload handler
93 */
94 protected function loadRequest() {
95 $this->mRequest = $request = $this->getRequest();
96 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
97 $this->mUpload = UploadBase::createFromRequest( $request );
98 $this->mUploadClicked = $request->wasPosted()
99 && ( $request->getCheck( 'wpUpload' )
100 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
101
102 // Guess the desired name from the filename if not provided
103 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
104 if ( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
105 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
106 }
107 $this->mLicense = $request->getText( 'wpLicense' );
108
109 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
110 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
111 || $request->getCheck( 'wpUploadIgnoreWarning' );
112 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
113 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
114 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
115
116 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
117
118 $commentDefault = '';
119 $commentMsg = $this->msg( 'upload-default-description' )->inContentLanguage();
120 if ( !$this->mForReUpload && !$commentMsg->isDisabled() ) {
121 $commentDefault = $commentMsg->plain();
122 }
123 $this->mComment = $request->getText( 'wpUploadDescription', $commentDefault );
124
125 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
126 || $request->getCheck( 'wpReUpload' ); // b/w compat
127
128 // If it was posted check for the token (no remote POST'ing with user credentials)
129 $token = $request->getVal( 'wpEditToken' );
130 $this->mTokenOk = $this->getUser()->matchEditToken( $token );
131
132 $this->uploadFormTextTop = '';
133 $this->uploadFormTextAfterSummary = '';
134 }
135
136 /**
137 * This page can be shown if uploading is enabled.
138 * Handle permission checking elsewhere in order to be able to show
139 * custom error messages.
140 *
141 * @param User $user
142 * @return bool
143 */
144 public function userCanExecute( User $user ) {
145 return UploadBase::isEnabled() && parent::userCanExecute( $user );
146 }
147
148 /**
149 * @param string|null $par
150 * @throws ErrorPageError
151 * @throws Exception
152 * @throws FatalError
153 * @throws MWException
154 * @throws PermissionsError
155 * @throws ReadOnlyError
156 * @throws UserBlockedError
157 */
158 public function execute( $par ) {
159 $this->useTransactionalTimeLimit();
160
161 $this->setHeaders();
162 $this->outputHeader();
163
164 # Check uploading enabled
165 if ( !UploadBase::isEnabled() ) {
166 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
167 }
168
169 $this->addHelpLink( 'Help:Managing files' );
170
171 # Check permissions
172 $user = $this->getUser();
173 $permissionRequired = UploadBase::isAllowed( $user );
174 if ( $permissionRequired !== true ) {
175 throw new PermissionsError( $permissionRequired );
176 }
177
178 # Check blocks
179 if ( $user->isBlockedFromUpload() ) {
180 throw new UserBlockedError( $user->getBlock() );
181 }
182
183 // Global blocks
184 if ( $user->isBlockedGlobally() ) {
185 throw new UserBlockedError( $user->getGlobalBlock() );
186 }
187
188 # Check whether we actually want to allow changing stuff
189 $this->checkReadOnly();
190
191 $this->loadRequest();
192
193 # Unsave the temporary file in case this was a cancelled upload
194 if ( $this->mCancelUpload && !$this->unsaveUploadedFile() ) {
195 # Something went wrong, so unsaveUploadedFile showed a warning
196 return;
197 }
198
199 # Process upload or show a form
200 if (
201 $this->mTokenOk && !$this->mCancelUpload &&
202 ( $this->mUpload && $this->mUploadClicked )
203 ) {
204 $this->processUpload();
205 } else {
206 # Backwards compatibility hook
207 // Avoid PHP 7.1 warning of passing $this by reference
208 $upload = $this;
209 if ( !Hooks::run( 'UploadForm:initial', [ &$upload ] ) ) {
210 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
211
212 return;
213 }
214 $this->showUploadForm( $this->getUploadForm() );
215 }
216
217 # Cleanup
218 if ( $this->mUpload ) {
219 $this->mUpload->cleanupTempFile();
220 }
221 }
222
223 /**
224 * Show the main upload form
225 *
226 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
227 */
228 protected function showUploadForm( $form ) {
229 # Add links if file was previously deleted
230 if ( $this->mDesiredDestName ) {
231 $this->showViewDeletedLinks();
232 }
233
234 if ( $form instanceof HTMLForm ) {
235 $form->show();
236 } else {
237 $this->getOutput()->addHTML( $form );
238 }
239 }
240
241 /**
242 * Get an UploadForm instance with title and text properly set.
243 *
244 * @param string $message HTML string to add to the form
245 * @param string $sessionKey Session key in case this is a stashed upload
246 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
247 * @return UploadForm
248 */
249 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
250 # Initialize form
251 $context = new DerivativeContext( $this->getContext() );
252 $context->setTitle( $this->getPageTitle() ); // Remove subpage
253 $form = new UploadForm( [
254 'watch' => $this->getWatchCheck(),
255 'forreupload' => $this->mForReUpload,
256 'sessionkey' => $sessionKey,
257 'hideignorewarning' => $hideIgnoreWarning,
258 'destwarningack' => (bool)$this->mDestWarningAck,
259
260 'description' => $this->mComment,
261 'texttop' => $this->uploadFormTextTop,
262 'textaftersummary' => $this->uploadFormTextAfterSummary,
263 'destfile' => $this->mDesiredDestName,
264 ], $context, $this->getLinkRenderer() );
265
266 # Check the token, but only if necessary
267 if (
268 !$this->mTokenOk && !$this->mCancelUpload &&
269 ( $this->mUpload && $this->mUploadClicked )
270 ) {
271 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
272 }
273
274 # Give a notice if the user is uploading a file that has been deleted or moved
275 # Note that this is independent from the message 'filewasdeleted'
276 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
277 $delNotice = ''; // empty by default
278 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
279 $dbr = wfGetDB( DB_REPLICA );
280
281 LogEventsList::showLogExtract( $delNotice, [ 'delete', 'move' ],
282 $desiredTitleObj,
283 '', [ 'lim' => 10,
284 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
285 'showIfEmpty' => false,
286 'msgKey' => [ 'upload-recreate-warning' ] ]
287 );
288 }
289 $form->addPreText( $delNotice );
290
291 # Add text to form
292 $form->addPreText( '<div id="uploadtext">' .
293 $this->msg( 'uploadtext', [ $this->mDesiredDestName ] )->parseAsBlock() .
294 '</div>' );
295 # Add upload error message
296 $form->addPreText( $message );
297
298 # Add footer to form
299 $uploadFooter = $this->msg( 'uploadfooter' );
300 if ( !$uploadFooter->isDisabled() ) {
301 $form->addPostText( '<div id="mw-upload-footer-message">'
302 . $uploadFooter->parseAsBlock() . "</div>\n" );
303 }
304
305 return $form;
306 }
307
308 /**
309 * Shows the "view X deleted revivions link""
310 */
311 protected function showViewDeletedLinks() {
312 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
313 $user = $this->getUser();
314 // Show a subtitle link to deleted revisions (to sysops et al only)
315 if ( $title instanceof Title ) {
316 $count = $title->isDeleted();
317 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
318 $restorelink = $this->getLinkRenderer()->makeKnownLink(
319 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
320 $this->msg( 'restorelink' )->numParams( $count )->text()
321 );
322 $link = $this->msg( $user->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted' )
323 ->rawParams( $restorelink )->parseAsBlock();
324 $this->getOutput()->addHTML(
325 Html::rawElement(
326 'div',
327 [ 'id' => 'contentSub2' ],
328 $link
329 )
330 );
331 }
332 }
333 }
334
335 /**
336 * Stashes the upload and shows the main upload form.
337 *
338 * Note: only errors that can be handled by changing the name or
339 * description should be redirected here. It should be assumed that the
340 * file itself is sane and has passed UploadBase::verifyFile. This
341 * essentially means that UploadBase::VERIFICATION_ERROR and
342 * UploadBase::EMPTY_FILE should not be passed here.
343 *
344 * @param string $message HTML message to be passed to mainUploadForm
345 */
346 protected function showRecoverableUploadError( $message ) {
347 $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
348 if ( $stashStatus->isGood() ) {
349 $sessionKey = $stashStatus->getValue()->getFileKey();
350 $uploadWarning = 'upload-tryagain';
351 } else {
352 $sessionKey = null;
353 $uploadWarning = 'upload-tryagain-nostash';
354 }
355 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
356 '<div class="error">' . $message . "</div>\n";
357
358 $form = $this->getUploadForm( $message, $sessionKey );
359 $form->setSubmitText( $this->msg( $uploadWarning )->escaped() );
360 $this->showUploadForm( $form );
361 }
362
363 /**
364 * Stashes the upload, shows the main form, but adds a "continue anyway button".
365 * Also checks whether there are actually warnings to display.
366 *
367 * @param array $warnings
368 * @return bool True if warnings were displayed, false if there are no
369 * warnings and it should continue processing
370 */
371 protected function showUploadWarning( $warnings ) {
372 # If there are no warnings, or warnings we can ignore, return early.
373 # mDestWarningAck is set when some javascript has shown the warning
374 # to the user. mForReUpload is set when the user clicks the "upload a
375 # new version" link.
376 if ( !$warnings || ( count( $warnings ) == 1
377 && isset( $warnings['exists'] )
378 && ( $this->mDestWarningAck || $this->mForReUpload ) )
379 ) {
380 return false;
381 }
382
383 $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
384 if ( $stashStatus->isGood() ) {
385 $sessionKey = $stashStatus->getValue()->getFileKey();
386 $uploadWarning = 'uploadwarning-text';
387 } else {
388 $sessionKey = null;
389 $uploadWarning = 'uploadwarning-text-nostash';
390 }
391
392 // Add styles for the warning, reused from the live preview
393 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
394
395 $linkRenderer = $this->getLinkRenderer();
396 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
397 . '<div class="mw-destfile-warning"><ul>';
398 foreach ( $warnings as $warning => $args ) {
399 if ( $warning == 'badfilename' ) {
400 $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
401 }
402 if ( $warning == 'exists' ) {
403 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
404 } elseif ( $warning == 'no-change' ) {
405 $file = $args;
406 $filename = $file->getTitle()->getPrefixedText();
407 $msg = "\t<li>" . $this->msg( 'fileexists-no-change', $filename )->parse() . "</li>\n";
408 } elseif ( $warning == 'duplicate-version' ) {
409 $file = $args[0];
410 $count = count( $args );
411 $filename = $file->getTitle()->getPrefixedText();
412 $message = $this->msg( 'fileexists-duplicate-version' )
413 ->params( $filename )
414 ->numParams( $count );
415 $msg = "\t<li>" . $message->parse() . "</li>\n";
416 } elseif ( $warning == 'was-deleted' ) {
417 # If the file existed before and was deleted, warn the user of this
418 $ltitle = SpecialPage::getTitleFor( 'Log' );
419 $llink = $linkRenderer->makeKnownLink(
420 $ltitle,
421 $this->msg( 'deletionlog' )->text(),
422 [],
423 [
424 'type' => 'delete',
425 'page' => Title::makeTitle( NS_FILE, $args )->getPrefixedText(),
426 ]
427 );
428 $msg = "\t<li>" . $this->msg( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
429 } elseif ( $warning == 'duplicate' ) {
430 $msg = $this->getDupeWarning( $args );
431 } elseif ( $warning == 'duplicate-archive' ) {
432 if ( $args === '' ) {
433 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
434 . "</li>\n";
435 } else {
436 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
437 Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
438 . "</li>\n";
439 }
440 } else {
441 if ( $args === true ) {
442 $args = [];
443 } elseif ( !is_array( $args ) ) {
444 $args = [ $args ];
445 }
446 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
447 }
448 $warningHtml .= $msg;
449 }
450 $warningHtml .= "</ul></div>\n";
451 $warningHtml .= $this->msg( $uploadWarning )->parseAsBlock();
452
453 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
454 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
455 $form->addButton( [
456 'name' => 'wpUploadIgnoreWarning',
457 'value' => $this->msg( 'ignorewarning' )->text()
458 ] );
459 $form->addButton( [
460 'name' => 'wpCancelUpload',
461 'value' => $this->msg( 'reuploaddesc' )->text()
462 ] );
463
464 $this->showUploadForm( $form );
465
466 # Indicate that we showed a form
467 return true;
468 }
469
470 /**
471 * Show the upload form with error message, but do not stash the file.
472 *
473 * @param string $message HTML string
474 */
475 protected function showUploadError( $message ) {
476 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
477 '<div class="error">' . $message . "</div>\n";
478 $this->showUploadForm( $this->getUploadForm( $message ) );
479 }
480
481 /**
482 * Do the upload.
483 * Checks are made in SpecialUpload::execute()
484 */
485 protected function processUpload() {
486 // Fetch the file if required
487 $status = $this->mUpload->fetchFile();
488 if ( !$status->isOK() ) {
489 $this->showUploadError( $this->getOutput()->parseAsInterface( $status->getWikiText() ) );
490
491 return;
492 }
493 // Avoid PHP 7.1 warning of passing $this by reference
494 $upload = $this;
495 if ( !Hooks::run( 'UploadForm:BeforeProcessing', [ &$upload ] ) ) {
496 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
497 // This code path is deprecated. If you want to break upload processing
498 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
499 // and UploadBase::verifyFile.
500 // If you use this hook to break uploading, the user will be returned
501 // an empty form with no error message whatsoever.
502 return;
503 }
504
505 // Upload verification
506 $details = $this->mUpload->verifyUpload();
507 if ( $details['status'] != UploadBase::OK ) {
508 $this->processVerificationError( $details );
509
510 return;
511 }
512
513 // Verify permissions for this title
514 $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
515 if ( $permErrors !== true ) {
516 $code = array_shift( $permErrors[0] );
517 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
518
519 return;
520 }
521
522 $this->mLocalFile = $this->mUpload->getLocalFile();
523
524 // Check warnings if necessary
525 if ( !$this->mIgnoreWarning ) {
526 $warnings = $this->mUpload->checkWarnings();
527 if ( $this->showUploadWarning( $warnings ) ) {
528 return;
529 }
530 }
531
532 // This is as late as we can throttle, after expected issues have been handled
533 if ( UploadBase::isThrottled( $this->getUser() ) ) {
534 $this->showRecoverableUploadError(
535 $this->msg( 'actionthrottledtext' )->escaped()
536 );
537 return;
538 }
539
540 // Get the page text if this is not a reupload
541 if ( !$this->mForReUpload ) {
542 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
543 $this->mCopyrightStatus, $this->mCopyrightSource, $this->getConfig() );
544 } else {
545 $pageText = false;
546 }
547
548 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
549 if ( is_null( $changeTags ) || $changeTags === '' ) {
550 $changeTags = [];
551 } else {
552 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
553 }
554
555 if ( $changeTags ) {
556 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
557 $changeTags, $this->getUser() );
558 if ( !$changeTagsStatus->isOK() ) {
559 $this->showUploadError( $this->getOutput()->parseAsInterface(
560 $changeTagsStatus->getWikiText()
561 ) );
562
563 return;
564 }
565 }
566
567 $status = $this->mUpload->performUpload(
568 $this->mComment,
569 $pageText,
570 $this->mWatchthis,
571 $this->getUser(),
572 $changeTags
573 );
574
575 if ( !$status->isGood() ) {
576 $this->showRecoverableUploadError(
577 $this->getOutput()->parseAsInterface( $status->getWikiText() )
578 );
579
580 return;
581 }
582
583 // Success, redirect to description page
584 $this->mUploadSuccessful = true;
585 // Avoid PHP 7.1 warning of passing $this by reference
586 $upload = $this;
587 Hooks::run( 'SpecialUploadComplete', [ &$upload ] );
588 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
589 }
590
591 /**
592 * Get the initial image page text based on a comment and optional file status information
593 * @param string $comment
594 * @param string $license
595 * @param string $copyStatus
596 * @param string $source
597 * @param Config|null $config Configuration object to load data from
598 * @return string
599 */
600 public static function getInitialPageText( $comment = '', $license = '',
601 $copyStatus = '', $source = '', Config $config = null
602 ) {
603 if ( $config === null ) {
604 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
605 $config = MediaWikiServices::getInstance()->getMainConfig();
606 }
607
608 $msg = [];
609 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
610 /* These messages are transcluded into the actual text of the description page.
611 * Thus, forcing them as content messages makes the upload to produce an int: template
612 * instead of hardcoding it there in the uploader language.
613 */
614 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
615 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
616 $msg[$msgName] = "{{int:$msgName}}";
617 } else {
618 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
619 }
620 }
621
622 $licenseText = '';
623 if ( $license !== '' ) {
624 $licenseText = '== ' . $msg['license-header'] . " ==\n{{" . $license . "}}\n";
625 }
626
627 $pageText = $comment . "\n";
628 $headerText = '== ' . $msg['filedesc'] . ' ==';
629 if ( $comment !== '' && strpos( $comment, $headerText ) === false ) {
630 // prepend header to page text unless it's already there (or there is no content)
631 $pageText = $headerText . "\n" . $pageText;
632 }
633
634 if ( $config->get( 'UseCopyrightUpload' ) ) {
635 $pageText .= '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n";
636 $pageText .= $licenseText;
637 $pageText .= '== ' . $msg['filesource'] . " ==\n" . $source;
638 } else {
639 $pageText .= $licenseText;
640 }
641
642 // allow extensions to modify the content
643 Hooks::run( 'UploadForm:getInitialPageText', [ &$pageText, $msg, $config ] );
644
645 return $pageText;
646 }
647
648 /**
649 * See if we should check the 'watch this page' checkbox on the form
650 * based on the user's preferences and whether we're being asked
651 * to create a new file or update an existing one.
652 *
653 * In the case where 'watch edits' is off but 'watch creations' is on,
654 * we'll leave the box unchecked.
655 *
656 * Note that the page target can be changed *on the form*, so our check
657 * state can get out of sync.
658 * @return bool|string
659 */
660 protected function getWatchCheck() {
661 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
662 // Watch all edits!
663 return true;
664 }
665
666 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
667 if ( $desiredTitleObj instanceof Title && $this->getUser()->isWatched( $desiredTitleObj ) ) {
668 // Already watched, don't change that
669 return true;
670 }
671
672 $local = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()
673 ->newFile( $this->mDesiredDestName );
674 if ( $local && $local->exists() ) {
675 // We're uploading a new version of an existing file.
676 // No creation, so don't watch it if we're not already.
677 return false;
678 } else {
679 // New page should get watched if that's our option.
680 return $this->getUser()->getOption( 'watchcreations' ) ||
681 $this->getUser()->getOption( 'watchuploads' );
682 }
683 }
684
685 /**
686 * Provides output to the user for a result of UploadBase::verifyUpload
687 *
688 * @param array $details Result of UploadBase::verifyUpload
689 * @throws MWException
690 */
691 protected function processVerificationError( $details ) {
692 switch ( $details['status'] ) {
693 /** Statuses that only require name changing **/
694 case UploadBase::MIN_LENGTH_PARTNAME:
695 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
696 break;
697 case UploadBase::ILLEGAL_FILENAME:
698 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
699 $details['filtered'] )->parse() );
700 break;
701 case UploadBase::FILENAME_TOO_LONG:
702 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
703 break;
704 case UploadBase::FILETYPE_MISSING:
705 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
706 break;
707 case UploadBase::WINDOWS_NONASCII_FILENAME:
708 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
709 break;
710
711 /** Statuses that require reuploading **/
712 case UploadBase::EMPTY_FILE:
713 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
714 break;
715 case UploadBase::FILE_TOO_LARGE:
716 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
717 break;
718 case UploadBase::FILETYPE_BADTYPE:
719 $msg = $this->msg( 'filetype-banned-type' );
720 if ( isset( $details['blacklistedExt'] ) ) {
721 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
722 } else {
723 $msg->params( $details['finalExt'] );
724 }
725 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
726 $msg->params( $this->getLanguage()->commaList( $extensions ),
727 count( $extensions ) );
728
729 // Add PLURAL support for the first parameter. This results
730 // in a bit unlogical parameter sequence, but does not break
731 // old translations
732 if ( isset( $details['blacklistedExt'] ) ) {
733 $msg->params( count( $details['blacklistedExt'] ) );
734 } else {
735 $msg->params( 1 );
736 }
737
738 $this->showUploadError( $msg->parse() );
739 break;
740 case UploadBase::VERIFICATION_ERROR:
741 unset( $details['status'] );
742 $code = array_shift( $details['details'] );
743 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
744 break;
745 case UploadBase::HOOK_ABORTED:
746 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
747 $args = $details['error'];
748 $error = array_shift( $args );
749 } else {
750 $error = $details['error'];
751 $args = null;
752 }
753
754 $this->showUploadError( $this->msg( $error, $args )->parse() );
755 break;
756 default:
757 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
758 }
759 }
760
761 /**
762 * Remove a temporarily kept file stashed by saveTempUploadedFile().
763 *
764 * @return bool Success
765 */
766 protected function unsaveUploadedFile() {
767 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
768 return true;
769 }
770 $success = $this->mUpload->unsaveUploadedFile();
771 if ( !$success ) {
772 $this->getOutput()->showFatalError(
773 $this->msg( 'filedeleteerror' )
774 ->params( $this->mUpload->getTempPath() )
775 ->escaped()
776 );
777
778 return false;
779 } else {
780 return true;
781 }
782 }
783
784 /*** Functions for formatting warnings ***/
785
786 /**
787 * Formats a result of UploadBase::getExistsWarning as HTML
788 * This check is static and can be done pre-upload via AJAX
789 *
790 * @param array $exists The result of UploadBase::getExistsWarning
791 * @return string Empty string if there is no warning or an HTML fragment
792 */
793 public static function getExistsWarning( $exists ) {
794 if ( !$exists ) {
795 return '';
796 }
797
798 $file = $exists['file'];
799 $filename = $file->getTitle()->getPrefixedText();
800 $warnMsg = null;
801
802 if ( $exists['warning'] == 'exists' ) {
803 // Exact match
804 $warnMsg = wfMessage( 'fileexists', $filename );
805 } elseif ( $exists['warning'] == 'page-exists' ) {
806 // Page exists but file does not
807 $warnMsg = wfMessage( 'filepageexists', $filename );
808 } elseif ( $exists['warning'] == 'exists-normalized' ) {
809 $warnMsg = wfMessage( 'fileexists-extension', $filename,
810 $exists['normalizedFile']->getTitle()->getPrefixedText() );
811 } elseif ( $exists['warning'] == 'thumb' ) {
812 // Swapped argument order compared with other messages for backwards compatibility
813 $warnMsg = wfMessage( 'fileexists-thumbnail-yes',
814 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
815 } elseif ( $exists['warning'] == 'thumb-name' ) {
816 // Image w/o '180px-' does not exists, but we do not like these filenames
817 $name = $file->getName();
818 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
819 $warnMsg = wfMessage( 'file-thumbnail-no', $badPart );
820 } elseif ( $exists['warning'] == 'bad-prefix' ) {
821 $warnMsg = wfMessage( 'filename-bad-prefix', $exists['prefix'] );
822 }
823
824 return $warnMsg ? $warnMsg->title( $file->getTitle() )->parse() : '';
825 }
826
827 /**
828 * Construct a warning and a gallery from an array of duplicate files.
829 * @param array $dupes
830 * @return string
831 */
832 public function getDupeWarning( $dupes ) {
833 if ( !$dupes ) {
834 return '';
835 }
836
837 $gallery = ImageGalleryBase::factory( false, $this->getContext() );
838 $gallery->setShowBytes( false );
839 $gallery->setShowDimensions( false );
840 foreach ( $dupes as $file ) {
841 $gallery->add( $file->getTitle() );
842 }
843
844 return '<li>' .
845 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
846 $gallery->toHTML() . "</li>\n";
847 }
848
849 protected function getGroupName() {
850 return 'media';
851 }
852
853 /**
854 * Should we rotate images in the preview on Special:Upload.
855 *
856 * This controls js: mw.config.get( 'wgFileCanRotate' )
857 *
858 * @todo What about non-BitmapHandler handled files?
859 * @return bool
860 */
861 public static function rotationEnabled() {
862 $bitmapHandler = new BitmapHandler();
863 return $bitmapHandler->autoRotateEnabled();
864 }
865 }