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