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