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