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