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