Merge "Store boolean values as integers with SQLite"
[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 $msg->params( $this->getLanguage()->commaList( $wgFileExtensions ),
574 count( $wgFileExtensions ) );
575
576 // Add PLURAL support for the first parameter. This results
577 // in a bit unlogical parameter sequence, but does not break
578 // old translations
579 if ( isset( $details['blacklistedExt'] ) ) {
580 $msg->params( count( $details['blacklistedExt'] ) );
581 } else {
582 $msg->params( 1 );
583 }
584
585 $this->showUploadError( $msg->parse() );
586 break;
587 case UploadBase::VERIFICATION_ERROR:
588 unset( $details['status'] );
589 $code = array_shift( $details['details'] );
590 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
591 break;
592 case UploadBase::HOOK_ABORTED:
593 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
594 $args = $details['error'];
595 $error = array_shift( $args );
596 } else {
597 $error = $details['error'];
598 $args = null;
599 }
600
601 $this->showUploadError( $this->msg( $error, $args )->parse() );
602 break;
603 default:
604 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
605 }
606 }
607
608 /**
609 * Remove a temporarily kept file stashed by saveTempUploadedFile().
610 *
611 * @return Boolean: success
612 */
613 protected function unsaveUploadedFile() {
614 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
615 return true;
616 }
617 $success = $this->mUpload->unsaveUploadedFile();
618 if ( !$success ) {
619 $this->getOutput()->showFileDeleteError( $this->mUpload->getTempPath() );
620 return false;
621 } else {
622 return true;
623 }
624 }
625
626 /*** Functions for formatting warnings ***/
627
628 /**
629 * Formats a result of UploadBase::getExistsWarning as HTML
630 * This check is static and can be done pre-upload via AJAX
631 *
632 * @param array $exists the result of UploadBase::getExistsWarning
633 * @return String: empty string if there is no warning or an HTML fragment
634 */
635 public static function getExistsWarning( $exists ) {
636 if ( !$exists ) {
637 return '';
638 }
639
640 $file = $exists['file'];
641 $filename = $file->getTitle()->getPrefixedText();
642 $warning = '';
643
644 if ( $exists['warning'] == 'exists' ) {
645 // Exact match
646 $warning = wfMessage( 'fileexists', $filename )->parse();
647 } elseif ( $exists['warning'] == 'page-exists' ) {
648 // Page exists but file does not
649 $warning = wfMessage( 'filepageexists', $filename )->parse();
650 } elseif ( $exists['warning'] == 'exists-normalized' ) {
651 $warning = wfMessage( 'fileexists-extension', $filename,
652 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
653 } elseif ( $exists['warning'] == 'thumb' ) {
654 // Swapped argument order compared with other messages for backwards compatibility
655 $warning = wfMessage( 'fileexists-thumbnail-yes',
656 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
657 } elseif ( $exists['warning'] == 'thumb-name' ) {
658 // Image w/o '180px-' does not exists, but we do not like these filenames
659 $name = $file->getName();
660 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
661 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
662 } elseif ( $exists['warning'] == 'bad-prefix' ) {
663 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
664 } elseif ( $exists['warning'] == 'was-deleted' ) {
665 # If the file existed before and was deleted, warn the user of this
666 $ltitle = SpecialPage::getTitleFor( 'Log' );
667 $llink = Linker::linkKnown(
668 $ltitle,
669 wfMessage( 'deletionlog' )->escaped(),
670 array(),
671 array(
672 'type' => 'delete',
673 'page' => $filename
674 )
675 );
676 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
677 }
678
679 return $warning;
680 }
681
682 /**
683 * Construct a warning and a gallery from an array of duplicate files.
684 * @param $dupes array
685 * @return string
686 */
687 public function getDupeWarning( $dupes ) {
688 if ( !$dupes ) {
689 return '';
690 }
691
692 $gallery = ImageGalleryBase::factory();
693 $gallery->setContext( $this->getContext() );
694 $gallery->setShowBytes( false );
695 foreach ( $dupes as $file ) {
696 $gallery->add( $file->getTitle() );
697 }
698 return '<li>' .
699 wfMessage( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
700 $gallery->toHtml() . "</li>\n";
701 }
702
703 protected function getGroupName() {
704 return 'media';
705 }
706 }
707
708 /**
709 * Sub class of HTMLForm that provides the form section of SpecialUpload
710 */
711 class UploadForm extends HTMLForm {
712 protected $mWatch;
713 protected $mForReUpload;
714 protected $mSessionKey;
715 protected $mHideIgnoreWarning;
716 protected $mDestWarningAck;
717 protected $mDestFile;
718
719 protected $mComment;
720 protected $mTextTop;
721 protected $mTextAfterSummary;
722
723 protected $mSourceIds;
724
725 protected $mMaxFileSize = array();
726
727 protected $mMaxUploadSize = array();
728
729 public function __construct( array $options = array(), IContextSource $context = null ) {
730 $this->mWatch = !empty( $options['watch'] );
731 $this->mForReUpload = !empty( $options['forreupload'] );
732 $this->mSessionKey = isset( $options['sessionkey'] )
733 ? $options['sessionkey'] : '';
734 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
735 $this->mDestWarningAck = !empty( $options['destwarningack'] );
736 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
737
738 $this->mComment = isset( $options['description'] ) ?
739 $options['description'] : '';
740
741 $this->mTextTop = isset( $options['texttop'] )
742 ? $options['texttop'] : '';
743
744 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
745 ? $options['textaftersummary'] : '';
746
747 $sourceDescriptor = $this->getSourceSection();
748 $descriptor = $sourceDescriptor
749 + $this->getDescriptionSection()
750 + $this->getOptionsSection();
751
752 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
753 parent::__construct( $descriptor, $context, 'upload' );
754
755 # Set some form properties
756 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
757 $this->setSubmitName( 'wpUpload' );
758 # Used message keys: 'accesskey-upload', 'tooltip-upload'
759 $this->setSubmitTooltip( 'upload' );
760 $this->setId( 'mw-upload-form' );
761
762 # Build a list of IDs for javascript insertion
763 $this->mSourceIds = array();
764 foreach ( $sourceDescriptor as $field ) {
765 if ( !empty( $field['id'] ) ) {
766 $this->mSourceIds[] = $field['id'];
767 }
768 }
769
770 }
771
772 /**
773 * Get the descriptor of the fieldset that contains the file source
774 * selection. The section is 'source'
775 *
776 * @return Array: descriptor array
777 */
778 protected function getSourceSection() {
779 global $wgCopyUploadsFromSpecialUpload;
780
781 if ( $this->mSessionKey ) {
782 return array(
783 'SessionKey' => array(
784 'type' => 'hidden',
785 'default' => $this->mSessionKey,
786 ),
787 'SourceType' => array(
788 'type' => 'hidden',
789 'default' => 'Stash',
790 ),
791 );
792 }
793
794 $canUploadByUrl = UploadFromUrl::isEnabled()
795 && UploadFromUrl::isAllowed( $this->getUser() )
796 && $wgCopyUploadsFromSpecialUpload;
797 $radio = $canUploadByUrl;
798 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
799
800 $descriptor = array();
801 if ( $this->mTextTop ) {
802 $descriptor['UploadFormTextTop'] = array(
803 'type' => 'info',
804 'section' => 'source',
805 'default' => $this->mTextTop,
806 'raw' => true,
807 );
808 }
809
810 $this->mMaxUploadSize['file'] = UploadBase::getMaxUploadSize( 'file' );
811 # Limit to upload_max_filesize unless we are running under HipHop and
812 # that setting doesn't exist
813 if ( !wfIsHipHop() ) {
814 $this->mMaxUploadSize['file'] = min( $this->mMaxUploadSize['file'],
815 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
816 wfShorthandToInteger( ini_get( 'post_max_size' ) )
817 );
818 }
819
820 $descriptor['UploadFile'] = array(
821 'class' => 'UploadSourceField',
822 'section' => 'source',
823 'type' => 'file',
824 'id' => 'wpUploadFile',
825 'label-message' => 'sourcefilename',
826 'upload-type' => 'File',
827 'radio' => &$radio,
828 'help' => $this->msg( 'upload-maxfilesize',
829 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] ) )
830 ->parse() .
831 $this->msg( 'word-separator' )->escaped() .
832 $this->msg( 'upload_source_file' )->escaped(),
833 'checked' => $selectedSourceType == 'file',
834 );
835
836 if ( $canUploadByUrl ) {
837 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
838 $descriptor['UploadFileURL'] = array(
839 'class' => 'UploadSourceField',
840 'section' => 'source',
841 'id' => 'wpUploadFileURL',
842 'label-message' => 'sourceurl',
843 'upload-type' => 'url',
844 'radio' => &$radio,
845 'help' => $this->msg( 'upload-maxfilesize',
846 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] ) )
847 ->parse() .
848 $this->msg( 'word-separator' )->escaped() .
849 $this->msg( 'upload_source_url' )->escaped(),
850 'checked' => $selectedSourceType == 'url',
851 );
852 }
853 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
854
855 $descriptor['Extensions'] = array(
856 'type' => 'info',
857 'section' => 'source',
858 'default' => $this->getExtensionsMessage(),
859 'raw' => true,
860 );
861 return $descriptor;
862 }
863
864 /**
865 * Get the messages indicating which extensions are preferred and prohibitted.
866 *
867 * @return String: HTML string containing the message
868 */
869 protected function getExtensionsMessage() {
870 # Print a list of allowed file extensions, if so configured. We ignore
871 # MIME type here, it's incomprehensible to most people and too long.
872 global $wgCheckFileExtensions, $wgStrictFileExtensions,
873 $wgFileExtensions, $wgFileBlacklist;
874
875 if ( $wgCheckFileExtensions ) {
876 if ( $wgStrictFileExtensions ) {
877 # Everything not permitted is banned
878 $extensionsList =
879 '<div id="mw-upload-permitted">' .
880 $this->msg( 'upload-permitted', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) )->parseAsBlock() .
881 "</div>\n";
882 } else {
883 # We have to list both preferred and prohibited
884 $extensionsList =
885 '<div id="mw-upload-preferred">' .
886 $this->msg( 'upload-preferred', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) )->parseAsBlock() .
887 "</div>\n" .
888 '<div id="mw-upload-prohibited">' .
889 $this->msg( 'upload-prohibited', $this->getContext()->getLanguage()->commaList( $wgFileBlacklist ) )->parseAsBlock() .
890 "</div>\n";
891 }
892 } else {
893 # Everything is permitted.
894 $extensionsList = '';
895 }
896 return $extensionsList;
897 }
898
899 /**
900 * Get the descriptor of the fieldset that contains the file description
901 * input. The section is 'description'
902 *
903 * @return Array: descriptor array
904 */
905 protected function getDescriptionSection() {
906 if ( $this->mSessionKey ) {
907 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
908 try {
909 $file = $stash->getFile( $this->mSessionKey );
910 } catch ( MWException $e ) {
911 $file = null;
912 }
913 if ( $file ) {
914 global $wgContLang;
915
916 $mto = $file->transform( array( 'width' => 120 ) );
917 $this->addHeaderText(
918 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
919 Html::element( 'img', array(
920 'src' => $mto->getUrl(),
921 'class' => 'thumbimage',
922 ) ) . '</div>', 'description' );
923 }
924 }
925
926 $descriptor = array(
927 'DestFile' => array(
928 'type' => 'text',
929 'section' => 'description',
930 'id' => 'wpDestFile',
931 'label-message' => 'destfilename',
932 'size' => 60,
933 'default' => $this->mDestFile,
934 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
935 'nodata' => strval( $this->mDestFile ) !== '',
936 ),
937 'UploadDescription' => array(
938 'type' => 'textarea',
939 'section' => 'description',
940 'id' => 'wpUploadDescription',
941 'label-message' => $this->mForReUpload
942 ? 'filereuploadsummary'
943 : 'fileuploadsummary',
944 'default' => $this->mComment,
945 'cols' => $this->getUser()->getIntOption( 'cols' ),
946 'rows' => 8,
947 )
948 );
949 if ( $this->mTextAfterSummary ) {
950 $descriptor['UploadFormTextAfterSummary'] = array(
951 'type' => 'info',
952 'section' => 'description',
953 'default' => $this->mTextAfterSummary,
954 'raw' => true,
955 );
956 }
957
958 $descriptor += array(
959 'EditTools' => array(
960 'type' => 'edittools',
961 'section' => 'description',
962 'message' => 'edittools-upload',
963 )
964 );
965
966 if ( $this->mForReUpload ) {
967 $descriptor['DestFile']['readonly'] = true;
968 } else {
969 $descriptor['License'] = array(
970 'type' => 'select',
971 'class' => 'Licenses',
972 'section' => 'description',
973 'id' => 'wpLicense',
974 'label-message' => 'license',
975 );
976 }
977
978 global $wgUseCopyrightUpload;
979 if ( $wgUseCopyrightUpload ) {
980 $descriptor['UploadCopyStatus'] = array(
981 'type' => 'text',
982 'section' => 'description',
983 'id' => 'wpUploadCopyStatus',
984 'label-message' => 'filestatus',
985 );
986 $descriptor['UploadSource'] = array(
987 'type' => 'text',
988 'section' => 'description',
989 'id' => 'wpUploadSource',
990 'label-message' => 'filesource',
991 );
992 }
993
994 return $descriptor;
995 }
996
997 /**
998 * Get the descriptor of the fieldset that contains the upload options,
999 * such as "watch this file". The section is 'options'
1000 *
1001 * @return Array: descriptor array
1002 */
1003 protected function getOptionsSection() {
1004 $user = $this->getUser();
1005 if ( $user->isLoggedIn() ) {
1006 $descriptor = array(
1007 'Watchthis' => array(
1008 'type' => 'check',
1009 'id' => 'wpWatchthis',
1010 'label-message' => 'watchthisupload',
1011 'section' => 'options',
1012 'default' => $user->getOption( 'watchcreations' ),
1013 )
1014 );
1015 }
1016 if ( !$this->mHideIgnoreWarning ) {
1017 $descriptor['IgnoreWarning'] = array(
1018 'type' => 'check',
1019 'id' => 'wpIgnoreWarning',
1020 'label-message' => 'ignorewarnings',
1021 'section' => 'options',
1022 );
1023 }
1024
1025 $descriptor['DestFileWarningAck'] = array(
1026 'type' => 'hidden',
1027 'id' => 'wpDestFileWarningAck',
1028 'default' => $this->mDestWarningAck ? '1' : '',
1029 );
1030
1031 if ( $this->mForReUpload ) {
1032 $descriptor['ForReUpload'] = array(
1033 'type' => 'hidden',
1034 'id' => 'wpForReUpload',
1035 'default' => '1',
1036 );
1037 }
1038
1039 return $descriptor;
1040 }
1041
1042 /**
1043 * Add the upload JS and show the form.
1044 */
1045 public function show() {
1046 $this->addUploadJS();
1047 parent::show();
1048 }
1049
1050 /**
1051 * Add upload JS to the OutputPage
1052 */
1053 protected function addUploadJS() {
1054 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1055
1056 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1057 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1058 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1059
1060 $scriptVars = array(
1061 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1062 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1063 'wgUploadAutoFill' => !$this->mForReUpload &&
1064 // If we received mDestFile from the request, don't autofill
1065 // the wpDestFile textbox
1066 $this->mDestFile === '',
1067 'wgUploadSourceIds' => $this->mSourceIds,
1068 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1069 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1070 'wgMaxUploadSize' => $this->mMaxUploadSize,
1071 );
1072
1073 $out = $this->getOutput();
1074 $out->addJsConfigVars( $scriptVars );
1075
1076 $out->addModules( array(
1077 'mediawiki.action.edit', // For <charinsert> support
1078 'mediawiki.legacy.upload', // Old form stuff...
1079 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1080 ) );
1081 }
1082
1083 /**
1084 * Empty function; submission is handled elsewhere.
1085 *
1086 * @return bool false
1087 */
1088 function trySubmit() {
1089 return false;
1090 }
1091
1092 }
1093
1094 /**
1095 * A form field that contains a radio box in the label
1096 */
1097 class UploadSourceField extends HTMLTextField {
1098
1099 /**
1100 * @param $cellAttributes array
1101 * @return string
1102 */
1103 function getLabelHtml( $cellAttributes = array() ) {
1104 $id = $this->mParams['id'];
1105 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1106
1107 if ( !empty( $this->mParams['radio'] ) ) {
1108 $attribs = array(
1109 'name' => 'wpSourceType',
1110 'type' => 'radio',
1111 'id' => $id,
1112 'value' => $this->mParams['upload-type'],
1113 );
1114 if ( !empty( $this->mParams['checked'] ) ) {
1115 $attribs['checked'] = 'checked';
1116 }
1117 $label .= Html::element( 'input', $attribs );
1118 }
1119
1120 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1121 }
1122
1123 /**
1124 * @return int
1125 */
1126 function getSize() {
1127 return isset( $this->mParams['size'] )
1128 ? $this->mParams['size']
1129 : 60;
1130 }
1131 }