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