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