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