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