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