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