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