Merge "jquery.accessKeyLabel: make modifier info public"
[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( array(
409 'name' => 'wpUploadIgnoreWarning',
410 'value' => $this->msg( 'ignorewarning' )->text()
411 ) );
412 $form->addButton( array(
413 'name' => 'wpCancelUpload',
414 'value' => $this->msg( 'reuploaddesc' )->text()
415 ) );
416
417 $this->showUploadForm( $form );
418
419 # Indicate that we showed a form
420 return true;
421 }
422
423 /**
424 * Show the upload form with error message, but do not stash the file.
425 *
426 * @param string $message HTML string
427 */
428 protected function showUploadError( $message ) {
429 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
430 '<div class="error">' . $message . "</div>\n";
431 $this->showUploadForm( $this->getUploadForm( $message ) );
432 }
433
434 /**
435 * Do the upload.
436 * Checks are made in SpecialUpload::execute()
437 */
438 protected function processUpload() {
439 // Fetch the file if required
440 $status = $this->mUpload->fetchFile();
441 if ( !$status->isOK() ) {
442 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
443
444 return;
445 }
446
447 if ( !Hooks::run( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
448 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
449 // This code path is deprecated. If you want to break upload processing
450 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
451 // and UploadBase::verifyFile.
452 // If you use this hook to break uploading, the user will be returned
453 // an empty form with no error message whatsoever.
454 return;
455 }
456
457 // Upload verification
458 $details = $this->mUpload->verifyUpload();
459 if ( $details['status'] != UploadBase::OK ) {
460 $this->processVerificationError( $details );
461
462 return;
463 }
464
465 // Verify permissions for this title
466 $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
467 if ( $permErrors !== true ) {
468 $code = array_shift( $permErrors[0] );
469 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
470
471 return;
472 }
473
474 $this->mLocalFile = $this->mUpload->getLocalFile();
475
476 // Check warnings if necessary
477 if ( !$this->mIgnoreWarning ) {
478 $warnings = $this->mUpload->checkWarnings();
479 if ( $this->showUploadWarning( $warnings ) ) {
480 return;
481 }
482 }
483
484 // This is as late as we can throttle, after expected issues have been handled
485 if ( UploadBase::isThrottled( $this->getUser() ) ) {
486 $this->showRecoverableUploadError(
487 $this->msg( 'actionthrottledtext' )->escaped()
488 );
489 return;
490 }
491
492 // Get the page text if this is not a reupload
493 if ( !$this->mForReUpload ) {
494 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
495 $this->mCopyrightStatus, $this->mCopyrightSource, $this->getConfig() );
496 } else {
497 $pageText = false;
498 }
499
500 $status = $this->mUpload->performUpload(
501 $this->mComment,
502 $pageText,
503 $this->mWatchthis,
504 $this->getUser()
505 );
506
507 if ( !$status->isGood() ) {
508 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
509
510 return;
511 }
512
513 // Success, redirect to description page
514 $this->mUploadSuccessful = true;
515 Hooks::run( 'SpecialUploadComplete', array( &$this ) );
516 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
517 }
518
519 /**
520 * Get the initial image page text based on a comment and optional file status information
521 * @param string $comment
522 * @param string $license
523 * @param string $copyStatus
524 * @param string $source
525 * @param Config $config Configuration object to load data from
526 * @return string
527 */
528 public static function getInitialPageText( $comment = '', $license = '',
529 $copyStatus = '', $source = '', Config $config = null
530 ) {
531 if ( $config === null ) {
532 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
533 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
534 }
535
536 $msg = array();
537 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
538 /* These messages are transcluded into the actual text of the description page.
539 * Thus, forcing them as content messages makes the upload to produce an int: template
540 * instead of hardcoding it there in the uploader language.
541 */
542 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
543 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
544 $msg[$msgName] = "{{int:$msgName}}";
545 } else {
546 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
547 }
548 }
549
550 if ( $config->get( 'UseCopyrightUpload' ) ) {
551 $licensetxt = '';
552 if ( $license != '' ) {
553 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
554 }
555 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
556 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
557 "$licensetxt" .
558 '== ' . $msg['filesource'] . " ==\n" . $source;
559 } else {
560 if ( $license != '' ) {
561 $filedesc = $comment == '' ? '' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
562 $pageText = $filedesc .
563 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
564 } else {
565 $pageText = $comment;
566 }
567 }
568
569 return $pageText;
570 }
571
572 /**
573 * See if we should check the 'watch this page' checkbox on the form
574 * based on the user's preferences and whether we're being asked
575 * to create a new file or update an existing one.
576 *
577 * In the case where 'watch edits' is off but 'watch creations' is on,
578 * we'll leave the box unchecked.
579 *
580 * Note that the page target can be changed *on the form*, so our check
581 * state can get out of sync.
582 * @return bool|string
583 */
584 protected function getWatchCheck() {
585 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
586 // Watch all edits!
587 return true;
588 }
589
590 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
591 if ( $desiredTitleObj instanceof Title && $this->getUser()->isWatched( $desiredTitleObj ) ) {
592 // Already watched, don't change that
593 return true;
594 }
595
596 $local = wfLocalFile( $this->mDesiredDestName );
597 if ( $local && $local->exists() ) {
598 // We're uploading a new version of an existing file.
599 // No creation, so don't watch it if we're not already.
600 return false;
601 } else {
602 // New page should get watched if that's our option.
603 return $this->getUser()->getOption( 'watchcreations' );
604 }
605 }
606
607 /**
608 * Provides output to the user for a result of UploadBase::verifyUpload
609 *
610 * @param array $details Result of UploadBase::verifyUpload
611 * @throws MWException
612 */
613 protected function processVerificationError( $details ) {
614 switch ( $details['status'] ) {
615
616 /** Statuses that only require name changing **/
617 case UploadBase::MIN_LENGTH_PARTNAME:
618 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
619 break;
620 case UploadBase::ILLEGAL_FILENAME:
621 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
622 $details['filtered'] )->parse() );
623 break;
624 case UploadBase::FILENAME_TOO_LONG:
625 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
626 break;
627 case UploadBase::FILETYPE_MISSING:
628 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
629 break;
630 case UploadBase::WINDOWS_NONASCII_FILENAME:
631 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
632 break;
633
634 /** Statuses that require reuploading **/
635 case UploadBase::EMPTY_FILE:
636 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
637 break;
638 case UploadBase::FILE_TOO_LARGE:
639 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
640 break;
641 case UploadBase::FILETYPE_BADTYPE:
642 $msg = $this->msg( 'filetype-banned-type' );
643 if ( isset( $details['blacklistedExt'] ) ) {
644 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
645 } else {
646 $msg->params( $details['finalExt'] );
647 }
648 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
649 $msg->params( $this->getLanguage()->commaList( $extensions ),
650 count( $extensions ) );
651
652 // Add PLURAL support for the first parameter. This results
653 // in a bit unlogical parameter sequence, but does not break
654 // old translations
655 if ( isset( $details['blacklistedExt'] ) ) {
656 $msg->params( count( $details['blacklistedExt'] ) );
657 } else {
658 $msg->params( 1 );
659 }
660
661 $this->showUploadError( $msg->parse() );
662 break;
663 case UploadBase::VERIFICATION_ERROR:
664 unset( $details['status'] );
665 $code = array_shift( $details['details'] );
666 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
667 break;
668 case UploadBase::HOOK_ABORTED:
669 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
670 $args = $details['error'];
671 $error = array_shift( $args );
672 } else {
673 $error = $details['error'];
674 $args = null;
675 }
676
677 $this->showUploadError( $this->msg( $error, $args )->parse() );
678 break;
679 default:
680 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
681 }
682 }
683
684 /**
685 * Remove a temporarily kept file stashed by saveTempUploadedFile().
686 *
687 * @return bool Success
688 */
689 protected function unsaveUploadedFile() {
690 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
691 return true;
692 }
693 $success = $this->mUpload->unsaveUploadedFile();
694 if ( !$success ) {
695 $this->getOutput()->showFileDeleteError( $this->mUpload->getTempPath() );
696
697 return false;
698 } else {
699 return true;
700 }
701 }
702
703 /*** Functions for formatting warnings ***/
704
705 /**
706 * Formats a result of UploadBase::getExistsWarning as HTML
707 * This check is static and can be done pre-upload via AJAX
708 *
709 * @param array $exists The result of UploadBase::getExistsWarning
710 * @return string Empty string if there is no warning or an HTML fragment
711 */
712 public static function getExistsWarning( $exists ) {
713 if ( !$exists ) {
714 return '';
715 }
716
717 $file = $exists['file'];
718 $filename = $file->getTitle()->getPrefixedText();
719 $warning = '';
720
721 if ( $exists['warning'] == 'exists' ) {
722 // Exact match
723 $warning = wfMessage( 'fileexists', $filename )->parse();
724 } elseif ( $exists['warning'] == 'page-exists' ) {
725 // Page exists but file does not
726 $warning = wfMessage( 'filepageexists', $filename )->parse();
727 } elseif ( $exists['warning'] == 'exists-normalized' ) {
728 $warning = wfMessage( 'fileexists-extension', $filename,
729 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
730 } elseif ( $exists['warning'] == 'thumb' ) {
731 // Swapped argument order compared with other messages for backwards compatibility
732 $warning = wfMessage( 'fileexists-thumbnail-yes',
733 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
734 } elseif ( $exists['warning'] == 'thumb-name' ) {
735 // Image w/o '180px-' does not exists, but we do not like these filenames
736 $name = $file->getName();
737 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
738 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
739 } elseif ( $exists['warning'] == 'bad-prefix' ) {
740 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
741 }
742
743 return $warning;
744 }
745
746 /**
747 * Construct a warning and a gallery from an array of duplicate files.
748 * @param array $dupes
749 * @return string
750 */
751 public function getDupeWarning( $dupes ) {
752 if ( !$dupes ) {
753 return '';
754 }
755
756 $gallery = ImageGalleryBase::factory( false, $this->getContext() );
757 $gallery->setShowBytes( false );
758 foreach ( $dupes as $file ) {
759 $gallery->add( $file->getTitle() );
760 }
761
762 return '<li>' .
763 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
764 $gallery->toHTML() . "</li>\n";
765 }
766
767 protected function getGroupName() {
768 return 'media';
769 }
770
771 /**
772 * Should we rotate images in the preview on Special:Upload.
773 *
774 * This controls js: mw.config.get( 'wgFileCanRotate' )
775 *
776 * @todo What about non-BitmapHandler handled files?
777 */
778 public static function rotationEnabled() {
779 $bitmapHandler = new BitmapHandler();
780 return $bitmapHandler->autoRotateEnabled();
781 }
782 }
783
784 /**
785 * Sub class of HTMLForm that provides the form section of SpecialUpload
786 */
787 class UploadForm extends HTMLForm {
788 protected $mWatch;
789 protected $mForReUpload;
790 protected $mSessionKey;
791 protected $mHideIgnoreWarning;
792 protected $mDestWarningAck;
793 protected $mDestFile;
794
795 protected $mComment;
796 protected $mTextTop;
797 protected $mTextAfterSummary;
798
799 protected $mSourceIds;
800
801 protected $mMaxFileSize = array();
802
803 protected $mMaxUploadSize = array();
804
805 public function __construct( array $options = array(), IContextSource $context = null ) {
806 if ( $context instanceof IContextSource ) {
807 $this->setContext( $context );
808 }
809
810 $this->mWatch = !empty( $options['watch'] );
811 $this->mForReUpload = !empty( $options['forreupload'] );
812 $this->mSessionKey = isset( $options['sessionkey'] ) ? $options['sessionkey'] : '';
813 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
814 $this->mDestWarningAck = !empty( $options['destwarningack'] );
815 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
816
817 $this->mComment = isset( $options['description'] ) ?
818 $options['description'] : '';
819
820 $this->mTextTop = isset( $options['texttop'] )
821 ? $options['texttop'] : '';
822
823 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
824 ? $options['textaftersummary'] : '';
825
826 $sourceDescriptor = $this->getSourceSection();
827 $descriptor = $sourceDescriptor
828 + $this->getDescriptionSection()
829 + $this->getOptionsSection();
830
831 Hooks::run( 'UploadFormInitDescriptor', array( &$descriptor ) );
832 parent::__construct( $descriptor, $context, 'upload' );
833
834 # Add a link to edit MediaWik:Licenses
835 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
836 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
837 $licensesLink = Linker::linkKnown(
838 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
839 $this->msg( 'licenses-edit' )->escaped(),
840 array(),
841 array( 'action' => 'edit' )
842 );
843 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
844 $this->addFooterText( $editLicenses, 'description' );
845 }
846
847 # Set some form properties
848 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
849 $this->setSubmitName( 'wpUpload' );
850 # Used message keys: 'accesskey-upload', 'tooltip-upload'
851 $this->setSubmitTooltip( 'upload' );
852 $this->setId( 'mw-upload-form' );
853
854 # Build a list of IDs for javascript insertion
855 $this->mSourceIds = array();
856 foreach ( $sourceDescriptor as $field ) {
857 if ( !empty( $field['id'] ) ) {
858 $this->mSourceIds[] = $field['id'];
859 }
860 }
861 }
862
863 /**
864 * Get the descriptor of the fieldset that contains the file source
865 * selection. The section is 'source'
866 *
867 * @return array Descriptor array
868 */
869 protected function getSourceSection() {
870 if ( $this->mSessionKey ) {
871 return array(
872 'SessionKey' => array(
873 'type' => 'hidden',
874 'default' => $this->mSessionKey,
875 ),
876 'SourceType' => array(
877 'type' => 'hidden',
878 'default' => 'Stash',
879 ),
880 );
881 }
882
883 $canUploadByUrl = UploadFromUrl::isEnabled()
884 && ( UploadFromUrl::isAllowed( $this->getUser() ) === true )
885 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
886 $radio = $canUploadByUrl;
887 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
888
889 $descriptor = array();
890 if ( $this->mTextTop ) {
891 $descriptor['UploadFormTextTop'] = array(
892 'type' => 'info',
893 'section' => 'source',
894 'default' => $this->mTextTop,
895 'raw' => true,
896 );
897 }
898
899 $this->mMaxUploadSize['file'] = min(
900 UploadBase::getMaxUploadSize( 'file' ),
901 UploadBase::getMaxPhpUploadSize()
902 );
903
904 $help = $this->msg( 'upload-maxfilesize',
905 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] )
906 )->parse();
907
908 // If the user can also upload by URL, there are 2 different file size limits.
909 // This extra message helps stress which limit corresponds to what.
910 if ( $canUploadByUrl ) {
911 $help .= $this->msg( 'word-separator' )->escaped();
912 $help .= $this->msg( 'upload_source_file' )->parse();
913 }
914
915 $descriptor['UploadFile'] = array(
916 'class' => 'UploadSourceField',
917 'section' => 'source',
918 'type' => 'file',
919 'id' => 'wpUploadFile',
920 'radio-id' => 'wpSourceTypeFile',
921 'label-message' => 'sourcefilename',
922 'upload-type' => 'File',
923 'radio' => &$radio,
924 'help' => $help,
925 'checked' => $selectedSourceType == 'file',
926 );
927
928 if ( $canUploadByUrl ) {
929 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
930 $descriptor['UploadFileURL'] = array(
931 'class' => 'UploadSourceField',
932 'section' => 'source',
933 'id' => 'wpUploadFileURL',
934 'radio-id' => 'wpSourceTypeurl',
935 'label-message' => 'sourceurl',
936 'upload-type' => 'url',
937 'radio' => &$radio,
938 'help' => $this->msg( 'upload-maxfilesize',
939 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] )
940 )->parse() .
941 $this->msg( 'word-separator' )->escaped() .
942 $this->msg( 'upload_source_url' )->parse(),
943 'checked' => $selectedSourceType == 'url',
944 );
945 }
946 Hooks::run( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
947
948 $descriptor['Extensions'] = array(
949 'type' => 'info',
950 'section' => 'source',
951 'default' => $this->getExtensionsMessage(),
952 'raw' => true,
953 );
954
955 return $descriptor;
956 }
957
958 /**
959 * Get the messages indicating which extensions are preferred and prohibitted.
960 *
961 * @return string HTML string containing the message
962 */
963 protected function getExtensionsMessage() {
964 # Print a list of allowed file extensions, if so configured. We ignore
965 # MIME type here, it's incomprehensible to most people and too long.
966 $config = $this->getConfig();
967
968 if ( $config->get( 'CheckFileExtensions' ) ) {
969 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
970 if ( $config->get( 'StrictFileExtensions' ) ) {
971 # Everything not permitted is banned
972 $extensionsList =
973 '<div id="mw-upload-permitted">' .
974 $this->msg( 'upload-permitted' )
975 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
976 ->numParams( count( $fileExtensions ) )
977 ->parseAsBlock() .
978 "</div>\n";
979 } else {
980 # We have to list both preferred and prohibited
981 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
982 $extensionsList =
983 '<div id="mw-upload-preferred">' .
984 $this->msg( 'upload-preferred' )
985 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
986 ->numParams( count( $fileExtensions ) )
987 ->parseAsBlock() .
988 "</div>\n" .
989 '<div id="mw-upload-prohibited">' .
990 $this->msg( 'upload-prohibited' )
991 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
992 ->numParams( count( $fileBlacklist ) )
993 ->parseAsBlock() .
994 "</div>\n";
995 }
996 } else {
997 # Everything is permitted.
998 $extensionsList = '';
999 }
1000
1001 return $extensionsList;
1002 }
1003
1004 /**
1005 * Get the descriptor of the fieldset that contains the file description
1006 * input. The section is 'description'
1007 *
1008 * @return array Descriptor array
1009 */
1010 protected function getDescriptionSection() {
1011 $config = $this->getConfig();
1012 if ( $this->mSessionKey ) {
1013 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1014 try {
1015 $file = $stash->getFile( $this->mSessionKey );
1016 } catch ( Exception $e ) {
1017 $file = null;
1018 }
1019 if ( $file ) {
1020 global $wgContLang;
1021
1022 $mto = $file->transform( array( 'width' => 120 ) );
1023 $this->addHeaderText(
1024 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1025 Html::element( 'img', array(
1026 'src' => $mto->getUrl(),
1027 'class' => 'thumbimage',
1028 ) ) . '</div>', 'description' );
1029 }
1030 }
1031
1032 $descriptor = array(
1033 'DestFile' => array(
1034 'type' => 'text',
1035 'section' => 'description',
1036 'id' => 'wpDestFile',
1037 'label-message' => 'destfilename',
1038 'size' => 60,
1039 'default' => $this->mDestFile,
1040 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1041 'nodata' => strval( $this->mDestFile ) !== '',
1042 ),
1043 'UploadDescription' => array(
1044 'type' => 'textarea',
1045 'section' => 'description',
1046 'id' => 'wpUploadDescription',
1047 'label-message' => $this->mForReUpload
1048 ? 'filereuploadsummary'
1049 : 'fileuploadsummary',
1050 'default' => $this->mComment,
1051 'cols' => $this->getUser()->getIntOption( 'cols' ),
1052 'rows' => 8,
1053 )
1054 );
1055 if ( $this->mTextAfterSummary ) {
1056 $descriptor['UploadFormTextAfterSummary'] = array(
1057 'type' => 'info',
1058 'section' => 'description',
1059 'default' => $this->mTextAfterSummary,
1060 'raw' => true,
1061 );
1062 }
1063
1064 $descriptor += array(
1065 'EditTools' => array(
1066 'type' => 'edittools',
1067 'section' => 'description',
1068 'message' => 'edittools-upload',
1069 )
1070 );
1071
1072 if ( $this->mForReUpload ) {
1073 $descriptor['DestFile']['readonly'] = true;
1074 } else {
1075 $descriptor['License'] = array(
1076 'type' => 'select',
1077 'class' => 'Licenses',
1078 'section' => 'description',
1079 'id' => 'wpLicense',
1080 'label-message' => 'license',
1081 );
1082 }
1083
1084 if ( $config->get( 'UseCopyrightUpload' ) ) {
1085 $descriptor['UploadCopyStatus'] = array(
1086 'type' => 'text',
1087 'section' => 'description',
1088 'id' => 'wpUploadCopyStatus',
1089 'label-message' => 'filestatus',
1090 );
1091 $descriptor['UploadSource'] = array(
1092 'type' => 'text',
1093 'section' => 'description',
1094 'id' => 'wpUploadSource',
1095 'label-message' => 'filesource',
1096 );
1097 }
1098
1099 return $descriptor;
1100 }
1101
1102 /**
1103 * Get the descriptor of the fieldset that contains the upload options,
1104 * such as "watch this file". The section is 'options'
1105 *
1106 * @return array Descriptor array
1107 */
1108 protected function getOptionsSection() {
1109 $user = $this->getUser();
1110 if ( $user->isLoggedIn() ) {
1111 $descriptor = array(
1112 'Watchthis' => array(
1113 'type' => 'check',
1114 'id' => 'wpWatchthis',
1115 'label-message' => 'watchthisupload',
1116 'section' => 'options',
1117 'default' => $this->mWatch,
1118 )
1119 );
1120 }
1121 if ( !$this->mHideIgnoreWarning ) {
1122 $descriptor['IgnoreWarning'] = array(
1123 'type' => 'check',
1124 'id' => 'wpIgnoreWarning',
1125 'label-message' => 'ignorewarnings',
1126 'section' => 'options',
1127 );
1128 }
1129
1130 $descriptor['DestFileWarningAck'] = array(
1131 'type' => 'hidden',
1132 'id' => 'wpDestFileWarningAck',
1133 'default' => $this->mDestWarningAck ? '1' : '',
1134 );
1135
1136 if ( $this->mForReUpload ) {
1137 $descriptor['ForReUpload'] = array(
1138 'type' => 'hidden',
1139 'id' => 'wpForReUpload',
1140 'default' => '1',
1141 );
1142 }
1143
1144 return $descriptor;
1145 }
1146
1147 /**
1148 * Add the upload JS and show the form.
1149 */
1150 public function show() {
1151 $this->addUploadJS();
1152 parent::show();
1153 }
1154
1155 /**
1156 * Add upload JS to the OutputPage
1157 */
1158 protected function addUploadJS() {
1159 $config = $this->getConfig();
1160
1161 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1162 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1163 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1164 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1165
1166 $scriptVars = array(
1167 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1168 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1169 'wgUploadAutoFill' => !$this->mForReUpload &&
1170 // If we received mDestFile from the request, don't autofill
1171 // the wpDestFile textbox
1172 $this->mDestFile === '',
1173 'wgUploadSourceIds' => $this->mSourceIds,
1174 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1175 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1176 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1177 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1178 'wgMaxUploadSize' => $this->mMaxUploadSize,
1179 'wgFileCanRotate' => SpecialUpload::rotationEnabled(),
1180 );
1181
1182 $out = $this->getOutput();
1183 $out->addJsConfigVars( $scriptVars );
1184
1185 $out->addModules( array(
1186 'mediawiki.action.edit', // For <charinsert> support
1187 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1188 ) );
1189 }
1190
1191 /**
1192 * Empty function; submission is handled elsewhere.
1193 *
1194 * @return bool False
1195 */
1196 function trySubmit() {
1197 return false;
1198 }
1199 }
1200
1201 /**
1202 * A form field that contains a radio box in the label
1203 */
1204 class UploadSourceField extends HTMLTextField {
1205
1206 /**
1207 * @param array $cellAttributes
1208 * @return string
1209 */
1210 function getLabelHtml( $cellAttributes = array() ) {
1211 $id = $this->mParams['id'];
1212 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1213
1214 if ( !empty( $this->mParams['radio'] ) ) {
1215 if ( isset( $this->mParams['radio-id'] ) ) {
1216 $radioId = $this->mParams['radio-id'];
1217 } else {
1218 // Old way. For the benefit of extensions that do not define
1219 // the 'radio-id' key.
1220 $radioId = 'wpSourceType' . $this->mParams['upload-type'];
1221 }
1222
1223 $attribs = array(
1224 'name' => 'wpSourceType',
1225 'type' => 'radio',
1226 'id' => $radioId,
1227 'value' => $this->mParams['upload-type'],
1228 );
1229
1230 if ( !empty( $this->mParams['checked'] ) ) {
1231 $attribs['checked'] = 'checked';
1232 }
1233
1234 $label .= Html::element( 'input', $attribs );
1235 }
1236
1237 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1238 }
1239
1240 /**
1241 * @return int
1242 */
1243 function getSize() {
1244 return isset( $this->mParams['size'] )
1245 ? $this->mParams['size']
1246 : 60;
1247 }
1248 }