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