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