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