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