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