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