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