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