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