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