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