New more slick gallery display
[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 * Construct a warning and a gallery from an array of duplicate files.
677 * @param $dupes array
678 * @return string
679 */
680 public static function getDupeWarning( $dupes ) {
681 if ( !$dupes ) {
682 return '';
683 }
684
685 $gallery = ImageGalleryBase::factory();
686 $gallery->setContext( $this->getContext() );
687 $gallery->setShowBytes( false );
688 foreach ( $dupes as $file ) {
689 $gallery->add( $file->getTitle() );
690 }
691 return '<li>' .
692 wfMessage( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
693 $gallery->toHtml() . "</li>\n";
694 }
695
696 protected function getGroupName() {
697 return 'media';
698 }
699 }
700
701 /**
702 * Sub class of HTMLForm that provides the form section of SpecialUpload
703 */
704 class UploadForm extends HTMLForm {
705 protected $mWatch;
706 protected $mForReUpload;
707 protected $mSessionKey;
708 protected $mHideIgnoreWarning;
709 protected $mDestWarningAck;
710 protected $mDestFile;
711
712 protected $mComment;
713 protected $mTextTop;
714 protected $mTextAfterSummary;
715
716 protected $mSourceIds;
717
718 protected $mMaxFileSize = array();
719
720 protected $mMaxUploadSize = array();
721
722 public function __construct( array $options = array(), IContextSource $context = null ) {
723 $this->mWatch = !empty( $options['watch'] );
724 $this->mForReUpload = !empty( $options['forreupload'] );
725 $this->mSessionKey = isset( $options['sessionkey'] )
726 ? $options['sessionkey'] : '';
727 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
728 $this->mDestWarningAck = !empty( $options['destwarningack'] );
729 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
730
731 $this->mComment = isset( $options['description'] ) ?
732 $options['description'] : '';
733
734 $this->mTextTop = isset( $options['texttop'] )
735 ? $options['texttop'] : '';
736
737 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
738 ? $options['textaftersummary'] : '';
739
740 $sourceDescriptor = $this->getSourceSection();
741 $descriptor = $sourceDescriptor
742 + $this->getDescriptionSection()
743 + $this->getOptionsSection();
744
745 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
746 parent::__construct( $descriptor, $context, 'upload' );
747
748 # Set some form properties
749 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
750 $this->setSubmitName( 'wpUpload' );
751 # Used message keys: 'accesskey-upload', 'tooltip-upload'
752 $this->setSubmitTooltip( 'upload' );
753 $this->setId( 'mw-upload-form' );
754
755 # Build a list of IDs for javascript insertion
756 $this->mSourceIds = array();
757 foreach ( $sourceDescriptor as $field ) {
758 if ( !empty( $field['id'] ) ) {
759 $this->mSourceIds[] = $field['id'];
760 }
761 }
762
763 }
764
765 /**
766 * Get the descriptor of the fieldset that contains the file source
767 * selection. The section is 'source'
768 *
769 * @return Array: descriptor array
770 */
771 protected function getSourceSection() {
772 global $wgCopyUploadsFromSpecialUpload;
773
774 if ( $this->mSessionKey ) {
775 return array(
776 'SessionKey' => array(
777 'type' => 'hidden',
778 'default' => $this->mSessionKey,
779 ),
780 'SourceType' => array(
781 'type' => 'hidden',
782 'default' => 'Stash',
783 ),
784 );
785 }
786
787 $canUploadByUrl = UploadFromUrl::isEnabled()
788 && UploadFromUrl::isAllowed( $this->getUser() )
789 && $wgCopyUploadsFromSpecialUpload;
790 $radio = $canUploadByUrl;
791 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
792
793 $descriptor = array();
794 if ( $this->mTextTop ) {
795 $descriptor['UploadFormTextTop'] = array(
796 'type' => 'info',
797 'section' => 'source',
798 'default' => $this->mTextTop,
799 'raw' => true,
800 );
801 }
802
803 $this->mMaxUploadSize['file'] = UploadBase::getMaxUploadSize( 'file' );
804 # Limit to upload_max_filesize unless we are running under HipHop and
805 # that setting doesn't exist
806 if ( !wfIsHipHop() ) {
807 $this->mMaxUploadSize['file'] = min( $this->mMaxUploadSize['file'],
808 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
809 wfShorthandToInteger( ini_get( 'post_max_size' ) )
810 );
811 }
812
813 $descriptor['UploadFile'] = array(
814 'class' => 'UploadSourceField',
815 'section' => 'source',
816 'type' => 'file',
817 'id' => 'wpUploadFile',
818 'label-message' => 'sourcefilename',
819 'upload-type' => 'File',
820 'radio' => &$radio,
821 'help' => $this->msg( 'upload-maxfilesize',
822 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] ) )
823 ->parse() .
824 $this->msg( 'word-separator' )->escaped() .
825 $this->msg( 'upload_source_file' )->escaped(),
826 'checked' => $selectedSourceType == 'file',
827 );
828
829 if ( $canUploadByUrl ) {
830 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
831 $descriptor['UploadFileURL'] = array(
832 'class' => 'UploadSourceField',
833 'section' => 'source',
834 'id' => 'wpUploadFileURL',
835 'label-message' => 'sourceurl',
836 'upload-type' => 'url',
837 'radio' => &$radio,
838 'help' => $this->msg( 'upload-maxfilesize',
839 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] ) )
840 ->parse() .
841 $this->msg( 'word-separator' )->escaped() .
842 $this->msg( 'upload_source_url' )->escaped(),
843 'checked' => $selectedSourceType == 'url',
844 );
845 }
846 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
847
848 $descriptor['Extensions'] = array(
849 'type' => 'info',
850 'section' => 'source',
851 'default' => $this->getExtensionsMessage(),
852 'raw' => true,
853 );
854 return $descriptor;
855 }
856
857 /**
858 * Get the messages indicating which extensions are preferred and prohibitted.
859 *
860 * @return String: HTML string containing the message
861 */
862 protected function getExtensionsMessage() {
863 # Print a list of allowed file extensions, if so configured. We ignore
864 # MIME type here, it's incomprehensible to most people and too long.
865 global $wgCheckFileExtensions, $wgStrictFileExtensions,
866 $wgFileExtensions, $wgFileBlacklist;
867
868 if ( $wgCheckFileExtensions ) {
869 if ( $wgStrictFileExtensions ) {
870 # Everything not permitted is banned
871 $extensionsList =
872 '<div id="mw-upload-permitted">' .
873 $this->msg( 'upload-permitted', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) )->parseAsBlock() .
874 "</div>\n";
875 } else {
876 # We have to list both preferred and prohibited
877 $extensionsList =
878 '<div id="mw-upload-preferred">' .
879 $this->msg( 'upload-preferred', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) )->parseAsBlock() .
880 "</div>\n" .
881 '<div id="mw-upload-prohibited">' .
882 $this->msg( 'upload-prohibited', $this->getContext()->getLanguage()->commaList( $wgFileBlacklist ) )->parseAsBlock() .
883 "</div>\n";
884 }
885 } else {
886 # Everything is permitted.
887 $extensionsList = '';
888 }
889 return $extensionsList;
890 }
891
892 /**
893 * Get the descriptor of the fieldset that contains the file description
894 * input. The section is 'description'
895 *
896 * @return Array: descriptor array
897 */
898 protected function getDescriptionSection() {
899 if ( $this->mSessionKey ) {
900 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
901 try {
902 $file = $stash->getFile( $this->mSessionKey );
903 } catch ( MWException $e ) {
904 $file = null;
905 }
906 if ( $file ) {
907 global $wgContLang;
908
909 $mto = $file->transform( array( 'width' => 120 ) );
910 $this->addHeaderText(
911 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
912 Html::element( 'img', array(
913 'src' => $mto->getUrl(),
914 'class' => 'thumbimage',
915 ) ) . '</div>', 'description' );
916 }
917 }
918
919 $descriptor = array(
920 'DestFile' => array(
921 'type' => 'text',
922 'section' => 'description',
923 'id' => 'wpDestFile',
924 'label-message' => 'destfilename',
925 'size' => 60,
926 'default' => $this->mDestFile,
927 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
928 'nodata' => strval( $this->mDestFile ) !== '',
929 ),
930 'UploadDescription' => array(
931 'type' => 'textarea',
932 'section' => 'description',
933 'id' => 'wpUploadDescription',
934 'label-message' => $this->mForReUpload
935 ? 'filereuploadsummary'
936 : 'fileuploadsummary',
937 'default' => $this->mComment,
938 'cols' => $this->getUser()->getIntOption( 'cols' ),
939 'rows' => 8,
940 )
941 );
942 if ( $this->mTextAfterSummary ) {
943 $descriptor['UploadFormTextAfterSummary'] = array(
944 'type' => 'info',
945 'section' => 'description',
946 'default' => $this->mTextAfterSummary,
947 'raw' => true,
948 );
949 }
950
951 $descriptor += array(
952 'EditTools' => array(
953 'type' => 'edittools',
954 'section' => 'description',
955 'message' => 'edittools-upload',
956 )
957 );
958
959 if ( $this->mForReUpload ) {
960 $descriptor['DestFile']['readonly'] = true;
961 } else {
962 $descriptor['License'] = array(
963 'type' => 'select',
964 'class' => 'Licenses',
965 'section' => 'description',
966 'id' => 'wpLicense',
967 'label-message' => 'license',
968 );
969 }
970
971 global $wgUseCopyrightUpload;
972 if ( $wgUseCopyrightUpload ) {
973 $descriptor['UploadCopyStatus'] = array(
974 'type' => 'text',
975 'section' => 'description',
976 'id' => 'wpUploadCopyStatus',
977 'label-message' => 'filestatus',
978 );
979 $descriptor['UploadSource'] = array(
980 'type' => 'text',
981 'section' => 'description',
982 'id' => 'wpUploadSource',
983 'label-message' => 'filesource',
984 );
985 }
986
987 return $descriptor;
988 }
989
990 /**
991 * Get the descriptor of the fieldset that contains the upload options,
992 * such as "watch this file". The section is 'options'
993 *
994 * @return Array: descriptor array
995 */
996 protected function getOptionsSection() {
997 $user = $this->getUser();
998 if ( $user->isLoggedIn() ) {
999 $descriptor = array(
1000 'Watchthis' => array(
1001 'type' => 'check',
1002 'id' => 'wpWatchthis',
1003 'label-message' => 'watchthisupload',
1004 'section' => 'options',
1005 'default' => $user->getOption( 'watchcreations' ),
1006 )
1007 );
1008 }
1009 if ( !$this->mHideIgnoreWarning ) {
1010 $descriptor['IgnoreWarning'] = array(
1011 'type' => 'check',
1012 'id' => 'wpIgnoreWarning',
1013 'label-message' => 'ignorewarnings',
1014 'section' => 'options',
1015 );
1016 }
1017
1018 $descriptor['DestFileWarningAck'] = array(
1019 'type' => 'hidden',
1020 'id' => 'wpDestFileWarningAck',
1021 'default' => $this->mDestWarningAck ? '1' : '',
1022 );
1023
1024 if ( $this->mForReUpload ) {
1025 $descriptor['ForReUpload'] = array(
1026 'type' => 'hidden',
1027 'id' => 'wpForReUpload',
1028 'default' => '1',
1029 );
1030 }
1031
1032 return $descriptor;
1033 }
1034
1035 /**
1036 * Add the upload JS and show the form.
1037 */
1038 public function show() {
1039 $this->addUploadJS();
1040 parent::show();
1041 }
1042
1043 /**
1044 * Add upload JS to the OutputPage
1045 */
1046 protected function addUploadJS() {
1047 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1048
1049 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1050 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1051 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1052
1053 $scriptVars = array(
1054 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1055 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1056 'wgUploadAutoFill' => !$this->mForReUpload &&
1057 // If we received mDestFile from the request, don't autofill
1058 // the wpDestFile textbox
1059 $this->mDestFile === '',
1060 'wgUploadSourceIds' => $this->mSourceIds,
1061 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1062 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1063 'wgMaxUploadSize' => $this->mMaxUploadSize,
1064 );
1065
1066 $out = $this->getOutput();
1067 $out->addJsConfigVars( $scriptVars );
1068
1069 $out->addModules( array(
1070 'mediawiki.action.edit', // For <charinsert> support
1071 'mediawiki.legacy.upload', // Old form stuff...
1072 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1073 ) );
1074 }
1075
1076 /**
1077 * Empty function; submission is handled elsewhere.
1078 *
1079 * @return bool false
1080 */
1081 function trySubmit() {
1082 return false;
1083 }
1084
1085 }
1086
1087 /**
1088 * A form field that contains a radio box in the label
1089 */
1090 class UploadSourceField extends HTMLTextField {
1091
1092 /**
1093 * @param $cellAttributes array
1094 * @return string
1095 */
1096 function getLabelHtml( $cellAttributes = array() ) {
1097 $id = $this->mParams['id'];
1098 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1099
1100 if ( !empty( $this->mParams['radio'] ) ) {
1101 $attribs = array(
1102 'name' => 'wpSourceType',
1103 'type' => 'radio',
1104 'id' => $id,
1105 'value' => $this->mParams['upload-type'],
1106 );
1107 if ( !empty( $this->mParams['checked'] ) ) {
1108 $attribs['checked'] = 'checked';
1109 }
1110 $label .= Html::element( 'input', $attribs );
1111 }
1112
1113 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1114 }
1115
1116 /**
1117 * @return int
1118 */
1119 function getSize() {
1120 return isset( $this->mParams['size'] )
1121 ? $this->mParams['size']
1122 : 60;
1123 }
1124 }