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