Switch some HTMLForms in special pages to OOUI
[lhc/web/wiklou.git] / includes / specials / SpecialUpload.php
1 <?php
2 /**
3 * Implements Special:Upload
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 * @ingroup Upload
23 */
24
25 /**
26 * Form for handling uploads and special page.
27 *
28 * @ingroup SpecialPage
29 * @ingroup Upload
30 */
31 class SpecialUpload extends SpecialPage {
32 /**
33 * Constructor : initialise object
34 * Get data POSTed through the form and assign them to the object
35 * @param WebRequest $request Data posted.
36 */
37 public function __construct( $request = null ) {
38 parent::__construct( 'Upload', 'upload' );
39 }
40
41 /** Misc variables **/
42
43 /** @var WebRequest|FauxRequest The request this form is supposed to handle */
44 public $mRequest;
45 public $mSourceType;
46
47 /** @var UploadBase */
48 public $mUpload;
49
50 /** @var LocalFile */
51 public $mLocalFile;
52 public $mUploadClicked;
53
54 /** User input variables from the "description" section **/
55
56 /** @var string The requested target file name */
57 public $mDesiredDestName;
58 public $mComment;
59 public $mLicense;
60
61 /** User input variables from the root section **/
62
63 public $mIgnoreWarning;
64 public $mWatchthis;
65 public $mCopyrightStatus;
66 public $mCopyrightSource;
67
68 /** Hidden variables **/
69
70 public $mDestWarningAck;
71
72 /** @var bool The user followed an "overwrite this file" link */
73 public $mForReUpload;
74
75 /** @var bool The user clicked "Cancel and return to upload form" button */
76 public $mCancelUpload;
77 public $mTokenOk;
78
79 /** @var bool Subclasses can use this to determine whether a file was uploaded */
80 public $mUploadSuccessful = false;
81
82 /** Text injection points for hooks not using HTMLForm **/
83 public $uploadFormTextTop;
84 public $uploadFormTextAfterSummary;
85
86 /**
87 * Initialize instance variables from request and create an Upload handler
88 */
89 protected function loadRequest() {
90 $this->mRequest = $request = $this->getRequest();
91 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
92 $this->mUpload = UploadBase::createFromRequest( $request );
93 $this->mUploadClicked = $request->wasPosted()
94 && ( $request->getCheck( 'wpUpload' )
95 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
96
97 // Guess the desired name from the filename if not provided
98 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
99 if ( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
100 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
101 }
102 $this->mLicense = $request->getText( 'wpLicense' );
103
104 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
105 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
106 || $request->getCheck( 'wpUploadIgnoreWarning' );
107 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
108 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
109 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
110
111 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
112
113 $commentDefault = '';
114 $commentMsg = wfMessage( 'upload-default-description' )->inContentLanguage();
115 if ( !$this->mForReUpload && !$commentMsg->isDisabled() ) {
116 $commentDefault = $commentMsg->plain();
117 }
118 $this->mComment = $request->getText( 'wpUploadDescription', $commentDefault );
119
120 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
121 || $request->getCheck( 'wpReUpload' ); // b/w compat
122
123 // If it was posted check for the token (no remote POST'ing with user credentials)
124 $token = $request->getVal( 'wpEditToken' );
125 $this->mTokenOk = $this->getUser()->matchEditToken( $token );
126
127 $this->uploadFormTextTop = '';
128 $this->uploadFormTextAfterSummary = '';
129 }
130
131 /**
132 * This page can be shown if uploading is enabled.
133 * Handle permission checking elsewhere in order to be able to show
134 * custom error messages.
135 *
136 * @param User $user
137 * @return bool
138 */
139 public function userCanExecute( User $user ) {
140 return UploadBase::isEnabled() && parent::userCanExecute( $user );
141 }
142
143 /**
144 * Special page entry point
145 * @param string $par
146 * @throws ErrorPageError
147 * @throws Exception
148 * @throws FatalError
149 * @throws MWException
150 * @throws PermissionsError
151 * @throws ReadOnlyError
152 * @throws UserBlockedError
153 */
154 public function execute( $par ) {
155 $this->setHeaders();
156 $this->outputHeader();
157
158 # Check uploading enabled
159 if ( !UploadBase::isEnabled() ) {
160 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
161 }
162
163 $this->addHelpLink( 'Help:Managing files' );
164
165 # Check permissions
166 $user = $this->getUser();
167 $permissionRequired = UploadBase::isAllowed( $user );
168 if ( $permissionRequired !== true ) {
169 throw new PermissionsError( $permissionRequired );
170 }
171
172 # Check blocks
173 if ( $user->isBlocked() ) {
174 throw new UserBlockedError( $user->getBlock() );
175 }
176
177 # Check whether we actually want to allow changing stuff
178 $this->checkReadOnly();
179
180 $this->loadRequest();
181
182 # Unsave the temporary file in case this was a cancelled upload
183 if ( $this->mCancelUpload ) {
184 if ( !$this->unsaveUploadedFile() ) {
185 # Something went wrong, so unsaveUploadedFile showed a warning
186 return;
187 }
188 }
189
190 # Process upload or show a form
191 if (
192 $this->mTokenOk && !$this->mCancelUpload &&
193 ( $this->mUpload && $this->mUploadClicked )
194 ) {
195 $this->processUpload();
196 } else {
197 # Backwards compatibility hook
198 if ( !Hooks::run( 'UploadForm:initial', array( &$this ) ) ) {
199 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
200
201 return;
202 }
203 $this->showUploadForm( $this->getUploadForm() );
204 }
205
206 # Cleanup
207 if ( $this->mUpload ) {
208 $this->mUpload->cleanupTempFile();
209 }
210 }
211
212 /**
213 * Show the main upload form
214 *
215 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
216 */
217 protected function showUploadForm( $form ) {
218 # Add links if file was previously deleted
219 if ( $this->mDesiredDestName ) {
220 $this->showViewDeletedLinks();
221 }
222
223 if ( $form instanceof HTMLForm ) {
224 $form->show();
225 } else {
226 $this->getOutput()->addHTML( $form );
227 }
228 }
229
230 /**
231 * Get an UploadForm instance with title and text properly set.
232 *
233 * @param string $message HTML string to add to the form
234 * @param string $sessionKey Session key in case this is a stashed upload
235 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
236 * @return UploadForm
237 */
238 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
239 # Initialize form
240 $context = new DerivativeContext( $this->getContext() );
241 $context->setTitle( $this->getPageTitle() ); // Remove subpage
242 $form = new UploadForm( array(
243 'watch' => $this->getWatchCheck(),
244 'forreupload' => $this->mForReUpload,
245 'sessionkey' => $sessionKey,
246 'hideignorewarning' => $hideIgnoreWarning,
247 'destwarningack' => (bool)$this->mDestWarningAck,
248
249 'description' => $this->mComment,
250 'texttop' => $this->uploadFormTextTop,
251 'textaftersummary' => $this->uploadFormTextAfterSummary,
252 'destfile' => $this->mDesiredDestName,
253 ), $context );
254
255 # Check the token, but only if necessary
256 if (
257 !$this->mTokenOk && !$this->mCancelUpload &&
258 ( $this->mUpload && $this->mUploadClicked )
259 ) {
260 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
261 }
262
263 # Give a notice if the user is uploading a file that has been deleted or moved
264 # Note that this is independent from the message 'filewasdeleted' that requires JS
265 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
266 $delNotice = ''; // empty by default
267 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
268 LogEventsList::showLogExtract( $delNotice, array( 'delete', 'move' ),
269 $desiredTitleObj,
270 '', array( 'lim' => 10,
271 'conds' => array( "log_action != 'revision'" ),
272 'showIfEmpty' => false,
273 'msgKey' => array( 'upload-recreate-warning' ) )
274 );
275 }
276 $form->addPreText( $delNotice );
277
278 # Add text to form
279 $form->addPreText( '<div id="uploadtext">' .
280 $this->msg( 'uploadtext', array( $this->mDesiredDestName ) )->parseAsBlock() .
281 '</div>' );
282 # Add upload error message
283 $form->addPreText( $message );
284
285 # Add footer to form
286 $uploadFooter = $this->msg( 'uploadfooter' );
287 if ( !$uploadFooter->isDisabled() ) {
288 $form->addPostText( '<div id="mw-upload-footer-message">'
289 . $uploadFooter->parseAsBlock() . "</div>\n" );
290 }
291
292 return $form;
293 }
294
295 /**
296 * Shows the "view X deleted revivions link""
297 */
298 protected function showViewDeletedLinks() {
299 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
300 $user = $this->getUser();
301 // Show a subtitle link to deleted revisions (to sysops et al only)
302 if ( $title instanceof Title ) {
303 $count = $title->isDeleted();
304 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
305 $restorelink = Linker::linkKnown(
306 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
307 $this->msg( 'restorelink' )->numParams( $count )->escaped()
308 );
309 $link = $this->msg( $user->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted' )
310 ->rawParams( $restorelink )->parseAsBlock();
311 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
312 }
313 }
314 }
315
316 /**
317 * Stashes the upload and shows the main upload form.
318 *
319 * Note: only errors that can be handled by changing the name or
320 * description should be redirected here. It should be assumed that the
321 * file itself is sane and has passed UploadBase::verifyFile. This
322 * essentially means that UploadBase::VERIFICATION_ERROR and
323 * UploadBase::EMPTY_FILE should not be passed here.
324 *
325 * @param string $message HTML message to be passed to mainUploadForm
326 */
327 protected function showRecoverableUploadError( $message ) {
328 $sessionKey = $this->mUpload->stashSession();
329 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
330 '<div class="error">' . $message . "</div>\n";
331
332 $form = $this->getUploadForm( $message, $sessionKey );
333 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
334 $this->showUploadForm( $form );
335 }
336
337 /**
338 * Stashes the upload, shows the main form, but adds a "continue anyway button".
339 * Also checks whether there are actually warnings to display.
340 *
341 * @param array $warnings
342 * @return bool True if warnings were displayed, false if there are no
343 * warnings and it should continue processing
344 */
345 protected function showUploadWarning( $warnings ) {
346 # If there are no warnings, or warnings we can ignore, return early.
347 # mDestWarningAck is set when some javascript has shown the warning
348 # to the user. mForReUpload is set when the user clicks the "upload a
349 # new version" link.
350 if ( !$warnings || ( count( $warnings ) == 1
351 && isset( $warnings['exists'] )
352 && ( $this->mDestWarningAck || $this->mForReUpload ) )
353 ) {
354 return false;
355 }
356
357 $sessionKey = $this->mUpload->stashSession();
358
359 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
360 . '<ul class="warning">';
361 foreach ( $warnings as $warning => $args ) {
362 if ( $warning == 'badfilename' ) {
363 $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
364 }
365 if ( $warning == 'exists' ) {
366 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
367 } elseif ( $warning == 'duplicate' ) {
368 $msg = $this->getDupeWarning( $args );
369 } elseif ( $warning == 'duplicate-archive' ) {
370 if ( $args === '' ) {
371 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
372 . "</li>\n";
373 } else {
374 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
375 Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
376 . "</li>\n";
377 }
378 } else {
379 if ( $args === true ) {
380 $args = array();
381 } elseif ( !is_array( $args ) ) {
382 $args = array( $args );
383 }
384 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
385 }
386 $warningHtml .= $msg;
387 }
388 $warningHtml .= "</ul>\n";
389 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
390
391 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
392 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
393 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
394 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
395
396 $this->showUploadForm( $form );
397
398 # Indicate that we showed a form
399 return true;
400 }
401
402 /**
403 * Show the upload form with error message, but do not stash the file.
404 *
405 * @param string $message HTML string
406 */
407 protected function showUploadError( $message ) {
408 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
409 '<div class="error">' . $message . "</div>\n";
410 $this->showUploadForm( $this->getUploadForm( $message ) );
411 }
412
413 /**
414 * Do the upload.
415 * Checks are made in SpecialUpload::execute()
416 */
417 protected function processUpload() {
418 // Fetch the file if required
419 $status = $this->mUpload->fetchFile();
420 if ( !$status->isOK() ) {
421 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
422
423 return;
424 }
425
426 if ( !Hooks::run( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
427 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
428 // This code path is deprecated. If you want to break upload processing
429 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
430 // and UploadBase::verifyFile.
431 // If you use this hook to break uploading, the user will be returned
432 // an empty form with no error message whatsoever.
433 return;
434 }
435
436 // Upload verification
437 $details = $this->mUpload->verifyUpload();
438 if ( $details['status'] != UploadBase::OK ) {
439 $this->processVerificationError( $details );
440
441 return;
442 }
443
444 // Verify permissions for this title
445 $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
446 if ( $permErrors !== true ) {
447 $code = array_shift( $permErrors[0] );
448 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
449
450 return;
451 }
452
453 $this->mLocalFile = $this->mUpload->getLocalFile();
454
455 // Check warnings if necessary
456 if ( !$this->mIgnoreWarning ) {
457 $warnings = $this->mUpload->checkWarnings();
458 if ( $this->showUploadWarning( $warnings ) ) {
459 return;
460 }
461 }
462
463 // Get the page text if this is not a reupload
464 if ( !$this->mForReUpload ) {
465 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
466 $this->mCopyrightStatus, $this->mCopyrightSource, $this->getConfig() );
467 } else {
468 $pageText = false;
469 }
470
471 $status = $this->mUpload->performUpload(
472 $this->mComment,
473 $pageText,
474 $this->mWatchthis,
475 $this->getUser()
476 );
477
478 if ( !$status->isGood() ) {
479 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
480
481 return;
482 }
483
484 // Success, redirect to description page
485 $this->mUploadSuccessful = true;
486 Hooks::run( 'SpecialUploadComplete', array( &$this ) );
487 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
488 }
489
490 /**
491 * Get the initial image page text based on a comment and optional file status information
492 * @param string $comment
493 * @param string $license
494 * @param string $copyStatus
495 * @param string $source
496 * @param Config $config Configuration object to load data from
497 * @return string
498 */
499 public static function getInitialPageText( $comment = '', $license = '',
500 $copyStatus = '', $source = '', Config $config = null
501 ) {
502 if ( $config === null ) {
503 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
504 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
505 }
506
507 $msg = array();
508 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
509 /* These messages are transcluded into the actual text of the description page.
510 * Thus, forcing them as content messages makes the upload to produce an int: template
511 * instead of hardcoding it there in the uploader language.
512 */
513 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
514 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
515 $msg[$msgName] = "{{int:$msgName}}";
516 } else {
517 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
518 }
519 }
520
521 if ( $config->get( 'UseCopyrightUpload' ) ) {
522 $licensetxt = '';
523 if ( $license != '' ) {
524 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
525 }
526 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
527 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
528 "$licensetxt" .
529 '== ' . $msg['filesource'] . " ==\n" . $source;
530 } else {
531 if ( $license != '' ) {
532 $filedesc = $comment == '' ? '' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
533 $pageText = $filedesc .
534 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
535 } else {
536 $pageText = $comment;
537 }
538 }
539
540 return $pageText;
541 }
542
543 /**
544 * See if we should check the 'watch this page' checkbox on the form
545 * based on the user's preferences and whether we're being asked
546 * to create a new file or update an existing one.
547 *
548 * In the case where 'watch edits' is off but 'watch creations' is on,
549 * we'll leave the box unchecked.
550 *
551 * Note that the page target can be changed *on the form*, so our check
552 * state can get out of sync.
553 * @return bool|string
554 */
555 protected function getWatchCheck() {
556 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
557 // Watch all edits!
558 return true;
559 }
560
561 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
562 if ( $desiredTitleObj instanceof Title && $this->getUser()->isWatched( $desiredTitleObj ) ) {
563 // Already watched, don't change that
564 return true;
565 }
566
567 $local = wfLocalFile( $this->mDesiredDestName );
568 if ( $local && $local->exists() ) {
569 // We're uploading a new version of an existing file.
570 // No creation, so don't watch it if we're not already.
571 return false;
572 } else {
573 // New page should get watched if that's our option.
574 return $this->getUser()->getOption( 'watchcreations' );
575 }
576 }
577
578 /**
579 * Provides output to the user for a result of UploadBase::verifyUpload
580 *
581 * @param array $details Result of UploadBase::verifyUpload
582 * @throws MWException
583 */
584 protected function processVerificationError( $details ) {
585 switch ( $details['status'] ) {
586
587 /** Statuses that only require name changing **/
588 case UploadBase::MIN_LENGTH_PARTNAME:
589 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
590 break;
591 case UploadBase::ILLEGAL_FILENAME:
592 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
593 $details['filtered'] )->parse() );
594 break;
595 case UploadBase::FILENAME_TOO_LONG:
596 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
597 break;
598 case UploadBase::FILETYPE_MISSING:
599 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
600 break;
601 case UploadBase::WINDOWS_NONASCII_FILENAME:
602 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
603 break;
604
605 /** Statuses that require reuploading **/
606 case UploadBase::EMPTY_FILE:
607 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
608 break;
609 case UploadBase::FILE_TOO_LARGE:
610 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
611 break;
612 case UploadBase::FILETYPE_BADTYPE:
613 $msg = $this->msg( 'filetype-banned-type' );
614 if ( isset( $details['blacklistedExt'] ) ) {
615 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
616 } else {
617 $msg->params( $details['finalExt'] );
618 }
619 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
620 $msg->params( $this->getLanguage()->commaList( $extensions ),
621 count( $extensions ) );
622
623 // Add PLURAL support for the first parameter. This results
624 // in a bit unlogical parameter sequence, but does not break
625 // old translations
626 if ( isset( $details['blacklistedExt'] ) ) {
627 $msg->params( count( $details['blacklistedExt'] ) );
628 } else {
629 $msg->params( 1 );
630 }
631
632 $this->showUploadError( $msg->parse() );
633 break;
634 case UploadBase::VERIFICATION_ERROR:
635 unset( $details['status'] );
636 $code = array_shift( $details['details'] );
637 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
638 break;
639 case UploadBase::HOOK_ABORTED:
640 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
641 $args = $details['error'];
642 $error = array_shift( $args );
643 } else {
644 $error = $details['error'];
645 $args = null;
646 }
647
648 $this->showUploadError( $this->msg( $error, $args )->parse() );
649 break;
650 default:
651 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
652 }
653 }
654
655 /**
656 * Remove a temporarily kept file stashed by saveTempUploadedFile().
657 *
658 * @return bool Success
659 */
660 protected function unsaveUploadedFile() {
661 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
662 return true;
663 }
664 $success = $this->mUpload->unsaveUploadedFile();
665 if ( !$success ) {
666 $this->getOutput()->showFileDeleteError( $this->mUpload->getTempPath() );
667
668 return false;
669 } else {
670 return true;
671 }
672 }
673
674 /*** Functions for formatting warnings ***/
675
676 /**
677 * Formats a result of UploadBase::getExistsWarning as HTML
678 * This check is static and can be done pre-upload via AJAX
679 *
680 * @param array $exists The result of UploadBase::getExistsWarning
681 * @return string Empty string if there is no warning or an HTML fragment
682 */
683 public static function getExistsWarning( $exists ) {
684 if ( !$exists ) {
685 return '';
686 }
687
688 $file = $exists['file'];
689 $filename = $file->getTitle()->getPrefixedText();
690 $warning = '';
691
692 if ( $exists['warning'] == 'exists' ) {
693 // Exact match
694 $warning = wfMessage( 'fileexists', $filename )->parse();
695 } elseif ( $exists['warning'] == 'page-exists' ) {
696 // Page exists but file does not
697 $warning = wfMessage( 'filepageexists', $filename )->parse();
698 } elseif ( $exists['warning'] == 'exists-normalized' ) {
699 $warning = wfMessage( 'fileexists-extension', $filename,
700 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
701 } elseif ( $exists['warning'] == 'thumb' ) {
702 // Swapped argument order compared with other messages for backwards compatibility
703 $warning = wfMessage( 'fileexists-thumbnail-yes',
704 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
705 } elseif ( $exists['warning'] == 'thumb-name' ) {
706 // Image w/o '180px-' does not exists, but we do not like these filenames
707 $name = $file->getName();
708 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
709 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
710 } elseif ( $exists['warning'] == 'bad-prefix' ) {
711 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
712 } elseif ( $exists['warning'] == 'was-deleted' ) {
713 # If the file existed before and was deleted, warn the user of this
714 $ltitle = SpecialPage::getTitleFor( 'Log' );
715 $llink = Linker::linkKnown(
716 $ltitle,
717 wfMessage( 'deletionlog' )->escaped(),
718 array(),
719 array(
720 'type' => 'delete',
721 'page' => $filename
722 )
723 );
724 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
725 }
726
727 return $warning;
728 }
729
730 /**
731 * Construct a warning and a gallery from an array of duplicate files.
732 * @param array $dupes
733 * @return string
734 */
735 public function getDupeWarning( $dupes ) {
736 if ( !$dupes ) {
737 return '';
738 }
739
740 $gallery = ImageGalleryBase::factory( false, $this->getContext() );
741 $gallery->setShowBytes( false );
742 foreach ( $dupes as $file ) {
743 $gallery->add( $file->getTitle() );
744 }
745
746 return '<li>' .
747 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
748 $gallery->toHTML() . "</li>\n";
749 }
750
751 protected function getGroupName() {
752 return 'media';
753 }
754
755 /**
756 * Should we rotate images in the preview on Special:Upload.
757 *
758 * This controls js: mw.config.get( 'wgFileCanRotate' )
759 *
760 * @todo What about non-BitmapHandler handled files?
761 */
762 public static function rotationEnabled() {
763 $bitmapHandler = new BitmapHandler();
764 return $bitmapHandler->autoRotateEnabled();
765 }
766 }
767
768 /**
769 * Sub class of HTMLForm that provides the form section of SpecialUpload
770 */
771 class UploadForm extends HTMLForm {
772 protected $mWatch;
773 protected $mForReUpload;
774 protected $mSessionKey;
775 protected $mHideIgnoreWarning;
776 protected $mDestWarningAck;
777 protected $mDestFile;
778
779 protected $mComment;
780 protected $mTextTop;
781 protected $mTextAfterSummary;
782
783 protected $mSourceIds;
784
785 protected $mMaxFileSize = array();
786
787 protected $mMaxUploadSize = array();
788
789 public function __construct( array $options = array(), IContextSource $context = null ) {
790 if ( $context instanceof IContextSource ) {
791 $this->setContext( $context );
792 }
793
794 $this->mWatch = !empty( $options['watch'] );
795 $this->mForReUpload = !empty( $options['forreupload'] );
796 $this->mSessionKey = isset( $options['sessionkey'] ) ? $options['sessionkey'] : '';
797 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
798 $this->mDestWarningAck = !empty( $options['destwarningack'] );
799 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
800
801 $this->mComment = isset( $options['description'] ) ?
802 $options['description'] : '';
803
804 $this->mTextTop = isset( $options['texttop'] )
805 ? $options['texttop'] : '';
806
807 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
808 ? $options['textaftersummary'] : '';
809
810 $sourceDescriptor = $this->getSourceSection();
811 $descriptor = $sourceDescriptor
812 + $this->getDescriptionSection()
813 + $this->getOptionsSection();
814
815 Hooks::run( 'UploadFormInitDescriptor', array( &$descriptor ) );
816 parent::__construct( $descriptor, $context, 'upload' );
817
818 # Add a link to edit MediaWik:Licenses
819 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
820 $licensesLink = Linker::linkKnown(
821 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
822 $this->msg( 'licenses-edit' )->escaped(),
823 array(),
824 array( 'action' => 'edit' )
825 );
826 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
827 $this->addFooterText( $editLicenses, 'description' );
828 }
829
830 # Set some form properties
831 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
832 $this->setSubmitName( 'wpUpload' );
833 # Used message keys: 'accesskey-upload', 'tooltip-upload'
834 $this->setSubmitTooltip( 'upload' );
835 $this->setId( 'mw-upload-form' );
836
837 # Build a list of IDs for javascript insertion
838 $this->mSourceIds = array();
839 foreach ( $sourceDescriptor as $field ) {
840 if ( !empty( $field['id'] ) ) {
841 $this->mSourceIds[] = $field['id'];
842 }
843 }
844 }
845
846 /**
847 * Get the descriptor of the fieldset that contains the file source
848 * selection. The section is 'source'
849 *
850 * @return array Descriptor array
851 */
852 protected function getSourceSection() {
853 if ( $this->mSessionKey ) {
854 return array(
855 'SessionKey' => array(
856 'type' => 'hidden',
857 'default' => $this->mSessionKey,
858 ),
859 'SourceType' => array(
860 'type' => 'hidden',
861 'default' => 'Stash',
862 ),
863 );
864 }
865
866 $canUploadByUrl = UploadFromUrl::isEnabled()
867 && ( UploadFromUrl::isAllowed( $this->getUser() ) === true )
868 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
869 $radio = $canUploadByUrl;
870 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
871
872 $descriptor = array();
873 if ( $this->mTextTop ) {
874 $descriptor['UploadFormTextTop'] = array(
875 'type' => 'info',
876 'section' => 'source',
877 'default' => $this->mTextTop,
878 'raw' => true,
879 );
880 }
881
882 $this->mMaxUploadSize['file'] = UploadBase::getMaxUploadSize( 'file' );
883 # Limit to upload_max_filesize unless we are running under HipHop and
884 # that setting doesn't exist
885 if ( !wfIsHHVM() ) {
886 $this->mMaxUploadSize['file'] = min( $this->mMaxUploadSize['file'],
887 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
888 wfShorthandToInteger( ini_get( 'post_max_size' ) )
889 );
890 }
891
892 $help = $this->msg( 'upload-maxfilesize',
893 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] )
894 )->parse();
895
896 // If the user can also upload by URL, there are 2 different file size limits.
897 // This extra message helps stress which limit corresponds to what.
898 if ( $canUploadByUrl ) {
899 $help .= $this->msg( 'word-separator' )->escaped();
900 $help .= $this->msg( 'upload_source_file' )->parse();
901 }
902
903 $descriptor['UploadFile'] = array(
904 'class' => 'UploadSourceField',
905 'section' => 'source',
906 'type' => 'file',
907 'id' => 'wpUploadFile',
908 'radio-id' => 'wpSourceTypeFile',
909 'label-message' => 'sourcefilename',
910 'upload-type' => 'File',
911 'radio' => &$radio,
912 'help' => $help,
913 'checked' => $selectedSourceType == 'file',
914 );
915
916 if ( $canUploadByUrl ) {
917 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
918 $descriptor['UploadFileURL'] = array(
919 'class' => 'UploadSourceField',
920 'section' => 'source',
921 'id' => 'wpUploadFileURL',
922 'radio-id' => 'wpSourceTypeurl',
923 'label-message' => 'sourceurl',
924 'upload-type' => 'url',
925 'radio' => &$radio,
926 'help' => $this->msg( 'upload-maxfilesize',
927 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] )
928 )->parse() .
929 $this->msg( 'word-separator' )->escaped() .
930 $this->msg( 'upload_source_url' )->parse(),
931 'checked' => $selectedSourceType == 'url',
932 );
933 }
934 Hooks::run( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
935
936 $descriptor['Extensions'] = array(
937 'type' => 'info',
938 'section' => 'source',
939 'default' => $this->getExtensionsMessage(),
940 'raw' => true,
941 );
942
943 return $descriptor;
944 }
945
946 /**
947 * Get the messages indicating which extensions are preferred and prohibitted.
948 *
949 * @return string HTML string containing the message
950 */
951 protected function getExtensionsMessage() {
952 # Print a list of allowed file extensions, if so configured. We ignore
953 # MIME type here, it's incomprehensible to most people and too long.
954 $config = $this->getConfig();
955
956 if ( $config->get( 'CheckFileExtensions' ) ) {
957 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
958 if ( $config->get( 'StrictFileExtensions' ) ) {
959 # Everything not permitted is banned
960 $extensionsList =
961 '<div id="mw-upload-permitted">' .
962 $this->msg( 'upload-permitted' )
963 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
964 ->numParams( count( $fileExtensions ) )
965 ->parseAsBlock() .
966 "</div>\n";
967 } else {
968 # We have to list both preferred and prohibited
969 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
970 $extensionsList =
971 '<div id="mw-upload-preferred">' .
972 $this->msg( 'upload-preferred' )
973 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
974 ->numParams( count( $fileExtensions ) )
975 ->parseAsBlock() .
976 "</div>\n" .
977 '<div id="mw-upload-prohibited">' .
978 $this->msg( 'upload-prohibited' )
979 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
980 ->numParams( count( $fileBlacklist ) )
981 ->parseAsBlock() .
982 "</div>\n";
983 }
984 } else {
985 # Everything is permitted.
986 $extensionsList = '';
987 }
988
989 return $extensionsList;
990 }
991
992 /**
993 * Get the descriptor of the fieldset that contains the file description
994 * input. The section is 'description'
995 *
996 * @return array Descriptor array
997 */
998 protected function getDescriptionSection() {
999 $config = $this->getConfig();
1000 if ( $this->mSessionKey ) {
1001 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1002 try {
1003 $file = $stash->getFile( $this->mSessionKey );
1004 } catch ( Exception $e ) {
1005 $file = null;
1006 }
1007 if ( $file ) {
1008 global $wgContLang;
1009
1010 $mto = $file->transform( array( 'width' => 120 ) );
1011 $this->addHeaderText(
1012 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1013 Html::element( 'img', array(
1014 'src' => $mto->getUrl(),
1015 'class' => 'thumbimage',
1016 ) ) . '</div>', 'description' );
1017 }
1018 }
1019
1020 $descriptor = array(
1021 'DestFile' => array(
1022 'type' => 'text',
1023 'section' => 'description',
1024 'id' => 'wpDestFile',
1025 'label-message' => 'destfilename',
1026 'size' => 60,
1027 'default' => $this->mDestFile,
1028 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1029 'nodata' => strval( $this->mDestFile ) !== '',
1030 ),
1031 'UploadDescription' => array(
1032 'type' => 'textarea',
1033 'section' => 'description',
1034 'id' => 'wpUploadDescription',
1035 'label-message' => $this->mForReUpload
1036 ? 'filereuploadsummary'
1037 : 'fileuploadsummary',
1038 'default' => $this->mComment,
1039 'cols' => $this->getUser()->getIntOption( 'cols' ),
1040 'rows' => 8,
1041 )
1042 );
1043 if ( $this->mTextAfterSummary ) {
1044 $descriptor['UploadFormTextAfterSummary'] = array(
1045 'type' => 'info',
1046 'section' => 'description',
1047 'default' => $this->mTextAfterSummary,
1048 'raw' => true,
1049 );
1050 }
1051
1052 $descriptor += array(
1053 'EditTools' => array(
1054 'type' => 'edittools',
1055 'section' => 'description',
1056 'message' => 'edittools-upload',
1057 )
1058 );
1059
1060 if ( $this->mForReUpload ) {
1061 $descriptor['DestFile']['readonly'] = true;
1062 } else {
1063 $descriptor['License'] = array(
1064 'type' => 'select',
1065 'class' => 'Licenses',
1066 'section' => 'description',
1067 'id' => 'wpLicense',
1068 'label-message' => 'license',
1069 );
1070 }
1071
1072 if ( $config->get( 'UseCopyrightUpload' ) ) {
1073 $descriptor['UploadCopyStatus'] = array(
1074 'type' => 'text',
1075 'section' => 'description',
1076 'id' => 'wpUploadCopyStatus',
1077 'label-message' => 'filestatus',
1078 );
1079 $descriptor['UploadSource'] = array(
1080 'type' => 'text',
1081 'section' => 'description',
1082 'id' => 'wpUploadSource',
1083 'label-message' => 'filesource',
1084 );
1085 }
1086
1087 return $descriptor;
1088 }
1089
1090 /**
1091 * Get the descriptor of the fieldset that contains the upload options,
1092 * such as "watch this file". The section is 'options'
1093 *
1094 * @return array Descriptor array
1095 */
1096 protected function getOptionsSection() {
1097 $user = $this->getUser();
1098 if ( $user->isLoggedIn() ) {
1099 $descriptor = array(
1100 'Watchthis' => array(
1101 'type' => 'check',
1102 'id' => 'wpWatchthis',
1103 'label-message' => 'watchthisupload',
1104 'section' => 'options',
1105 'default' => $this->mWatch,
1106 )
1107 );
1108 }
1109 if ( !$this->mHideIgnoreWarning ) {
1110 $descriptor['IgnoreWarning'] = array(
1111 'type' => 'check',
1112 'id' => 'wpIgnoreWarning',
1113 'label-message' => 'ignorewarnings',
1114 'section' => 'options',
1115 );
1116 }
1117
1118 $descriptor['DestFileWarningAck'] = array(
1119 'type' => 'hidden',
1120 'id' => 'wpDestFileWarningAck',
1121 'default' => $this->mDestWarningAck ? '1' : '',
1122 );
1123
1124 if ( $this->mForReUpload ) {
1125 $descriptor['ForReUpload'] = array(
1126 'type' => 'hidden',
1127 'id' => 'wpForReUpload',
1128 'default' => '1',
1129 );
1130 }
1131
1132 return $descriptor;
1133 }
1134
1135 /**
1136 * Add the upload JS and show the form.
1137 */
1138 public function show() {
1139 $this->addUploadJS();
1140 parent::show();
1141 }
1142
1143 /**
1144 * Add upload JS to the OutputPage
1145 */
1146 protected function addUploadJS() {
1147 $config = $this->getConfig();
1148
1149 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1150 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1151 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1152 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1153
1154 $scriptVars = array(
1155 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1156 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1157 'wgUploadAutoFill' => !$this->mForReUpload &&
1158 // If we received mDestFile from the request, don't autofill
1159 // the wpDestFile textbox
1160 $this->mDestFile === '',
1161 'wgUploadSourceIds' => $this->mSourceIds,
1162 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1163 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1164 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1165 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1166 'wgMaxUploadSize' => $this->mMaxUploadSize,
1167 'wgFileCanRotate' => SpecialUpload::rotationEnabled(),
1168 );
1169
1170 $out = $this->getOutput();
1171 $out->addJsConfigVars( $scriptVars );
1172
1173 $out->addModules( array(
1174 'mediawiki.action.edit', // For <charinsert> support
1175 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1176 ) );
1177 }
1178
1179 /**
1180 * Empty function; submission is handled elsewhere.
1181 *
1182 * @return bool False
1183 */
1184 function trySubmit() {
1185 return false;
1186 }
1187 }
1188
1189 /**
1190 * A form field that contains a radio box in the label
1191 */
1192 class UploadSourceField extends HTMLTextField {
1193
1194 /**
1195 * @param array $cellAttributes
1196 * @return string
1197 */
1198 function getLabelHtml( $cellAttributes = array() ) {
1199 $id = $this->mParams['id'];
1200 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1201
1202 if ( !empty( $this->mParams['radio'] ) ) {
1203 if ( isset( $this->mParams['radio-id'] ) ) {
1204 $radioId = $this->mParams['radio-id'];
1205 } else {
1206 // Old way. For the benefit of extensions that do not define
1207 // the 'radio-id' key.
1208 $radioId = 'wpSourceType' . $this->mParams['upload-type'];
1209 }
1210
1211 $attribs = array(
1212 'name' => 'wpSourceType',
1213 'type' => 'radio',
1214 'id' => $radioId,
1215 'value' => $this->mParams['upload-type'],
1216 );
1217
1218 if ( !empty( $this->mParams['checked'] ) ) {
1219 $attribs['checked'] = 'checked';
1220 }
1221
1222 $label .= Html::element( 'input', $attribs );
1223 }
1224
1225 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1226 }
1227
1228 /**
1229 * @return int
1230 */
1231 function getSize() {
1232 return isset( $this->mParams['size'] )
1233 ? $this->mParams['size']
1234 : 60;
1235 }
1236 }