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