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