Follow up to r60277: Restore the uploadFormTextTop and uploadFormTextAfterSummary...
[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 = self::getExistsWarning( $args );
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 ( is_bool( $args ) )
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 * consisting of one or more <li> elements if there is a warning.
573 */
574 public static function getExistsWarning( $exists ) {
575 global $wgUser, $wgContLang;
576
577 if ( !$exists )
578 return '';
579
580 $file = $exists['file'];
581 $filename = $file->getTitle()->getPrefixedText();
582 $warning = array();
583
584 $sk = $wgUser->getSkin();
585
586 if( $exists['warning'] == 'exists' ) {
587 // Exact match
588 $warning[] = '<li>' . wfMsgExt( 'fileexists', 'parseinline', $filename ) . '</li>';
589 } elseif( $exists['warning'] == 'page-exists' ) {
590 // Page exists but file does not
591 $warning[] = '<li>' . wfMsgExt( 'filepageexists', 'parseinline', $filename ) . '</li>';
592 } elseif ( $exists['warning'] == 'exists-normalized' ) {
593 $warning[] = '<li>' . wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
594 $exists['normalizedFile']->getTitle()->getPrefixedText() ) . '</li>';
595 } elseif ( $exists['warning'] == 'thumb' ) {
596 // Swapped argument order compared with other messages for backwards compatibility
597 $warning[] = '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
598 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename ) . '</li>';
599 } elseif ( $exists['warning'] == 'thumb-name' ) {
600 // Image w/o '180px-' does not exists, but we do not like these filenames
601 $name = $file->getName();
602 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
603 $warning[] = '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart ) . '</li>';
604 } elseif ( $exists['warning'] == 'bad-prefix' ) {
605 $warning[] = '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] ) . '</li>';
606 } elseif ( $exists['warning'] == 'was-deleted' ) {
607 # If the file existed before and was deleted, warn the user of this
608 $ltitle = SpecialPage::getTitleFor( 'Log' );
609 $llink = $sk->linkKnown(
610 $ltitle,
611 wfMsgHtml( 'deletionlog' ),
612 array(),
613 array(
614 'type' => 'delete',
615 'page' => $filename
616 )
617 );
618 $warning[] = '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
619 }
620
621 return implode( "\n", $warning );
622 }
623
624 /**
625 * Get a list of warnings
626 *
627 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
628 * @return array list of warning messages
629 */
630 public static function ajaxGetExistsWarning( $filename ) {
631 $file = wfFindFile( $filename );
632 if( !$file ) {
633 // Force local file so we have an object to do further checks against
634 // if there isn't an exact match...
635 $file = wfLocalFile( $filename );
636 }
637 $s = '&nbsp;';
638 if ( $file ) {
639 $exists = UploadBase::getExistsWarning( $file );
640 $warning = self::getExistsWarning( $exists );
641 if ( $warning !== '' ) {
642 $s = "<ul>$warning</ul>";
643 }
644 }
645 return $s;
646 }
647
648 /**
649 * Render a preview of a given license for the AJAX preview on upload
650 *
651 * @param string $license
652 * @return string
653 */
654 public static function ajaxGetLicensePreview( $license ) {
655 global $wgParser, $wgUser;
656 $text = '{{' . $license . '}}';
657 $title = Title::makeTitle( NS_FILE, 'Sample.jpg' );
658 $options = ParserOptions::newFromUser( $wgUser );
659
660 // Expand subst: first, then live templates...
661 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
662 $output = $wgParser->parse( $text, $title, $options );
663
664 return $output->getText();
665 }
666
667 /**
668 * Construct a warning and a gallery from an array of duplicate files.
669 */
670 public static function getDupeWarning( $dupes ) {
671 if( $dupes ) {
672 global $wgOut;
673 $msg = "<gallery>";
674 foreach( $dupes as $file ) {
675 $title = $file->getTitle();
676 $msg .= $title->getPrefixedText() .
677 "|" . $title->getText() . "\n";
678 }
679 $msg .= "</gallery>";
680 return "<li>" .
681 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
682 $wgOut->parse( $msg ) .
683 "</li>\n";
684 } else {
685 return '';
686 }
687 }
688
689 }
690
691 /**
692 * Sub class of HTMLForm that provides the form section of SpecialUpload
693 */
694 class UploadForm extends HTMLForm {
695 protected $mWatch;
696 protected $mForReUpload;
697 protected $mSessionKey;
698 protected $mHideIgnoreWarning;
699 protected $mDestWarningAck;
700
701 protected $mTextTop;
702 protected $mTextAfterSummary;
703
704 protected $mSourceIds;
705
706 public function __construct( $options = array() ) {
707 global $wgLang;
708
709 $this->mWatch = !empty( $options['watch'] );
710 $this->mForReUpload = !empty( $options['forreupload'] );
711 $this->mSessionKey = isset( $options['sessionkey'] )
712 ? $options['sessionkey'] : '';
713 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
714 $this->mDestWarningAck = !empty( $options['destwarningack'] );
715
716 $this->mTextTop = $options['texttop'];
717 $this->mTextAfterSummary = $options['textaftersummary'];
718
719 $sourceDescriptor = $this->getSourceSection();
720 $descriptor = $sourceDescriptor
721 + $this->getDescriptionSection()
722 + $this->getOptionsSection();
723
724 wfRunHooks( 'UploadFormInitDescriptor', array( $descriptor ) );
725 parent::__construct( $descriptor, 'upload' );
726
727 # Set some form properties
728 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
729 $this->setSubmitName( 'wpUpload' );
730 $this->setSubmitTooltip( 'upload' );
731 $this->setId( 'mw-upload-form' );
732
733 # Build a list of IDs for javascript insertion
734 $this->mSourceIds = array();
735 foreach ( $sourceDescriptor as $key => $field ) {
736 if ( !empty( $field['id'] ) )
737 $this->mSourceIds[] = $field['id'];
738 }
739
740 }
741
742 /**
743 * Get the descriptor of the fieldset that contains the file source
744 * selection. The section is 'source'
745 *
746 * @return array Descriptor array
747 */
748 protected function getSourceSection() {
749 global $wgLang, $wgUser, $wgRequest;
750
751 if ( $this->mSessionKey ) {
752 return array(
753 'wpSessionKey' => array(
754 'type' => 'hidden',
755 'default' => $this->mSessionKey,
756 ),
757 'wpSourceType' => array(
758 'type' => 'hidden',
759 'default' => 'Stash',
760 ),
761 );
762 }
763
764 $canUploadByUrl = UploadFromUrl::isEnabled() && $wgUser->isAllowed( 'upload_by_url' );
765 $radio = $canUploadByUrl;
766 $selectedSourceType = strtolower( $wgRequest->getText( 'wpSourceType', 'File' ) );
767
768 $descriptor = array();
769 if ( $this->mTextTop ) {
770 $descriptor['UploadFormTextTop'] = array(
771 'type' => 'info',
772 'section' => 'source',
773 'default' => $this->mTextTop,
774 'raw' => true,
775 );
776 }
777
778 $descriptor['UploadFile'] = array(
779 'class' => 'UploadSourceField',
780 'section' => 'source',
781 'type' => 'file',
782 'id' => 'wpUploadFile',
783 'label-message' => 'sourcefilename',
784 'upload-type' => 'File',
785 'radio' => &$radio,
786 'help' => wfMsgExt( 'upload-maxfilesize',
787 array( 'parseinline', 'escapenoentities' ),
788 $wgLang->formatSize(
789 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) )
790 )
791 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
792 'checked' => $selectedSourceType == 'file',
793 );
794 if ( $canUploadByUrl ) {
795 global $wgMaxUploadSize;
796 $descriptor['UploadFileURL'] = array(
797 'class' => 'UploadSourceField',
798 'section' => 'source',
799 'id' => 'wpUploadFileURL',
800 'label-message' => 'sourceurl',
801 'upload-type' => 'url',
802 'radio' => &$radio,
803 'help' => wfMsgExt( 'upload-maxfilesize',
804 array( 'parseinline', 'escapenoentities' ),
805 $wgLang->formatSize( $wgMaxUploadSize )
806 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
807 'checked' => $selectedSourceType == 'url',
808 );
809 }
810 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
811
812 $descriptor['Extensions'] = array(
813 'type' => 'info',
814 'section' => 'source',
815 'default' => $this->getExtensionsMessage(),
816 'raw' => true,
817 );
818 return $descriptor;
819 }
820
821
822 /**
823 * Get the messages indicating which extensions are preferred and prohibitted.
824 *
825 * @return string HTML string containing the message
826 */
827 protected function getExtensionsMessage() {
828 # Print a list of allowed file extensions, if so configured. We ignore
829 # MIME type here, it's incomprehensible to most people and too long.
830 global $wgLang, $wgCheckFileExtensions, $wgStrictFileExtensions,
831 $wgFileExtensions, $wgFileBlacklist;
832
833 $allowedExtensions = '';
834 if( $wgCheckFileExtensions ) {
835 if( $wgStrictFileExtensions ) {
836 # Everything not permitted is banned
837 $extensionsList =
838 '<div id="mw-upload-permitted">' .
839 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
840 "</div>\n";
841 } else {
842 # We have to list both preferred and prohibited
843 $extensionsList =
844 '<div id="mw-upload-preferred">' .
845 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
846 "</div>\n" .
847 '<div id="mw-upload-prohibited">' .
848 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
849 "</div>\n";
850 }
851 } else {
852 # Everything is permitted.
853 $extensionsList = '';
854 }
855 return $extensionsList;
856 }
857
858 /**
859 * Get the descriptor of the fieldset that contains the file description
860 * input. The section is 'description'
861 *
862 * @return array Descriptor array
863 */
864 protected function getDescriptionSection() {
865 global $wgUser, $wgOut;
866
867 $cols = intval( $wgUser->getOption( 'cols' ) );
868 if( $wgUser->getOption( 'editwidth' ) ) {
869 $wgOut->addInlineStyle( '#mw-htmlform-description { width: 100%; }' );
870 }
871
872 $descriptor = array(
873 'DestFile' => array(
874 'type' => 'text',
875 'section' => 'description',
876 'id' => 'wpDestFile',
877 'label-message' => 'destfilename',
878 'size' => 60,
879 ),
880 'UploadDescription' => array(
881 'type' => 'textarea',
882 'section' => 'description',
883 'id' => 'wpUploadDescription',
884 'label-message' => $this->mForReUpload
885 ? 'filereuploadsummary'
886 : 'fileuploadsummary',
887 'cols' => $cols,
888 'rows' => 8,
889 )
890 );
891 if ( $this->mTextAfterSummary ) {
892 $descriptor['UploadFormTextAfterSummary'] = array(
893 'type' => 'info',
894 'section' => 'description',
895 'default' => $this->mTextAfterSummary,
896 'raw' => true,
897 );
898 }
899
900 $descriptor += array(
901 'EditTools' => array(
902 'type' => 'edittools',
903 'section' => 'description',
904 ),
905 'License' => array(
906 'type' => 'select',
907 'class' => 'Licenses',
908 'section' => 'description',
909 'id' => 'wpLicense',
910 'label-message' => 'license',
911 ),
912 );
913 if ( $this->mForReUpload )
914 $descriptor['DestFile']['readonly'] = true;
915
916 global $wgUseCopyrightUpload;
917 if ( $wgUseCopyrightUpload ) {
918 $descriptor['UploadCopyStatus'] = array(
919 'type' => 'text',
920 'section' => 'description',
921 'id' => 'wpUploadCopyStatus',
922 'label-message' => 'filestatus',
923 );
924 $descriptor['UploadSource'] = array(
925 'type' => 'text',
926 'section' => 'description',
927 'id' => 'wpUploadSource',
928 'label-message' => 'filesource',
929 );
930 }
931
932 return $descriptor;
933 }
934
935 /**
936 * Get the descriptor of the fieldset that contains the upload options,
937 * such as "watch this file". The section is 'options'
938 *
939 * @return array Descriptor array
940 */
941 protected function getOptionsSection() {
942 global $wgUser, $wgOut;
943
944 if( $wgUser->isLoggedIn() ) {
945 $descriptor = array(
946 'Watchthis' => array(
947 'type' => 'check',
948 'id' => 'wpWatchthis',
949 'label-message' => 'watchthisupload',
950 'section' => 'options',
951 )
952 );
953 }
954 if( !$this->mHideIgnoreWarning ) {
955 $descriptor['IgnoreWarning'] = array(
956 'type' => 'check',
957 'id' => 'wpIgnoreWarning',
958 'label-message' => 'ignorewarnings',
959 'section' => 'options',
960 );
961 }
962
963 $descriptor['wpDestFileWarningAck'] = array(
964 'type' => 'hidden',
965 'id' => 'wpDestFileWarningAck',
966 'default' => $this->mDestWarningAck ? '1' : '',
967 );
968
969 return $descriptor;
970
971 }
972
973 /**
974 * Add the upload JS and show the form.
975 */
976 public function show() {
977 $this->addUploadJS();
978 parent::show();
979 }
980
981 /**
982 * Add upload JS to $wgOut
983 *
984 * @param bool $autofill Whether or not to autofill the destination
985 * filename text box
986 */
987 protected function addUploadJS( ) {
988 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
989 global $wgOut;
990
991 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
992 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
993
994 $scriptVars = array(
995 'wgAjaxUploadDestCheck' => $wgUseAjax && $wgAjaxUploadDestCheck,
996 'wgAjaxLicensePreview' => $wgUseAjax && $wgAjaxLicensePreview,
997 'wgUploadAutoFill' => !$this->mForReUpload,
998 'wgUploadSourceIds' => $this->mSourceIds,
999 );
1000
1001 $wgOut->addScript( Skin::makeVariablesScript( $scriptVars ) );
1002
1003 // For <charinsert> support
1004 $wgOut->addScriptFile( 'edit.js' );
1005 $wgOut->addScriptFile( 'upload.js' );
1006 }
1007
1008 /**
1009 * Empty function; submission is handled elsewhere.
1010 *
1011 * @return bool false
1012 */
1013 function trySubmit() {
1014 return false;
1015 }
1016
1017 }
1018
1019 /**
1020 * A form field that contains a radio box in the label
1021 */
1022 class UploadSourceField extends HTMLTextField {
1023 function getLabelHtml() {
1024 $id = "wpSourceType{$this->mParams['upload-type']}";
1025 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1026
1027 if ( !empty( $this->mParams['radio'] ) ) {
1028 $attribs = array(
1029 'name' => 'wpSourceType',
1030 'type' => 'radio',
1031 'id' => $id,
1032 'value' => $this->mParams['upload-type'],
1033 );
1034 if ( !empty( $this->mParams['checked'] ) )
1035 $attribs['checked'] = 'checked';
1036 $label .= Html::element( 'input', $attribs );
1037 }
1038
1039 return Html::rawElement( 'td', array( 'class' => 'mw-label' ), $label );
1040 }
1041 function getSize() {
1042 return isset( $this->mParams['size'] )
1043 ? $this->mParams['size']
1044 : 60;
1045 }
1046 }
1047