Merge "Resolve bug #18704 ("Add an unique CSS class or ID to the tagfilter table...
[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->getBlock() );
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 $this->processUpload();
182 } else {
183 # Backwards compatibility hook
184 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
185 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
186 return;
187 }
188 $this->showUploadForm( $this->getUploadForm() );
189 }
190
191 # Cleanup
192 if ( $this->mUpload ) {
193 $this->mUpload->cleanupTempFile();
194 }
195 }
196
197 /**
198 * Show the main upload form
199 *
200 * @param $form Mixed: an HTMLForm instance or HTML string to show
201 */
202 protected function showUploadForm( $form ) {
203 # Add links if file was previously deleted
204 if ( $this->mDesiredDestName ) {
205 $this->showViewDeletedLinks();
206 }
207
208 if ( $form instanceof HTMLForm ) {
209 $form->show();
210 } else {
211 $this->getOutput()->addHTML( $form );
212 }
213
214 }
215
216 /**
217 * Get an UploadForm instance with title and text properly set.
218 *
219 * @param $message String: HTML string to add to the form
220 * @param $sessionKey String: session key in case this is a stashed upload
221 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
222 * @return UploadForm
223 */
224 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
225 # Initialize form
226 $form = new UploadForm( array(
227 'watch' => $this->getWatchCheck(),
228 'forreupload' => $this->mForReUpload,
229 'sessionkey' => $sessionKey,
230 'hideignorewarning' => $hideIgnoreWarning,
231 'destwarningack' => (bool)$this->mDestWarningAck,
232
233 'description' => $this->mComment,
234 'texttop' => $this->uploadFormTextTop,
235 'textaftersummary' => $this->uploadFormTextAfterSummary,
236 'destfile' => $this->mDesiredDestName,
237 ), $this->getContext() );
238 $form->setTitle( $this->getTitle() );
239
240 # Check the token, but only if necessary
241 if(
242 !$this->mTokenOk && !$this->mCancelUpload &&
243 ( $this->mUpload && $this->mUploadClicked )
244 ) {
245 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
246 }
247
248 # Give a notice if the user is uploading a file that has been deleted or moved
249 # Note that this is independent from the message 'filewasdeleted' that requires JS
250 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
251 $delNotice = ''; // empty by default
252 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
253 LogEventsList::showLogExtract( $delNotice, array( 'delete', 'move' ),
254 $desiredTitleObj,
255 '', array( 'lim' => 10,
256 'conds' => array( "log_action != 'revision'" ),
257 'showIfEmpty' => false,
258 'msgKey' => array( 'upload-recreate-warning' ) )
259 );
260 }
261 $form->addPreText( $delNotice );
262
263 # Add text to form
264 $form->addPreText( '<div id="uploadtext">' .
265 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName ) ) .
266 '</div>' );
267 # Add upload error message
268 $form->addPreText( $message );
269
270 # Add footer to form
271 $uploadFooter = wfMessage( 'uploadfooter' );
272 if ( !$uploadFooter->isDisabled() ) {
273 $form->addPostText( '<div id="mw-upload-footer-message">'
274 . $this->getOutput()->parse( $uploadFooter->plain() ) . "</div>\n" );
275 }
276
277 return $form;
278 }
279
280 /**
281 * Shows the "view X deleted revivions link""
282 */
283 protected function showViewDeletedLinks() {
284 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
285 $user = $this->getUser();
286 // Show a subtitle link to deleted revisions (to sysops et al only)
287 if( $title instanceof Title ) {
288 $count = $title->isDeleted();
289 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
290 $link = wfMsgExt(
291 $user->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
292 array( 'parse', 'replaceafter' ),
293 Linker::linkKnown(
294 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
295 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
296 )
297 );
298 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
299 }
300 }
301 }
302
303 /**
304 * Stashes the upload and shows the main upload form.
305 *
306 * Note: only errors that can be handled by changing the name or
307 * description should be redirected here. It should be assumed that the
308 * file itself is sane and has passed UploadBase::verifyFile. This
309 * essentially means that UploadBase::VERIFICATION_ERROR and
310 * UploadBase::EMPTY_FILE should not be passed here.
311 *
312 * @param $message String: HTML message to be passed to mainUploadForm
313 */
314 protected function showRecoverableUploadError( $message ) {
315 $sessionKey = $this->mUpload->stashSession();
316 $message = '<h2>' . wfMsgHtml( 'uploaderror' ) . "</h2>\n" .
317 '<div class="error">' . $message . "</div>\n";
318
319 $form = $this->getUploadForm( $message, $sessionKey );
320 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
321 $this->showUploadForm( $form );
322 }
323 /**
324 * Stashes the upload, shows the main form, but adds an "continue anyway button".
325 * Also checks whether there are actually warnings to display.
326 *
327 * @param $warnings Array
328 * @return boolean true if warnings were displayed, false if there are no
329 * warnings and the should continue processing like there was no warning
330 */
331 protected function showUploadWarning( $warnings ) {
332 # If there are no warnings, or warnings we can ignore, return early.
333 # mDestWarningAck is set when some javascript has shown the warning
334 # to the user. mForReUpload is set when the user clicks the "upload a
335 # new version" link.
336 if ( !$warnings || ( count( $warnings ) == 1 &&
337 isset( $warnings['exists'] ) &&
338 ( $this->mDestWarningAck || $this->mForReUpload ) ) )
339 {
340 return false;
341 }
342
343 $sessionKey = $this->mUpload->stashSession();
344
345 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
346 . '<ul class="warning">';
347 foreach( $warnings as $warning => $args ) {
348 if( $warning == 'exists' ) {
349 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
350 } elseif( $warning == 'duplicate' ) {
351 $msg = self::getDupeWarning( $args );
352 } elseif( $warning == 'duplicate-archive' ) {
353 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
354 array( Title::makeTitle( NS_FILE, $args )->getPrefixedText() ) )
355 . "</li>\n";
356 } else {
357 if ( $args === true ) {
358 $args = array();
359 } elseif ( !is_array( $args ) ) {
360 $args = array( $args );
361 }
362 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
363 }
364 $warningHtml .= $msg;
365 }
366 $warningHtml .= "</ul>\n";
367 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
368
369 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
370 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
371 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
372 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
373
374 $this->showUploadForm( $form );
375
376 # Indicate that we showed a form
377 return true;
378 }
379
380 /**
381 * Show the upload form with error message, but do not stash the file.
382 *
383 * @param $message string HTML string
384 */
385 protected function showUploadError( $message ) {
386 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
387 '<div class="error">' . $message . "</div>\n";
388 $this->showUploadForm( $this->getUploadForm( $message ) );
389 }
390
391 /**
392 * Do the upload.
393 * Checks are made in SpecialUpload::execute()
394 */
395 protected function processUpload() {
396 // Fetch the file if required
397 $status = $this->mUpload->fetchFile();
398 if( !$status->isOK() ) {
399 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
400 return;
401 }
402
403 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
404 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
405 // This code path is deprecated. If you want to break upload processing
406 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
407 // and UploadBase::verifyFile.
408 // If you use this hook to break uploading, the user will be returned
409 // an empty form with no error message whatsoever.
410 return;
411 }
412
413 // Upload verification
414 $details = $this->mUpload->verifyUpload();
415 if ( $details['status'] != UploadBase::OK ) {
416 $this->processVerificationError( $details );
417 return;
418 }
419
420 // Verify permissions for this title
421 $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
422 if( $permErrors !== true ) {
423 $code = array_shift( $permErrors[0] );
424 $this->showRecoverableUploadError( wfMsgExt( $code,
425 'parseinline', $permErrors[0] ) );
426 return;
427 }
428
429 $this->mLocalFile = $this->mUpload->getLocalFile();
430
431 // Check warnings if necessary
432 if( !$this->mIgnoreWarning ) {
433 $warnings = $this->mUpload->checkWarnings();
434 if( $this->showUploadWarning( $warnings ) ) {
435 return;
436 }
437 }
438
439 // Get the page text if this is not a reupload
440 if( !$this->mForReUpload ) {
441 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
442 $this->mCopyrightStatus, $this->mCopyrightSource );
443 } else {
444 $pageText = false;
445 }
446 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $this->getUser() );
447 if ( !$status->isGood() ) {
448 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
449 return;
450 }
451
452 // Success, redirect to description page
453 $this->mUploadSuccessful = true;
454 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
455 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
456 }
457
458 /**
459 * Get the initial image page text based on a comment and optional file status information
460 * @param $comment string
461 * @param $license string
462 * @param $copyStatus string
463 * @param $source string
464 * @return string
465 */
466 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
467 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
468 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
469
470 $msg = array();
471 /* These messages are transcluded into the actual text of the description page.
472 * Thus, forcing them as content messages makes the upload to produce an int: template
473 * instead of hardcoding it there in the uploader language.
474 */
475 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
476 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
477 $msg[$msgName] = "{{int:$msgName}}";
478 } else {
479 $msg[$msgName] = wfMsgForContent( $msgName );
480 }
481 }
482
483 if ( $wgUseCopyrightUpload ) {
484 $licensetxt = '';
485 if ( $license != '' ) {
486 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
487 }
488 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
489 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
490 "$licensetxt" .
491 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
492 } else {
493 if ( $license != '' ) {
494 $filedesc = $comment == '' ? '' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
495 $pageText = $filedesc .
496 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
497 } else {
498 $pageText = $comment;
499 }
500 }
501 return $pageText;
502 }
503
504 /**
505 * See if we should check the 'watch this page' checkbox on the form
506 * based on the user's preferences and whether we're being asked
507 * to create a new file or update an existing one.
508 *
509 * In the case where 'watch edits' is off but 'watch creations' is on,
510 * we'll leave the box unchecked.
511 *
512 * Note that the page target can be changed *on the form*, so our check
513 * state can get out of sync.
514 * @return Bool|String
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->getLanguage()->commaList( $details['blacklistedExt'] ) );
575 } else {
576 $msg->params( $details['finalExt'] );
577 }
578 $msg->params( $this->getLanguage()->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 * @param $dupes array
714 * @return string
715 */
716 public static function getDupeWarning( $dupes ) {
717 global $wgOut;
718 if( $dupes ) {
719 $msg = '<gallery>';
720 foreach( $dupes as $file ) {
721 $title = $file->getTitle();
722 $msg .= $title->getPrefixedText() .
723 '|' . $title->getText() . "\n";
724 }
725 $msg .= '</gallery>';
726 return '<li>' .
727 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
728 $wgOut->parse( $msg ) .
729 "</li>\n";
730 } else {
731 return '';
732 }
733 }
734
735 }
736
737 /**
738 * Sub class of HTMLForm that provides the form section of SpecialUpload
739 */
740 class UploadForm extends HTMLForm {
741 protected $mWatch;
742 protected $mForReUpload;
743 protected $mSessionKey;
744 protected $mHideIgnoreWarning;
745 protected $mDestWarningAck;
746 protected $mDestFile;
747
748 protected $mComment;
749 protected $mTextTop;
750 protected $mTextAfterSummary;
751
752 protected $mSourceIds;
753
754 protected $mMaxFileSize = array();
755
756 protected $mMaxUploadSize = array();
757
758 public function __construct( array $options = array(), IContextSource $context = null ) {
759 $this->mWatch = !empty( $options['watch'] );
760 $this->mForReUpload = !empty( $options['forreupload'] );
761 $this->mSessionKey = isset( $options['sessionkey'] )
762 ? $options['sessionkey'] : '';
763 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
764 $this->mDestWarningAck = !empty( $options['destwarningack'] );
765 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
766
767 $this->mComment = isset( $options['description'] ) ?
768 $options['description'] : '';
769
770 $this->mTextTop = isset( $options['texttop'] )
771 ? $options['texttop'] : '';
772
773 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
774 ? $options['textaftersummary'] : '';
775
776 $sourceDescriptor = $this->getSourceSection();
777 $descriptor = $sourceDescriptor
778 + $this->getDescriptionSection()
779 + $this->getOptionsSection();
780
781 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
782 parent::__construct( $descriptor, $context, 'upload' );
783
784 # Set some form properties
785 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
786 $this->setSubmitName( 'wpUpload' );
787 # Used message keys: 'accesskey-upload', 'tooltip-upload'
788 $this->setSubmitTooltip( 'upload' );
789 $this->setId( 'mw-upload-form' );
790
791 # Build a list of IDs for javascript insertion
792 $this->mSourceIds = array();
793 foreach ( $sourceDescriptor as $field ) {
794 if ( !empty( $field['id'] ) ) {
795 $this->mSourceIds[] = $field['id'];
796 }
797 }
798
799 }
800
801 /**
802 * Get the descriptor of the fieldset that contains the file source
803 * selection. The section is 'source'
804 *
805 * @return Array: descriptor array
806 */
807 protected function getSourceSection() {
808 if ( $this->mSessionKey ) {
809 return array(
810 'SessionKey' => array(
811 'type' => 'hidden',
812 'default' => $this->mSessionKey,
813 ),
814 'SourceType' => array(
815 'type' => 'hidden',
816 'default' => 'Stash',
817 ),
818 );
819 }
820
821 $canUploadByUrl = UploadFromUrl::isEnabled() && UploadFromUrl::isAllowed( $this->getUser() );
822 $radio = $canUploadByUrl;
823 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
824
825 $descriptor = array();
826 if ( $this->mTextTop ) {
827 $descriptor['UploadFormTextTop'] = array(
828 'type' => 'info',
829 'section' => 'source',
830 'default' => $this->mTextTop,
831 'raw' => true,
832 );
833 }
834
835 $this->mMaxUploadSize['file'] = UploadBase::getMaxUploadSize( 'file' );
836 # Limit to upload_max_filesize unless we are running under HipHop and
837 # that setting doesn't exist
838 if ( !wfIsHipHop() ) {
839 $this->mMaxUploadSize['file'] = min( $this->mMaxUploadSize['file'],
840 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ) );
841 }
842
843 $descriptor['UploadFile'] = array(
844 'class' => 'UploadSourceField',
845 'section' => 'source',
846 'type' => 'file',
847 'id' => 'wpUploadFile',
848 'label-message' => 'sourcefilename',
849 'upload-type' => 'File',
850 'radio' => &$radio,
851 'help' => wfMsgExt( 'upload-maxfilesize',
852 array( 'parseinline', 'escapenoentities' ),
853 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] )
854 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
855 'checked' => $selectedSourceType == 'file',
856 );
857 if ( $canUploadByUrl ) {
858 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
859 $descriptor['UploadFileURL'] = array(
860 'class' => 'UploadSourceField',
861 'section' => 'source',
862 'id' => 'wpUploadFileURL',
863 'label-message' => 'sourceurl',
864 'upload-type' => 'url',
865 'radio' => &$radio,
866 'help' => wfMsgExt( 'upload-maxfilesize',
867 array( 'parseinline', 'escapenoentities' ),
868 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] )
869 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
870 'checked' => $selectedSourceType == 'url',
871 );
872 }
873 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
874
875 $descriptor['Extensions'] = array(
876 'type' => 'info',
877 'section' => 'source',
878 'default' => $this->getExtensionsMessage(),
879 'raw' => true,
880 );
881 return $descriptor;
882 }
883
884 /**
885 * Get the messages indicating which extensions are preferred and prohibitted.
886 *
887 * @return String: HTML string containing the message
888 */
889 protected function getExtensionsMessage() {
890 # Print a list of allowed file extensions, if so configured. We ignore
891 # MIME type here, it's incomprehensible to most people and too long.
892 global $wgCheckFileExtensions, $wgStrictFileExtensions,
893 $wgFileExtensions, $wgFileBlacklist;
894
895 if( $wgCheckFileExtensions ) {
896 if( $wgStrictFileExtensions ) {
897 # Everything not permitted is banned
898 $extensionsList =
899 '<div id="mw-upload-permitted">' .
900 wfMsgExt( 'upload-permitted', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) ) .
901 "</div>\n";
902 } else {
903 # We have to list both preferred and prohibited
904 $extensionsList =
905 '<div id="mw-upload-preferred">' .
906 wfMsgExt( 'upload-preferred', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) ) .
907 "</div>\n" .
908 '<div id="mw-upload-prohibited">' .
909 wfMsgExt( 'upload-prohibited', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileBlacklist ) ) .
910 "</div>\n";
911 }
912 } else {
913 # Everything is permitted.
914 $extensionsList = '';
915 }
916 return $extensionsList;
917 }
918
919 /**
920 * Get the descriptor of the fieldset that contains the file description
921 * input. The section is 'description'
922 *
923 * @return Array: descriptor array
924 */
925 protected function getDescriptionSection() {
926 if ( $this->mSessionKey ) {
927 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
928 try {
929 $file = $stash->getFile( $this->mSessionKey );
930 } catch ( MWException $e ) {
931 $file = null;
932 }
933 if ( $file ) {
934 global $wgContLang;
935
936 $mto = $file->transform( array( 'width' => 120 ) );
937 $this->addHeaderText(
938 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
939 Html::element( 'img', array(
940 'src' => $mto->getUrl(),
941 'class' => 'thumbimage',
942 ) ) . '</div>', 'description' );
943 }
944 }
945
946 $descriptor = array(
947 'DestFile' => array(
948 'type' => 'text',
949 'section' => 'description',
950 'id' => 'wpDestFile',
951 'label-message' => 'destfilename',
952 'size' => 60,
953 'default' => $this->mDestFile,
954 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
955 'nodata' => strval( $this->mDestFile ) !== '',
956 ),
957 'UploadDescription' => array(
958 'type' => 'textarea',
959 'section' => 'description',
960 'id' => 'wpUploadDescription',
961 'label-message' => $this->mForReUpload
962 ? 'filereuploadsummary'
963 : 'fileuploadsummary',
964 'default' => $this->mComment,
965 'cols' => intval( $this->getUser()->getOption( 'cols' ) ),
966 'rows' => 8,
967 )
968 );
969 if ( $this->mTextAfterSummary ) {
970 $descriptor['UploadFormTextAfterSummary'] = array(
971 'type' => 'info',
972 'section' => 'description',
973 'default' => $this->mTextAfterSummary,
974 'raw' => true,
975 );
976 }
977
978 $descriptor += array(
979 'EditTools' => array(
980 'type' => 'edittools',
981 'section' => 'description',
982 'message' => 'edittools-upload',
983 )
984 );
985
986 if ( $this->mForReUpload ) {
987 $descriptor['DestFile']['readonly'] = true;
988 } else {
989 $descriptor['License'] = array(
990 'type' => 'select',
991 'class' => 'Licenses',
992 'section' => 'description',
993 'id' => 'wpLicense',
994 'label-message' => 'license',
995 );
996 }
997
998 global $wgUseCopyrightUpload;
999 if ( $wgUseCopyrightUpload ) {
1000 $descriptor['UploadCopyStatus'] = array(
1001 'type' => 'text',
1002 'section' => 'description',
1003 'id' => 'wpUploadCopyStatus',
1004 'label-message' => 'filestatus',
1005 );
1006 $descriptor['UploadSource'] = array(
1007 'type' => 'text',
1008 'section' => 'description',
1009 'id' => 'wpUploadSource',
1010 'label-message' => 'filesource',
1011 );
1012 }
1013
1014 return $descriptor;
1015 }
1016
1017 /**
1018 * Get the descriptor of the fieldset that contains the upload options,
1019 * such as "watch this file". The section is 'options'
1020 *
1021 * @return Array: descriptor array
1022 */
1023 protected function getOptionsSection() {
1024 $user = $this->getUser();
1025 if ( $user->isLoggedIn() ) {
1026 $descriptor = array(
1027 'Watchthis' => array(
1028 'type' => 'check',
1029 'id' => 'wpWatchthis',
1030 'label-message' => 'watchthisupload',
1031 'section' => 'options',
1032 'default' => $user->getOption( 'watchcreations' ),
1033 )
1034 );
1035 }
1036 if ( !$this->mHideIgnoreWarning ) {
1037 $descriptor['IgnoreWarning'] = array(
1038 'type' => 'check',
1039 'id' => 'wpIgnoreWarning',
1040 'label-message' => 'ignorewarnings',
1041 'section' => 'options',
1042 );
1043 }
1044
1045 $descriptor['DestFileWarningAck'] = array(
1046 'type' => 'hidden',
1047 'id' => 'wpDestFileWarningAck',
1048 'default' => $this->mDestWarningAck ? '1' : '',
1049 );
1050
1051 if ( $this->mForReUpload ) {
1052 $descriptor['ForReUpload'] = array(
1053 'type' => 'hidden',
1054 'id' => 'wpForReUpload',
1055 'default' => '1',
1056 );
1057 }
1058
1059 return $descriptor;
1060 }
1061
1062 /**
1063 * Add the upload JS and show the form.
1064 */
1065 public function show() {
1066 $this->addUploadJS();
1067 parent::show();
1068 }
1069
1070 /**
1071 * Add upload JS to the OutputPage
1072 */
1073 protected function addUploadJS() {
1074 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1075
1076 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1077 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1078 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1079
1080 $scriptVars = array(
1081 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1082 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1083 'wgUploadAutoFill' => !$this->mForReUpload &&
1084 // If we received mDestFile from the request, don't autofill
1085 // the wpDestFile textbox
1086 $this->mDestFile === '',
1087 'wgUploadSourceIds' => $this->mSourceIds,
1088 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1089 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1090 'wgMaxUploadSize' => $this->mMaxUploadSize,
1091 );
1092
1093 $out = $this->getOutput();
1094 $out->addJsConfigVars( $scriptVars );
1095
1096
1097 $out->addModules( array(
1098 'mediawiki.action.edit', // For <charinsert> support
1099 'mediawiki.legacy.upload', // Old form stuff...
1100 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1101 ) );
1102 }
1103
1104 /**
1105 * Empty function; submission is handled elsewhere.
1106 *
1107 * @return bool false
1108 */
1109 function trySubmit() {
1110 return false;
1111 }
1112
1113 }
1114
1115 /**
1116 * A form field that contains a radio box in the label
1117 */
1118 class UploadSourceField extends HTMLTextField {
1119
1120 /**
1121 * @param $cellAttributes array
1122 * @return string
1123 */
1124 function getLabelHtml( $cellAttributes = array() ) {
1125 $id = "wpSourceType{$this->mParams['upload-type']}";
1126 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1127
1128 if ( !empty( $this->mParams['radio'] ) ) {
1129 $attribs = array(
1130 'name' => 'wpSourceType',
1131 'type' => 'radio',
1132 'id' => $id,
1133 'value' => $this->mParams['upload-type'],
1134 );
1135 if ( !empty( $this->mParams['checked'] ) ) {
1136 $attribs['checked'] = 'checked';
1137 }
1138 $label .= Html::element( 'input', $attribs );
1139 }
1140
1141 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1142 }
1143
1144 /**
1145 * @return int
1146 */
1147 function getSize() {
1148 return isset( $this->mParams['size'] )
1149 ? $this->mParams['size']
1150 : 60;
1151 }
1152 }
1153