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