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