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