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