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