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