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