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