Convert all array() syntax to []
[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 /**
26 * Form for handling uploads and special page.
27 *
28 * @ingroup SpecialPage
29 * @ingroup Upload
30 */
31 class SpecialUpload extends SpecialPage {
32 /**
33 * Constructor : initialise object
34 * Get data POSTed through the form and assign them to the object
35 * @param WebRequest $request Data posted.
36 */
37 public function __construct( $request = null ) {
38 parent::__construct( 'Upload', 'upload' );
39 }
40
41 public function doesWrites() {
42 return true;
43 }
44
45 /** Misc variables **/
46
47 /** @var WebRequest|FauxRequest The request this form is supposed to handle */
48 public $mRequest;
49 public $mSourceType;
50
51 /** @var UploadBase */
52 public $mUpload;
53
54 /** @var LocalFile */
55 public $mLocalFile;
56 public $mUploadClicked;
57
58 /** User input variables from the "description" section **/
59
60 /** @var string The requested target file name */
61 public $mDesiredDestName;
62 public $mComment;
63 public $mLicense;
64
65 /** User input variables from the root section **/
66
67 public $mIgnoreWarning;
68 public $mWatchthis;
69 public $mCopyrightStatus;
70 public $mCopyrightSource;
71
72 /** Hidden variables **/
73
74 public $mDestWarningAck;
75
76 /** @var bool The user followed an "overwrite this file" link */
77 public $mForReUpload;
78
79 /** @var bool The user clicked "Cancel and return to upload form" button */
80 public $mCancelUpload;
81 public $mTokenOk;
82
83 /** @var bool Subclasses can use this to determine whether a file was uploaded */
84 public $mUploadSuccessful = false;
85
86 /** Text injection points for hooks not using HTMLForm **/
87 public $uploadFormTextTop;
88 public $uploadFormTextAfterSummary;
89
90 /**
91 * Initialize instance variables from request and create an Upload handler
92 */
93 protected function loadRequest() {
94 $this->mRequest = $request = $this->getRequest();
95 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
96 $this->mUpload = UploadBase::createFromRequest( $request );
97 $this->mUploadClicked = $request->wasPosted()
98 && ( $request->getCheck( 'wpUpload' )
99 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
100
101 // Guess the desired name from the filename if not provided
102 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
103 if ( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
104 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
105 }
106 $this->mLicense = $request->getText( 'wpLicense' );
107
108 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
109 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
110 || $request->getCheck( 'wpUploadIgnoreWarning' );
111 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
112 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
113 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
114
115 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
116
117 $commentDefault = '';
118 $commentMsg = wfMessage( 'upload-default-description' )->inContentLanguage();
119 if ( !$this->mForReUpload && !$commentMsg->isDisabled() ) {
120 $commentDefault = $commentMsg->plain();
121 }
122 $this->mComment = $request->getText( 'wpUploadDescription', $commentDefault );
123
124 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
125 || $request->getCheck( 'wpReUpload' ); // b/w compat
126
127 // If it was posted check for the token (no remote POST'ing with user credentials)
128 $token = $request->getVal( 'wpEditToken' );
129 $this->mTokenOk = $this->getUser()->matchEditToken( $token );
130
131 $this->uploadFormTextTop = '';
132 $this->uploadFormTextAfterSummary = '';
133 }
134
135 /**
136 * This page can be shown if uploading is enabled.
137 * Handle permission checking elsewhere in order to be able to show
138 * custom error messages.
139 *
140 * @param User $user
141 * @return bool
142 */
143 public function userCanExecute( User $user ) {
144 return UploadBase::isEnabled() && parent::userCanExecute( $user );
145 }
146
147 /**
148 * Special page entry point
149 * @param string $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->isBlocked() ) {
180 throw new UserBlockedError( $user->getBlock() );
181 }
182
183 # Check whether we actually want to allow changing stuff
184 $this->checkReadOnly();
185
186 $this->loadRequest();
187
188 # Unsave the temporary file in case this was a cancelled upload
189 if ( $this->mCancelUpload ) {
190 if ( !$this->unsaveUploadedFile() ) {
191 # Something went wrong, so unsaveUploadedFile showed a warning
192 return;
193 }
194 }
195
196 # Process upload or show a form
197 if (
198 $this->mTokenOk && !$this->mCancelUpload &&
199 ( $this->mUpload && $this->mUploadClicked )
200 ) {
201 $this->processUpload();
202 } else {
203 # Backwards compatibility hook
204 if ( !Hooks::run( 'UploadForm:initial', [ &$this ] ) ) {
205 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
206
207 return;
208 }
209 $this->showUploadForm( $this->getUploadForm() );
210 }
211
212 # Cleanup
213 if ( $this->mUpload ) {
214 $this->mUpload->cleanupTempFile();
215 }
216 }
217
218 /**
219 * Show the main upload form
220 *
221 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
222 */
223 protected function showUploadForm( $form ) {
224 # Add links if file was previously deleted
225 if ( $this->mDesiredDestName ) {
226 $this->showViewDeletedLinks();
227 }
228
229 if ( $form instanceof HTMLForm ) {
230 $form->show();
231 } else {
232 $this->getOutput()->addHTML( $form );
233 }
234 }
235
236 /**
237 * Get an UploadForm instance with title and text properly set.
238 *
239 * @param string $message HTML string to add to the form
240 * @param string $sessionKey Session key in case this is a stashed upload
241 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
242 * @return UploadForm
243 */
244 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
245 # Initialize form
246 $context = new DerivativeContext( $this->getContext() );
247 $context->setTitle( $this->getPageTitle() ); // Remove subpage
248 $form = new UploadForm( [
249 'watch' => $this->getWatchCheck(),
250 'forreupload' => $this->mForReUpload,
251 'sessionkey' => $sessionKey,
252 'hideignorewarning' => $hideIgnoreWarning,
253 'destwarningack' => (bool)$this->mDestWarningAck,
254
255 'description' => $this->mComment,
256 'texttop' => $this->uploadFormTextTop,
257 'textaftersummary' => $this->uploadFormTextAfterSummary,
258 'destfile' => $this->mDesiredDestName,
259 ], $context );
260
261 # Check the token, but only if necessary
262 if (
263 !$this->mTokenOk && !$this->mCancelUpload &&
264 ( $this->mUpload && $this->mUploadClicked )
265 ) {
266 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
267 }
268
269 # Give a notice if the user is uploading a file that has been deleted or moved
270 # Note that this is independent from the message 'filewasdeleted'
271 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
272 $delNotice = ''; // empty by default
273 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
274 LogEventsList::showLogExtract( $delNotice, [ 'delete', 'move' ],
275 $desiredTitleObj,
276 '', [ 'lim' => 10,
277 'conds' => [ "log_action != 'revision'" ],
278 'showIfEmpty' => false,
279 'msgKey' => [ 'upload-recreate-warning' ] ]
280 );
281 }
282 $form->addPreText( $delNotice );
283
284 # Add text to form
285 $form->addPreText( '<div id="uploadtext">' .
286 $this->msg( 'uploadtext', [ $this->mDesiredDestName ] )->parseAsBlock() .
287 '</div>' );
288 # Add upload error message
289 $form->addPreText( $message );
290
291 # Add footer to form
292 $uploadFooter = $this->msg( 'uploadfooter' );
293 if ( !$uploadFooter->isDisabled() ) {
294 $form->addPostText( '<div id="mw-upload-footer-message">'
295 . $uploadFooter->parseAsBlock() . "</div>\n" );
296 }
297
298 return $form;
299 }
300
301 /**
302 * Shows the "view X deleted revivions link""
303 */
304 protected function showViewDeletedLinks() {
305 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
306 $user = $this->getUser();
307 // Show a subtitle link to deleted revisions (to sysops et al only)
308 if ( $title instanceof Title ) {
309 $count = $title->isDeleted();
310 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
311 $restorelink = Linker::linkKnown(
312 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
313 $this->msg( 'restorelink' )->numParams( $count )->escaped()
314 );
315 $link = $this->msg( $user->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted' )
316 ->rawParams( $restorelink )->parseAsBlock();
317 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
318 }
319 }
320 }
321
322 /**
323 * Stashes the upload and shows the main upload form.
324 *
325 * Note: only errors that can be handled by changing the name or
326 * description should be redirected here. It should be assumed that the
327 * file itself is sane and has passed UploadBase::verifyFile. This
328 * essentially means that UploadBase::VERIFICATION_ERROR and
329 * UploadBase::EMPTY_FILE should not be passed here.
330 *
331 * @param string $message HTML message to be passed to mainUploadForm
332 */
333 protected function showRecoverableUploadError( $message ) {
334 $sessionKey = $this->mUpload->stashSession();
335 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
336 '<div class="error">' . $message . "</div>\n";
337
338 $form = $this->getUploadForm( $message, $sessionKey );
339 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
340 $this->showUploadForm( $form );
341 }
342
343 /**
344 * Stashes the upload, shows the main form, but adds a "continue anyway button".
345 * Also checks whether there are actually warnings to display.
346 *
347 * @param array $warnings
348 * @return bool True if warnings were displayed, false if there are no
349 * warnings and it should continue processing
350 */
351 protected function showUploadWarning( $warnings ) {
352 # If there are no warnings, or warnings we can ignore, return early.
353 # mDestWarningAck is set when some javascript has shown the warning
354 # to the user. mForReUpload is set when the user clicks the "upload a
355 # new version" link.
356 if ( !$warnings || ( count( $warnings ) == 1
357 && isset( $warnings['exists'] )
358 && ( $this->mDestWarningAck || $this->mForReUpload ) )
359 ) {
360 return false;
361 }
362
363 $sessionKey = $this->mUpload->stashSession();
364
365 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
366 . '<div class="warningbox"><ul>';
367 foreach ( $warnings as $warning => $args ) {
368 if ( $warning == 'badfilename' ) {
369 $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
370 }
371 if ( $warning == 'exists' ) {
372 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
373 } elseif ( $warning == 'was-deleted' ) {
374 # If the file existed before and was deleted, warn the user of this
375 $ltitle = SpecialPage::getTitleFor( 'Log' );
376 $llink = Linker::linkKnown(
377 $ltitle,
378 wfMessage( 'deletionlog' )->escaped(),
379 [],
380 [
381 'type' => 'delete',
382 'page' => Title::makeTitle( NS_FILE, $args )->getPrefixedText(),
383 ]
384 );
385 $msg = "\t<li>" . wfMessage( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
386 } elseif ( $warning == 'duplicate' ) {
387 $msg = $this->getDupeWarning( $args );
388 } elseif ( $warning == 'duplicate-archive' ) {
389 if ( $args === '' ) {
390 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
391 . "</li>\n";
392 } else {
393 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
394 Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
395 . "</li>\n";
396 }
397 } else {
398 if ( $args === true ) {
399 $args = [];
400 } elseif ( !is_array( $args ) ) {
401 $args = [ $args ];
402 }
403 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
404 }
405 $warningHtml .= $msg;
406 }
407 $warningHtml .= "</ul></div>\n";
408 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
409
410 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
411 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
412 $form->addButton( [
413 'name' => 'wpUploadIgnoreWarning',
414 'value' => $this->msg( 'ignorewarning' )->text()
415 ] );
416 $form->addButton( [
417 'name' => 'wpCancelUpload',
418 'value' => $this->msg( 'reuploaddesc' )->text()
419 ] );
420
421 $this->showUploadForm( $form );
422
423 # Indicate that we showed a form
424 return true;
425 }
426
427 /**
428 * Show the upload form with error message, but do not stash the file.
429 *
430 * @param string $message HTML string
431 */
432 protected function showUploadError( $message ) {
433 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
434 '<div class="error">' . $message . "</div>\n";
435 $this->showUploadForm( $this->getUploadForm( $message ) );
436 }
437
438 /**
439 * Do the upload.
440 * Checks are made in SpecialUpload::execute()
441 */
442 protected function processUpload() {
443 // Fetch the file if required
444 $status = $this->mUpload->fetchFile();
445 if ( !$status->isOK() ) {
446 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
447
448 return;
449 }
450
451 if ( !Hooks::run( 'UploadForm:BeforeProcessing', [ &$this ] ) ) {
452 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
453 // This code path is deprecated. If you want to break upload processing
454 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
455 // and UploadBase::verifyFile.
456 // If you use this hook to break uploading, the user will be returned
457 // an empty form with no error message whatsoever.
458 return;
459 }
460
461 // Upload verification
462 $details = $this->mUpload->verifyUpload();
463 if ( $details['status'] != UploadBase::OK ) {
464 $this->processVerificationError( $details );
465
466 return;
467 }
468
469 // Verify permissions for this title
470 $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
471 if ( $permErrors !== true ) {
472 $code = array_shift( $permErrors[0] );
473 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
474
475 return;
476 }
477
478 $this->mLocalFile = $this->mUpload->getLocalFile();
479
480 // Check warnings if necessary
481 if ( !$this->mIgnoreWarning ) {
482 $warnings = $this->mUpload->checkWarnings();
483 if ( $this->showUploadWarning( $warnings ) ) {
484 return;
485 }
486 }
487
488 // This is as late as we can throttle, after expected issues have been handled
489 if ( UploadBase::isThrottled( $this->getUser() ) ) {
490 $this->showRecoverableUploadError(
491 $this->msg( 'actionthrottledtext' )->escaped()
492 );
493 return;
494 }
495
496 // Get the page text if this is not a reupload
497 if ( !$this->mForReUpload ) {
498 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
499 $this->mCopyrightStatus, $this->mCopyrightSource, $this->getConfig() );
500 } else {
501 $pageText = false;
502 }
503
504 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
505 if ( is_null( $changeTags ) || $changeTags === '' ) {
506 $changeTags = [];
507 } else {
508 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
509 }
510
511 if ( $changeTags ) {
512 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
513 $changeTags, $this->getUser() );
514 if ( !$changeTagsStatus->isOK() ) {
515 $this->showUploadError( $this->getOutput()->parse( $changeTagsStatus->getWikiText() ) );
516
517 return;
518 }
519 }
520
521 $status = $this->mUpload->performUpload(
522 $this->mComment,
523 $pageText,
524 $this->mWatchthis,
525 $this->getUser(),
526 $changeTags
527 );
528
529 if ( !$status->isGood() ) {
530 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
531
532 return;
533 }
534
535 // Success, redirect to description page
536 $this->mUploadSuccessful = true;
537 Hooks::run( 'SpecialUploadComplete', [ &$this ] );
538 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
539 }
540
541 /**
542 * Get the initial image page text based on a comment and optional file status information
543 * @param string $comment
544 * @param string $license
545 * @param string $copyStatus
546 * @param string $source
547 * @param Config $config Configuration object to load data from
548 * @return string
549 */
550 public static function getInitialPageText( $comment = '', $license = '',
551 $copyStatus = '', $source = '', Config $config = null
552 ) {
553 if ( $config === null ) {
554 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
555 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
556 }
557
558 $msg = [];
559 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
560 /* These messages are transcluded into the actual text of the description page.
561 * Thus, forcing them as content messages makes the upload to produce an int: template
562 * instead of hardcoding it there in the uploader language.
563 */
564 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
565 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
566 $msg[$msgName] = "{{int:$msgName}}";
567 } else {
568 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
569 }
570 }
571
572 if ( $config->get( 'UseCopyrightUpload' ) ) {
573 $licensetxt = '';
574 if ( $license != '' ) {
575 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
576 }
577 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
578 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
579 "$licensetxt" .
580 '== ' . $msg['filesource'] . " ==\n" . $source;
581 } else {
582 if ( $license != '' ) {
583 $filedesc = $comment == '' ? '' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
584 $pageText = $filedesc .
585 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
586 } else {
587 $pageText = $comment;
588 }
589 }
590
591 return $pageText;
592 }
593
594 /**
595 * See if we should check the 'watch this page' checkbox on the form
596 * based on the user's preferences and whether we're being asked
597 * to create a new file or update an existing one.
598 *
599 * In the case where 'watch edits' is off but 'watch creations' is on,
600 * we'll leave the box unchecked.
601 *
602 * Note that the page target can be changed *on the form*, so our check
603 * state can get out of sync.
604 * @return bool|string
605 */
606 protected function getWatchCheck() {
607 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
608 // Watch all edits!
609 return true;
610 }
611
612 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
613 if ( $desiredTitleObj instanceof Title && $this->getUser()->isWatched( $desiredTitleObj ) ) {
614 // Already watched, don't change that
615 return true;
616 }
617
618 $local = wfLocalFile( $this->mDesiredDestName );
619 if ( $local && $local->exists() ) {
620 // We're uploading a new version of an existing file.
621 // No creation, so don't watch it if we're not already.
622 return false;
623 } else {
624 // New page should get watched if that's our option.
625 return $this->getUser()->getOption( 'watchcreations' );
626 }
627 }
628
629 /**
630 * Provides output to the user for a result of UploadBase::verifyUpload
631 *
632 * @param array $details Result of UploadBase::verifyUpload
633 * @throws MWException
634 */
635 protected function processVerificationError( $details ) {
636 switch ( $details['status'] ) {
637
638 /** Statuses that only require name changing **/
639 case UploadBase::MIN_LENGTH_PARTNAME:
640 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
641 break;
642 case UploadBase::ILLEGAL_FILENAME:
643 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
644 $details['filtered'] )->parse() );
645 break;
646 case UploadBase::FILENAME_TOO_LONG:
647 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
648 break;
649 case UploadBase::FILETYPE_MISSING:
650 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
651 break;
652 case UploadBase::WINDOWS_NONASCII_FILENAME:
653 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
654 break;
655
656 /** Statuses that require reuploading **/
657 case UploadBase::EMPTY_FILE:
658 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
659 break;
660 case UploadBase::FILE_TOO_LARGE:
661 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
662 break;
663 case UploadBase::FILETYPE_BADTYPE:
664 $msg = $this->msg( 'filetype-banned-type' );
665 if ( isset( $details['blacklistedExt'] ) ) {
666 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
667 } else {
668 $msg->params( $details['finalExt'] );
669 }
670 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
671 $msg->params( $this->getLanguage()->commaList( $extensions ),
672 count( $extensions ) );
673
674 // Add PLURAL support for the first parameter. This results
675 // in a bit unlogical parameter sequence, but does not break
676 // old translations
677 if ( isset( $details['blacklistedExt'] ) ) {
678 $msg->params( count( $details['blacklistedExt'] ) );
679 } else {
680 $msg->params( 1 );
681 }
682
683 $this->showUploadError( $msg->parse() );
684 break;
685 case UploadBase::VERIFICATION_ERROR:
686 unset( $details['status'] );
687 $code = array_shift( $details['details'] );
688 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
689 break;
690 case UploadBase::HOOK_ABORTED:
691 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
692 $args = $details['error'];
693 $error = array_shift( $args );
694 } else {
695 $error = $details['error'];
696 $args = null;
697 }
698
699 $this->showUploadError( $this->msg( $error, $args )->parse() );
700 break;
701 default:
702 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
703 }
704 }
705
706 /**
707 * Remove a temporarily kept file stashed by saveTempUploadedFile().
708 *
709 * @return bool Success
710 */
711 protected function unsaveUploadedFile() {
712 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
713 return true;
714 }
715 $success = $this->mUpload->unsaveUploadedFile();
716 if ( !$success ) {
717 $this->getOutput()->showFileDeleteError( $this->mUpload->getTempPath() );
718
719 return false;
720 } else {
721 return true;
722 }
723 }
724
725 /*** Functions for formatting warnings ***/
726
727 /**
728 * Formats a result of UploadBase::getExistsWarning as HTML
729 * This check is static and can be done pre-upload via AJAX
730 *
731 * @param array $exists The result of UploadBase::getExistsWarning
732 * @return string Empty string if there is no warning or an HTML fragment
733 */
734 public static function getExistsWarning( $exists ) {
735 if ( !$exists ) {
736 return '';
737 }
738
739 $file = $exists['file'];
740 $filename = $file->getTitle()->getPrefixedText();
741 $warning = '';
742
743 if ( $exists['warning'] == 'exists' ) {
744 // Exact match
745 $warning = wfMessage( 'fileexists', $filename )->parse();
746 } elseif ( $exists['warning'] == 'page-exists' ) {
747 // Page exists but file does not
748 $warning = wfMessage( 'filepageexists', $filename )->parse();
749 } elseif ( $exists['warning'] == 'exists-normalized' ) {
750 $warning = wfMessage( 'fileexists-extension', $filename,
751 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
752 } elseif ( $exists['warning'] == 'thumb' ) {
753 // Swapped argument order compared with other messages for backwards compatibility
754 $warning = wfMessage( 'fileexists-thumbnail-yes',
755 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
756 } elseif ( $exists['warning'] == 'thumb-name' ) {
757 // Image w/o '180px-' does not exists, but we do not like these filenames
758 $name = $file->getName();
759 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
760 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
761 } elseif ( $exists['warning'] == 'bad-prefix' ) {
762 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
763 }
764
765 return $warning;
766 }
767
768 /**
769 * Construct a warning and a gallery from an array of duplicate files.
770 * @param array $dupes
771 * @return string
772 */
773 public function getDupeWarning( $dupes ) {
774 if ( !$dupes ) {
775 return '';
776 }
777
778 $gallery = ImageGalleryBase::factory( false, $this->getContext() );
779 $gallery->setShowBytes( false );
780 foreach ( $dupes as $file ) {
781 $gallery->add( $file->getTitle() );
782 }
783
784 return '<li>' .
785 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
786 $gallery->toHTML() . "</li>\n";
787 }
788
789 protected function getGroupName() {
790 return 'media';
791 }
792
793 /**
794 * Should we rotate images in the preview on Special:Upload.
795 *
796 * This controls js: mw.config.get( 'wgFileCanRotate' )
797 *
798 * @todo What about non-BitmapHandler handled files?
799 */
800 public static function rotationEnabled() {
801 $bitmapHandler = new BitmapHandler();
802 return $bitmapHandler->autoRotateEnabled();
803 }
804 }
805
806 /**
807 * Sub class of HTMLForm that provides the form section of SpecialUpload
808 */
809 class UploadForm extends HTMLForm {
810 protected $mWatch;
811 protected $mForReUpload;
812 protected $mSessionKey;
813 protected $mHideIgnoreWarning;
814 protected $mDestWarningAck;
815 protected $mDestFile;
816
817 protected $mComment;
818 protected $mTextTop;
819 protected $mTextAfterSummary;
820
821 protected $mSourceIds;
822
823 protected $mMaxFileSize = [];
824
825 protected $mMaxUploadSize = [];
826
827 public function __construct( array $options = [], IContextSource $context = null ) {
828 if ( $context instanceof IContextSource ) {
829 $this->setContext( $context );
830 }
831
832 $this->mWatch = !empty( $options['watch'] );
833 $this->mForReUpload = !empty( $options['forreupload'] );
834 $this->mSessionKey = isset( $options['sessionkey'] ) ? $options['sessionkey'] : '';
835 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
836 $this->mDestWarningAck = !empty( $options['destwarningack'] );
837 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
838
839 $this->mComment = isset( $options['description'] ) ?
840 $options['description'] : '';
841
842 $this->mTextTop = isset( $options['texttop'] )
843 ? $options['texttop'] : '';
844
845 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
846 ? $options['textaftersummary'] : '';
847
848 $sourceDescriptor = $this->getSourceSection();
849 $descriptor = $sourceDescriptor
850 + $this->getDescriptionSection()
851 + $this->getOptionsSection();
852
853 Hooks::run( 'UploadFormInitDescriptor', [ &$descriptor ] );
854 parent::__construct( $descriptor, $context, 'upload' );
855
856 # Add a link to edit MediaWik:Licenses
857 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
858 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
859 $licensesLink = Linker::linkKnown(
860 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
861 $this->msg( 'licenses-edit' )->escaped(),
862 [],
863 [ 'action' => 'edit' ]
864 );
865 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
866 $this->addFooterText( $editLicenses, 'description' );
867 }
868
869 # Set some form properties
870 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
871 $this->setSubmitName( 'wpUpload' );
872 # Used message keys: 'accesskey-upload', 'tooltip-upload'
873 $this->setSubmitTooltip( 'upload' );
874 $this->setId( 'mw-upload-form' );
875
876 # Build a list of IDs for javascript insertion
877 $this->mSourceIds = [];
878 foreach ( $sourceDescriptor as $field ) {
879 if ( !empty( $field['id'] ) ) {
880 $this->mSourceIds[] = $field['id'];
881 }
882 }
883 }
884
885 /**
886 * Get the descriptor of the fieldset that contains the file source
887 * selection. The section is 'source'
888 *
889 * @return array Descriptor array
890 */
891 protected function getSourceSection() {
892 if ( $this->mSessionKey ) {
893 return [
894 'SessionKey' => [
895 'type' => 'hidden',
896 'default' => $this->mSessionKey,
897 ],
898 'SourceType' => [
899 'type' => 'hidden',
900 'default' => 'Stash',
901 ],
902 ];
903 }
904
905 $canUploadByUrl = UploadFromUrl::isEnabled()
906 && ( UploadFromUrl::isAllowed( $this->getUser() ) === true )
907 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
908 $radio = $canUploadByUrl;
909 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
910
911 $descriptor = [];
912 if ( $this->mTextTop ) {
913 $descriptor['UploadFormTextTop'] = [
914 'type' => 'info',
915 'section' => 'source',
916 'default' => $this->mTextTop,
917 'raw' => true,
918 ];
919 }
920
921 $this->mMaxUploadSize['file'] = min(
922 UploadBase::getMaxUploadSize( 'file' ),
923 UploadBase::getMaxPhpUploadSize()
924 );
925
926 $help = $this->msg( 'upload-maxfilesize',
927 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] )
928 )->parse();
929
930 // If the user can also upload by URL, there are 2 different file size limits.
931 // This extra message helps stress which limit corresponds to what.
932 if ( $canUploadByUrl ) {
933 $help .= $this->msg( 'word-separator' )->escaped();
934 $help .= $this->msg( 'upload_source_file' )->parse();
935 }
936
937 $descriptor['UploadFile'] = [
938 'class' => 'UploadSourceField',
939 'section' => 'source',
940 'type' => 'file',
941 'id' => 'wpUploadFile',
942 'radio-id' => 'wpSourceTypeFile',
943 'label-message' => 'sourcefilename',
944 'upload-type' => 'File',
945 'radio' => &$radio,
946 'help' => $help,
947 'checked' => $selectedSourceType == 'file',
948 ];
949
950 if ( $canUploadByUrl ) {
951 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
952 $descriptor['UploadFileURL'] = [
953 'class' => 'UploadSourceField',
954 'section' => 'source',
955 'id' => 'wpUploadFileURL',
956 'radio-id' => 'wpSourceTypeurl',
957 'label-message' => 'sourceurl',
958 'upload-type' => 'url',
959 'radio' => &$radio,
960 'help' => $this->msg( 'upload-maxfilesize',
961 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] )
962 )->parse() .
963 $this->msg( 'word-separator' )->escaped() .
964 $this->msg( 'upload_source_url' )->parse(),
965 'checked' => $selectedSourceType == 'url',
966 ];
967 }
968 Hooks::run( 'UploadFormSourceDescriptors', [ &$descriptor, &$radio, $selectedSourceType ] );
969
970 $descriptor['Extensions'] = [
971 'type' => 'info',
972 'section' => 'source',
973 'default' => $this->getExtensionsMessage(),
974 'raw' => true,
975 ];
976
977 return $descriptor;
978 }
979
980 /**
981 * Get the messages indicating which extensions are preferred and prohibitted.
982 *
983 * @return string HTML string containing the message
984 */
985 protected function getExtensionsMessage() {
986 # Print a list of allowed file extensions, if so configured. We ignore
987 # MIME type here, it's incomprehensible to most people and too long.
988 $config = $this->getConfig();
989
990 if ( $config->get( 'CheckFileExtensions' ) ) {
991 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
992 if ( $config->get( 'StrictFileExtensions' ) ) {
993 # Everything not permitted is banned
994 $extensionsList =
995 '<div id="mw-upload-permitted">' .
996 $this->msg( 'upload-permitted' )
997 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
998 ->numParams( count( $fileExtensions ) )
999 ->parseAsBlock() .
1000 "</div>\n";
1001 } else {
1002 # We have to list both preferred and prohibited
1003 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
1004 $extensionsList =
1005 '<div id="mw-upload-preferred">' .
1006 $this->msg( 'upload-preferred' )
1007 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1008 ->numParams( count( $fileExtensions ) )
1009 ->parseAsBlock() .
1010 "</div>\n" .
1011 '<div id="mw-upload-prohibited">' .
1012 $this->msg( 'upload-prohibited' )
1013 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
1014 ->numParams( count( $fileBlacklist ) )
1015 ->parseAsBlock() .
1016 "</div>\n";
1017 }
1018 } else {
1019 # Everything is permitted.
1020 $extensionsList = '';
1021 }
1022
1023 return $extensionsList;
1024 }
1025
1026 /**
1027 * Get the descriptor of the fieldset that contains the file description
1028 * input. The section is 'description'
1029 *
1030 * @return array Descriptor array
1031 */
1032 protected function getDescriptionSection() {
1033 $config = $this->getConfig();
1034 if ( $this->mSessionKey ) {
1035 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1036 try {
1037 $file = $stash->getFile( $this->mSessionKey );
1038 } catch ( Exception $e ) {
1039 $file = null;
1040 }
1041 if ( $file ) {
1042 global $wgContLang;
1043
1044 $mto = $file->transform( [ 'width' => 120 ] );
1045 $this->addHeaderText(
1046 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1047 Html::element( 'img', [
1048 'src' => $mto->getUrl(),
1049 'class' => 'thumbimage',
1050 ] ) . '</div>', 'description' );
1051 }
1052 }
1053
1054 $descriptor = [
1055 'DestFile' => [
1056 'type' => 'text',
1057 'section' => 'description',
1058 'id' => 'wpDestFile',
1059 'label-message' => 'destfilename',
1060 'size' => 60,
1061 'default' => $this->mDestFile,
1062 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1063 'nodata' => strval( $this->mDestFile ) !== '',
1064 ],
1065 'UploadDescription' => [
1066 'type' => 'textarea',
1067 'section' => 'description',
1068 'id' => 'wpUploadDescription',
1069 'label-message' => $this->mForReUpload
1070 ? 'filereuploadsummary'
1071 : 'fileuploadsummary',
1072 'default' => $this->mComment,
1073 'cols' => $this->getUser()->getIntOption( 'cols' ),
1074 'rows' => 8,
1075 ]
1076 ];
1077 if ( $this->mTextAfterSummary ) {
1078 $descriptor['UploadFormTextAfterSummary'] = [
1079 'type' => 'info',
1080 'section' => 'description',
1081 'default' => $this->mTextAfterSummary,
1082 'raw' => true,
1083 ];
1084 }
1085
1086 $descriptor += [
1087 'EditTools' => [
1088 'type' => 'edittools',
1089 'section' => 'description',
1090 'message' => 'edittools-upload',
1091 ]
1092 ];
1093
1094 if ( $this->mForReUpload ) {
1095 $descriptor['DestFile']['readonly'] = true;
1096 } else {
1097 $descriptor['License'] = [
1098 'type' => 'select',
1099 'class' => 'Licenses',
1100 'section' => 'description',
1101 'id' => 'wpLicense',
1102 'label-message' => 'license',
1103 ];
1104 }
1105
1106 if ( $config->get( 'UseCopyrightUpload' ) ) {
1107 $descriptor['UploadCopyStatus'] = [
1108 'type' => 'text',
1109 'section' => 'description',
1110 'id' => 'wpUploadCopyStatus',
1111 'label-message' => 'filestatus',
1112 ];
1113 $descriptor['UploadSource'] = [
1114 'type' => 'text',
1115 'section' => 'description',
1116 'id' => 'wpUploadSource',
1117 'label-message' => 'filesource',
1118 ];
1119 }
1120
1121 return $descriptor;
1122 }
1123
1124 /**
1125 * Get the descriptor of the fieldset that contains the upload options,
1126 * such as "watch this file". The section is 'options'
1127 *
1128 * @return array Descriptor array
1129 */
1130 protected function getOptionsSection() {
1131 $user = $this->getUser();
1132 if ( $user->isLoggedIn() ) {
1133 $descriptor = [
1134 'Watchthis' => [
1135 'type' => 'check',
1136 'id' => 'wpWatchthis',
1137 'label-message' => 'watchthisupload',
1138 'section' => 'options',
1139 'default' => $this->mWatch,
1140 ]
1141 ];
1142 }
1143 if ( !$this->mHideIgnoreWarning ) {
1144 $descriptor['IgnoreWarning'] = [
1145 'type' => 'check',
1146 'id' => 'wpIgnoreWarning',
1147 'label-message' => 'ignorewarnings',
1148 'section' => 'options',
1149 ];
1150 }
1151
1152 $descriptor['DestFileWarningAck'] = [
1153 'type' => 'hidden',
1154 'id' => 'wpDestFileWarningAck',
1155 'default' => $this->mDestWarningAck ? '1' : '',
1156 ];
1157
1158 if ( $this->mForReUpload ) {
1159 $descriptor['ForReUpload'] = [
1160 'type' => 'hidden',
1161 'id' => 'wpForReUpload',
1162 'default' => '1',
1163 ];
1164 }
1165
1166 return $descriptor;
1167 }
1168
1169 /**
1170 * Add the upload JS and show the form.
1171 */
1172 public function show() {
1173 $this->addUploadJS();
1174 parent::show();
1175 }
1176
1177 /**
1178 * Add upload JS to the OutputPage
1179 */
1180 protected function addUploadJS() {
1181 $config = $this->getConfig();
1182
1183 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1184 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1185 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1186 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1187
1188 $scriptVars = [
1189 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1190 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1191 'wgUploadAutoFill' => !$this->mForReUpload &&
1192 // If we received mDestFile from the request, don't autofill
1193 // the wpDestFile textbox
1194 $this->mDestFile === '',
1195 'wgUploadSourceIds' => $this->mSourceIds,
1196 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1197 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1198 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1199 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1200 'wgMaxUploadSize' => $this->mMaxUploadSize,
1201 'wgFileCanRotate' => SpecialUpload::rotationEnabled(),
1202 ];
1203
1204 $out = $this->getOutput();
1205 $out->addJsConfigVars( $scriptVars );
1206
1207 $out->addModules( [
1208 'mediawiki.action.edit', // For <charinsert> support
1209 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1210 ] );
1211 }
1212
1213 /**
1214 * Empty function; submission is handled elsewhere.
1215 *
1216 * @return bool False
1217 */
1218 function trySubmit() {
1219 return false;
1220 }
1221 }
1222
1223 /**
1224 * A form field that contains a radio box in the label
1225 */
1226 class UploadSourceField extends HTMLTextField {
1227
1228 /**
1229 * @param array $cellAttributes
1230 * @return string
1231 */
1232 function getLabelHtml( $cellAttributes = [] ) {
1233 $id = $this->mParams['id'];
1234 $label = Html::rawElement( 'label', [ 'for' => $id ], $this->mLabel );
1235
1236 if ( !empty( $this->mParams['radio'] ) ) {
1237 if ( isset( $this->mParams['radio-id'] ) ) {
1238 $radioId = $this->mParams['radio-id'];
1239 } else {
1240 // Old way. For the benefit of extensions that do not define
1241 // the 'radio-id' key.
1242 $radioId = 'wpSourceType' . $this->mParams['upload-type'];
1243 }
1244
1245 $attribs = [
1246 'name' => 'wpSourceType',
1247 'type' => 'radio',
1248 'id' => $radioId,
1249 'value' => $this->mParams['upload-type'],
1250 ];
1251
1252 if ( !empty( $this->mParams['checked'] ) ) {
1253 $attribs['checked'] = 'checked';
1254 }
1255
1256 $label .= Html::element( 'input', $attribs );
1257 }
1258
1259 return Html::rawElement( 'td', [ 'class' => 'mw-label' ] + $cellAttributes, $label );
1260 }
1261
1262 /**
1263 * @return int
1264 */
1265 function getSize() {
1266 return isset( $this->mParams['size'] )
1267 ? $this->mParams['size']
1268 : 60;
1269 }
1270 }