Merge "Protect WAN cache sets() against uncommitted data"
[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'] = UploadBase::getMaxUploadSize( 'file' );
894 # Limit to upload_max_filesize unless we are running under HipHop and
895 # that setting doesn't exist
896 if ( !wfIsHHVM() ) {
897 $this->mMaxUploadSize['file'] = min( $this->mMaxUploadSize['file'],
898 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
899 wfShorthandToInteger( ini_get( 'post_max_size' ) )
900 );
901 }
902
903 $help = $this->msg( 'upload-maxfilesize',
904 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] )
905 )->parse();
906
907 // If the user can also upload by URL, there are 2 different file size limits.
908 // This extra message helps stress which limit corresponds to what.
909 if ( $canUploadByUrl ) {
910 $help .= $this->msg( 'word-separator' )->escaped();
911 $help .= $this->msg( 'upload_source_file' )->parse();
912 }
913
914 $descriptor['UploadFile'] = array(
915 'class' => 'UploadSourceField',
916 'section' => 'source',
917 'type' => 'file',
918 'id' => 'wpUploadFile',
919 'radio-id' => 'wpSourceTypeFile',
920 'label-message' => 'sourcefilename',
921 'upload-type' => 'File',
922 'radio' => &$radio,
923 'help' => $help,
924 'checked' => $selectedSourceType == 'file',
925 );
926
927 if ( $canUploadByUrl ) {
928 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
929 $descriptor['UploadFileURL'] = array(
930 'class' => 'UploadSourceField',
931 'section' => 'source',
932 'id' => 'wpUploadFileURL',
933 'radio-id' => 'wpSourceTypeurl',
934 'label-message' => 'sourceurl',
935 'upload-type' => 'url',
936 'radio' => &$radio,
937 'help' => $this->msg( 'upload-maxfilesize',
938 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] )
939 )->parse() .
940 $this->msg( 'word-separator' )->escaped() .
941 $this->msg( 'upload_source_url' )->parse(),
942 'checked' => $selectedSourceType == 'url',
943 );
944 }
945 Hooks::run( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
946
947 $descriptor['Extensions'] = array(
948 'type' => 'info',
949 'section' => 'source',
950 'default' => $this->getExtensionsMessage(),
951 'raw' => true,
952 );
953
954 return $descriptor;
955 }
956
957 /**
958 * Get the messages indicating which extensions are preferred and prohibitted.
959 *
960 * @return string HTML string containing the message
961 */
962 protected function getExtensionsMessage() {
963 # Print a list of allowed file extensions, if so configured. We ignore
964 # MIME type here, it's incomprehensible to most people and too long.
965 $config = $this->getConfig();
966
967 if ( $config->get( 'CheckFileExtensions' ) ) {
968 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
969 if ( $config->get( 'StrictFileExtensions' ) ) {
970 # Everything not permitted is banned
971 $extensionsList =
972 '<div id="mw-upload-permitted">' .
973 $this->msg( 'upload-permitted' )
974 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
975 ->numParams( count( $fileExtensions ) )
976 ->parseAsBlock() .
977 "</div>\n";
978 } else {
979 # We have to list both preferred and prohibited
980 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
981 $extensionsList =
982 '<div id="mw-upload-preferred">' .
983 $this->msg( 'upload-preferred' )
984 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
985 ->numParams( count( $fileExtensions ) )
986 ->parseAsBlock() .
987 "</div>\n" .
988 '<div id="mw-upload-prohibited">' .
989 $this->msg( 'upload-prohibited' )
990 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
991 ->numParams( count( $fileBlacklist ) )
992 ->parseAsBlock() .
993 "</div>\n";
994 }
995 } else {
996 # Everything is permitted.
997 $extensionsList = '';
998 }
999
1000 return $extensionsList;
1001 }
1002
1003 /**
1004 * Get the descriptor of the fieldset that contains the file description
1005 * input. The section is 'description'
1006 *
1007 * @return array Descriptor array
1008 */
1009 protected function getDescriptionSection() {
1010 $config = $this->getConfig();
1011 if ( $this->mSessionKey ) {
1012 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1013 try {
1014 $file = $stash->getFile( $this->mSessionKey );
1015 } catch ( Exception $e ) {
1016 $file = null;
1017 }
1018 if ( $file ) {
1019 global $wgContLang;
1020
1021 $mto = $file->transform( array( 'width' => 120 ) );
1022 $this->addHeaderText(
1023 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1024 Html::element( 'img', array(
1025 'src' => $mto->getUrl(),
1026 'class' => 'thumbimage',
1027 ) ) . '</div>', 'description' );
1028 }
1029 }
1030
1031 $descriptor = array(
1032 'DestFile' => array(
1033 'type' => 'text',
1034 'section' => 'description',
1035 'id' => 'wpDestFile',
1036 'label-message' => 'destfilename',
1037 'size' => 60,
1038 'default' => $this->mDestFile,
1039 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1040 'nodata' => strval( $this->mDestFile ) !== '',
1041 ),
1042 'UploadDescription' => array(
1043 'type' => 'textarea',
1044 'section' => 'description',
1045 'id' => 'wpUploadDescription',
1046 'label-message' => $this->mForReUpload
1047 ? 'filereuploadsummary'
1048 : 'fileuploadsummary',
1049 'default' => $this->mComment,
1050 'cols' => $this->getUser()->getIntOption( 'cols' ),
1051 'rows' => 8,
1052 )
1053 );
1054 if ( $this->mTextAfterSummary ) {
1055 $descriptor['UploadFormTextAfterSummary'] = array(
1056 'type' => 'info',
1057 'section' => 'description',
1058 'default' => $this->mTextAfterSummary,
1059 'raw' => true,
1060 );
1061 }
1062
1063 $descriptor += array(
1064 'EditTools' => array(
1065 'type' => 'edittools',
1066 'section' => 'description',
1067 'message' => 'edittools-upload',
1068 )
1069 );
1070
1071 if ( $this->mForReUpload ) {
1072 $descriptor['DestFile']['readonly'] = true;
1073 } else {
1074 $descriptor['License'] = array(
1075 'type' => 'select',
1076 'class' => 'Licenses',
1077 'section' => 'description',
1078 'id' => 'wpLicense',
1079 'label-message' => 'license',
1080 );
1081 }
1082
1083 if ( $config->get( 'UseCopyrightUpload' ) ) {
1084 $descriptor['UploadCopyStatus'] = array(
1085 'type' => 'text',
1086 'section' => 'description',
1087 'id' => 'wpUploadCopyStatus',
1088 'label-message' => 'filestatus',
1089 );
1090 $descriptor['UploadSource'] = array(
1091 'type' => 'text',
1092 'section' => 'description',
1093 'id' => 'wpUploadSource',
1094 'label-message' => 'filesource',
1095 );
1096 }
1097
1098 return $descriptor;
1099 }
1100
1101 /**
1102 * Get the descriptor of the fieldset that contains the upload options,
1103 * such as "watch this file". The section is 'options'
1104 *
1105 * @return array Descriptor array
1106 */
1107 protected function getOptionsSection() {
1108 $user = $this->getUser();
1109 if ( $user->isLoggedIn() ) {
1110 $descriptor = array(
1111 'Watchthis' => array(
1112 'type' => 'check',
1113 'id' => 'wpWatchthis',
1114 'label-message' => 'watchthisupload',
1115 'section' => 'options',
1116 'default' => $this->mWatch,
1117 )
1118 );
1119 }
1120 if ( !$this->mHideIgnoreWarning ) {
1121 $descriptor['IgnoreWarning'] = array(
1122 'type' => 'check',
1123 'id' => 'wpIgnoreWarning',
1124 'label-message' => 'ignorewarnings',
1125 'section' => 'options',
1126 );
1127 }
1128
1129 $descriptor['DestFileWarningAck'] = array(
1130 'type' => 'hidden',
1131 'id' => 'wpDestFileWarningAck',
1132 'default' => $this->mDestWarningAck ? '1' : '',
1133 );
1134
1135 if ( $this->mForReUpload ) {
1136 $descriptor['ForReUpload'] = array(
1137 'type' => 'hidden',
1138 'id' => 'wpForReUpload',
1139 'default' => '1',
1140 );
1141 }
1142
1143 return $descriptor;
1144 }
1145
1146 /**
1147 * Add the upload JS and show the form.
1148 */
1149 public function show() {
1150 $this->addUploadJS();
1151 parent::show();
1152 }
1153
1154 /**
1155 * Add upload JS to the OutputPage
1156 */
1157 protected function addUploadJS() {
1158 $config = $this->getConfig();
1159
1160 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1161 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1162 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1163 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1164
1165 $scriptVars = array(
1166 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1167 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1168 'wgUploadAutoFill' => !$this->mForReUpload &&
1169 // If we received mDestFile from the request, don't autofill
1170 // the wpDestFile textbox
1171 $this->mDestFile === '',
1172 'wgUploadSourceIds' => $this->mSourceIds,
1173 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1174 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1175 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1176 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1177 'wgMaxUploadSize' => $this->mMaxUploadSize,
1178 'wgFileCanRotate' => SpecialUpload::rotationEnabled(),
1179 );
1180
1181 $out = $this->getOutput();
1182 $out->addJsConfigVars( $scriptVars );
1183
1184 $out->addModules( array(
1185 'mediawiki.action.edit', // For <charinsert> support
1186 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1187 ) );
1188 }
1189
1190 /**
1191 * Empty function; submission is handled elsewhere.
1192 *
1193 * @return bool False
1194 */
1195 function trySubmit() {
1196 return false;
1197 }
1198 }
1199
1200 /**
1201 * A form field that contains a radio box in the label
1202 */
1203 class UploadSourceField extends HTMLTextField {
1204
1205 /**
1206 * @param array $cellAttributes
1207 * @return string
1208 */
1209 function getLabelHtml( $cellAttributes = array() ) {
1210 $id = $this->mParams['id'];
1211 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1212
1213 if ( !empty( $this->mParams['radio'] ) ) {
1214 if ( isset( $this->mParams['radio-id'] ) ) {
1215 $radioId = $this->mParams['radio-id'];
1216 } else {
1217 // Old way. For the benefit of extensions that do not define
1218 // the 'radio-id' key.
1219 $radioId = 'wpSourceType' . $this->mParams['upload-type'];
1220 }
1221
1222 $attribs = array(
1223 'name' => 'wpSourceType',
1224 'type' => 'radio',
1225 'id' => $radioId,
1226 'value' => $this->mParams['upload-type'],
1227 );
1228
1229 if ( !empty( $this->mParams['checked'] ) ) {
1230 $attribs['checked'] = 'checked';
1231 }
1232
1233 $label .= Html::element( 'input', $attribs );
1234 }
1235
1236 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1237 }
1238
1239 /**
1240 * @return int
1241 */
1242 function getSize() {
1243 return isset( $this->mParams['size'] )
1244 ? $this->mParams['size']
1245 : 60;
1246 }
1247 }