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