Documentation
[lhc/web/wiklou.git] / includes / specials / SpecialUpload.php
1 <?php
2 /**
3 * Implements Special:Upload
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 * @ingroup Upload
23 */
24
25 /**
26 * Form for handling uploads and special page.
27 *
28 * @ingroup SpecialPage
29 * @ingroup Upload
30 */
31 class SpecialUpload extends SpecialPage {
32 /**
33 * Constructor : initialise object
34 * Get data POSTed through the form and assign them to the object
35 * @param $request WebRequest : data posted.
36 */
37 public function __construct( $request = null ) {
38 parent::__construct( 'Upload', 'upload' );
39 }
40
41 /** Misc variables **/
42 public $mRequest; // The WebRequest or FauxRequest this form is supposed to handle
43 public $mSourceType;
44
45 /**
46 * @var UploadBase
47 */
48 public $mUpload;
49
50 /**
51 * @var LocalFile
52 */
53 public $mLocalFile;
54 public $mUploadClicked;
55
56 /** User input variables from the "description" section **/
57 public $mDesiredDestName; // The requested target file name
58 public $mComment;
59 public $mLicense;
60
61 /** User input variables from the root section **/
62 public $mIgnoreWarning;
63 public $mWatchThis;
64 public $mCopyrightStatus;
65 public $mCopyrightSource;
66
67 /** Hidden variables **/
68 public $mDestWarningAck;
69 public $mForReUpload; // The user followed an "overwrite this file" link
70 public $mCancelUpload; // The user clicked "Cancel and return to upload form" button
71 public $mTokenOk;
72 public $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
73
74 /** Text injection points for hooks not using HTMLForm **/
75 public $uploadFormTextTop;
76 public $uploadFormTextAfterSummary;
77
78 public $mWatchthis;
79
80 /**
81 * Initialize instance variables from request and create an Upload handler
82 */
83 protected function loadRequest() {
84 $this->mRequest = $request = $this->getRequest();
85 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
86 $this->mUpload = UploadBase::createFromRequest( $request );
87 $this->mUploadClicked = $request->wasPosted()
88 && ( $request->getCheck( 'wpUpload' )
89 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
90
91 // Guess the desired name from the filename if not provided
92 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
93 if( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
94 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
95 }
96 $this->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 $this->setHeaders();
144 $this->outputHeader();
145
146 # Check uploading enabled
147 if( !UploadBase::isEnabled() ) {
148 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
149 }
150
151 # Check permissions
152 $user = $this->getUser();
153 $permissionRequired = UploadBase::isAllowed( $user );
154 if( $permissionRequired !== true ) {
155 throw new PermissionsError( $permissionRequired );
156 }
157
158 # Check blocks
159 if( $user->isBlocked() ) {
160 throw new UserBlockedError( $user->mBlock );
161 }
162
163 # Check whether we actually want to allow changing stuff
164 $this->checkReadOnly();
165
166 $this->loadRequest();
167
168 # Unsave the temporary file in case this was a cancelled upload
169 if ( $this->mCancelUpload ) {
170 if ( !$this->unsaveUploadedFile() ) {
171 # Something went wrong, so unsaveUploadedFile showed a warning
172 return;
173 }
174 }
175
176 # Process upload or show a form
177 if (
178 $this->mTokenOk && !$this->mCancelUpload &&
179 ( $this->mUpload && $this->mUploadClicked )
180 )
181 {
182 $this->processUpload();
183 } else {
184 # Backwards compatibility hook
185 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
186 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
187 return;
188 }
189
190
191 $this->showUploadForm( $this->getUploadForm() );
192 }
193
194 # Cleanup
195 if ( $this->mUpload ) {
196 $this->mUpload->cleanupTempFile();
197 }
198 }
199
200 /**
201 * Show the main upload form
202 *
203 * @param $form Mixed: an HTMLForm instance or HTML string to show
204 */
205 protected function showUploadForm( $form ) {
206 # Add links if file was previously deleted
207 if ( $this->mDesiredDestName ) {
208 $this->showViewDeletedLinks();
209 }
210
211 if ( $form instanceof HTMLForm ) {
212 $form->show();
213 } else {
214 $this->getOutput()->addHTML( $form );
215 }
216
217 }
218
219 /**
220 * Get an UploadForm instance with title and text properly set.
221 *
222 * @param $message String: HTML string to add to the form
223 * @param $sessionKey String: session key in case this is a stashed upload
224 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
225 * @return UploadForm
226 */
227 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
228 # Initialize form
229 $form = new UploadForm( array(
230 'watch' => $this->getWatchCheck(),
231 'forreupload' => $this->mForReUpload,
232 'sessionkey' => $sessionKey,
233 'hideignorewarning' => $hideIgnoreWarning,
234 'destwarningack' => (bool)$this->mDestWarningAck,
235
236 'description' => $this->mComment,
237 'texttop' => $this->uploadFormTextTop,
238 'textaftersummary' => $this->uploadFormTextAfterSummary,
239 'destfile' => $this->mDesiredDestName,
240 ), $this->getContext() );
241 $form->setTitle( $this->getTitle() );
242
243 # Check the token, but only if necessary
244 if(
245 !$this->mTokenOk && !$this->mCancelUpload &&
246 ( $this->mUpload && $this->mUploadClicked )
247 ) {
248 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
249 }
250
251 # Give a notice if the user is uploading a file that has been deleted or moved
252 # Note that this is independent from the message 'filewasdeleted' that requires JS
253 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
254 $delNotice = ''; // empty by default
255 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
256 LogEventsList::showLogExtract( $delNotice, array( 'delete', 'move' ),
257 $desiredTitleObj,
258 '', array( 'lim' => 10,
259 'conds' => array( "log_action != 'revision'" ),
260 'showIfEmpty' => false,
261 'msgKey' => array( 'upload-recreate-warning' ) )
262 );
263 }
264 $form->addPreText( $delNotice );
265
266 # Add text to form
267 $form->addPreText( '<div id="uploadtext">' .
268 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName ) ) .
269 '</div>' );
270 # Add upload error message
271 $form->addPreText( $message );
272
273 # Add footer to form
274 $uploadFooter = wfMessage( 'uploadfooter' );
275 if ( !$uploadFooter->isDisabled() ) {
276 $form->addPostText( '<div id="mw-upload-footer-message">'
277 . $this->getOutput()->parse( $uploadFooter->plain() ) . "</div>\n" );
278 }
279
280 return $form;
281 }
282
283 /**
284 * Shows the "view X deleted revivions link""
285 */
286 protected function showViewDeletedLinks() {
287 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
288 $user = $this->getUser();
289 // Show a subtitle link to deleted revisions (to sysops et al only)
290 if( $title instanceof Title ) {
291 $count = $title->isDeleted();
292 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
293 $link = wfMsgExt(
294 $user->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
295 array( 'parse', 'replaceafter' ),
296 Linker::linkKnown(
297 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
298 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
299 )
300 );
301 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
302 }
303 }
304 }
305
306 /**
307 * Stashes the upload and shows the main upload form.
308 *
309 * Note: only errors that can be handled by changing the name or
310 * description should be redirected here. It should be assumed that the
311 * file itself is sane and has passed UploadBase::verifyFile. This
312 * essentially means that UploadBase::VERIFICATION_ERROR and
313 * UploadBase::EMPTY_FILE should not be passed here.
314 *
315 * @param $message String: HTML message to be passed to mainUploadForm
316 */
317 protected function showRecoverableUploadError( $message ) {
318 $sessionKey = $this->mUpload->stashSession();
319 $message = '<h2>' . wfMsgHtml( 'uploaderror' ) . "</h2>\n" .
320 '<div class="error">' . $message . "</div>\n";
321
322 $form = $this->getUploadForm( $message, $sessionKey );
323 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
324 $this->showUploadForm( $form );
325 }
326 /**
327 * Stashes the upload, shows the main form, but adds an "continue anyway button".
328 * Also checks whether there are actually warnings to display.
329 *
330 * @param $warnings Array
331 * @return boolean true if warnings were displayed, false if there are no
332 * warnings and the should continue processing like there was no warning
333 */
334 protected function showUploadWarning( $warnings ) {
335 # If there are no warnings, or warnings we can ignore, return early.
336 # mDestWarningAck is set when some javascript has shown the warning
337 # to the user. mForReUpload is set when the user clicks the "upload a
338 # new version" link.
339 if ( !$warnings || ( count( $warnings ) == 1 &&
340 isset( $warnings['exists'] ) &&
341 ( $this->mDestWarningAck || $this->mForReUpload ) ) )
342 {
343 return false;
344 }
345
346 $sessionKey = $this->mUpload->stashSession();
347
348 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
349 . '<ul class="warning">';
350 foreach( $warnings as $warning => $args ) {
351 if( $warning == 'exists' ) {
352 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
353 } elseif( $warning == 'duplicate' ) {
354 $msg = self::getDupeWarning( $args );
355 } elseif( $warning == 'duplicate-archive' ) {
356 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
357 array( Title::makeTitle( NS_FILE, $args )->getPrefixedText() ) )
358 . "</li>\n";
359 } else {
360 if ( $args === true ) {
361 $args = array();
362 } elseif ( !is_array( $args ) ) {
363 $args = array( $args );
364 }
365 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
366 }
367 $warningHtml .= $msg;
368 }
369 $warningHtml .= "</ul>\n";
370 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
371
372 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
373 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
374 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
375 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
376
377 $this->showUploadForm( $form );
378
379 # Indicate that we showed a form
380 return true;
381 }
382
383 /**
384 * Show the upload form with error message, but do not stash the file.
385 *
386 * @param $message string HTML string
387 */
388 protected function showUploadError( $message ) {
389 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
390 '<div class="error">' . $message . "</div>\n";
391 $this->showUploadForm( $this->getUploadForm( $message ) );
392 }
393
394 /**
395 * Do the upload.
396 * Checks are made in SpecialUpload::execute()
397 */
398 protected function processUpload() {
399 // Fetch the file if required
400 $status = $this->mUpload->fetchFile();
401 if( !$status->isOK() ) {
402 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
403 return;
404 }
405
406 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
407 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
408 // This code path is deprecated. If you want to break upload processing
409 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
410 // and UploadBase::verifyFile.
411 // If you use this hook to break uploading, the user will be returned
412 // an empty form with no error message whatsoever.
413 return;
414 }
415
416 // Upload verification
417 $details = $this->mUpload->verifyUpload();
418 if ( $details['status'] != UploadBase::OK ) {
419 $this->processVerificationError( $details );
420 return;
421 }
422
423 // Verify permissions for this title
424 $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
425 if( $permErrors !== true ) {
426 $code = array_shift( $permErrors[0] );
427 $this->showRecoverableUploadError( wfMsgExt( $code,
428 'parseinline', $permErrors[0] ) );
429 return;
430 }
431
432 $this->mLocalFile = $this->mUpload->getLocalFile();
433
434 // Check warnings if necessary
435 if( !$this->mIgnoreWarning ) {
436 $warnings = $this->mUpload->checkWarnings();
437 if( $this->showUploadWarning( $warnings ) ) {
438 return;
439 }
440 }
441
442 // Get the page text if this is not a reupload
443 if( !$this->mForReUpload ) {
444 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
445 $this->mCopyrightStatus, $this->mCopyrightSource );
446 } else {
447 $pageText = false;
448 }
449 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $this->getUser() );
450 if ( !$status->isGood() ) {
451 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
452 return;
453 }
454
455 // Success, redirect to description page
456 $this->mUploadSuccessful = true;
457 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
458 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
459 }
460
461 /**
462 * Get the initial image page text based on a comment and optional file status information
463 * @param $comment string
464 * @param $license string
465 * @param $copyStatus string
466 * @param $source string
467 * @return string
468 */
469 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
470 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
471 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
472
473 $msg = array();
474 /* These messages are transcluded into the actual text of the description page.
475 * Thus, forcing them as content messages makes the upload to produce an int: template
476 * instead of hardcoding it there in the uploader language.
477 */
478 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
479 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
480 $msg[$msgName] = "{{int:$msgName}}";
481 } else {
482 $msg[$msgName] = wfMsgForContent( $msgName );
483 }
484 }
485
486 if ( $wgUseCopyrightUpload ) {
487 $licensetxt = '';
488 if ( $license != '' ) {
489 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
490 }
491 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
492 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
493 "$licensetxt" .
494 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
495 } else {
496 if ( $license != '' ) {
497 $filedesc = $comment == '' ? '' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
498 $pageText = $filedesc .
499 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
500 } else {
501 $pageText = $comment;
502 }
503 }
504 return $pageText;
505 }
506
507 /**
508 * See if we should check the 'watch this page' checkbox on the form
509 * based on the user's preferences and whether we're being asked
510 * to create a new file or update an existing one.
511 *
512 * In the case where 'watch edits' is off but 'watch creations' is on,
513 * we'll leave the box unchecked.
514 *
515 * Note that the page target can be changed *on the form*, so our check
516 * state can get out of sync.
517 * @return Bool|String
518 */
519 protected function getWatchCheck() {
520 if( $this->getUser()->getOption( 'watchdefault' ) ) {
521 // Watch all edits!
522 return true;
523 }
524
525 $local = wfLocalFile( $this->mDesiredDestName );
526 if( $local && $local->exists() ) {
527 // We're uploading a new version of an existing file.
528 // No creation, so don't watch it if we're not already.
529 return $local->getTitle()->userIsWatching();
530 } else {
531 // New page should get watched if that's our option.
532 return $this->getUser()->getOption( 'watchcreations' );
533 }
534 }
535
536
537 /**
538 * Provides output to the user for a result of UploadBase::verifyUpload
539 *
540 * @param $details Array: result of UploadBase::verifyUpload
541 */
542 protected function processVerificationError( $details ) {
543 global $wgFileExtensions;
544
545 switch( $details['status'] ) {
546
547 /** Statuses that only require name changing **/
548 case UploadBase::MIN_LENGTH_PARTNAME:
549 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
550 break;
551 case UploadBase::ILLEGAL_FILENAME:
552 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
553 'parseinline', $details['filtered'] ) );
554 break;
555 case UploadBase::FILENAME_TOO_LONG:
556 $this->showRecoverableUploadError( wfMsgHtml( 'filename-toolong' ) );
557 break;
558 case UploadBase::FILETYPE_MISSING:
559 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
560 'parseinline' ) );
561 break;
562 case UploadBase::WINDOWS_NONASCII_FILENAME:
563 $this->showRecoverableUploadError( wfMsgExt( 'windows-nonascii-filename',
564 'parseinline' ) );
565 break;
566
567 /** Statuses that require reuploading **/
568 case UploadBase::EMPTY_FILE:
569 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
570 break;
571 case UploadBase::FILE_TOO_LARGE:
572 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
573 break;
574 case UploadBase::FILETYPE_BADTYPE:
575 $msg = wfMessage( 'filetype-banned-type' );
576 if ( isset( $details['blacklistedExt'] ) ) {
577 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
578 } else {
579 $msg->params( $details['finalExt'] );
580 }
581 $msg->params( $this->getLanguage()->commaList( $wgFileExtensions ),
582 count( $wgFileExtensions ) );
583
584 // Add PLURAL support for the first parameter. This results
585 // in a bit unlogical parameter sequence, but does not break
586 // old translations
587 if ( isset( $details['blacklistedExt'] ) ) {
588 $msg->params( count( $details['blacklistedExt'] ) );
589 } else {
590 $msg->params( 1 );
591 }
592
593 $this->showUploadError( $msg->parse() );
594 break;
595 case UploadBase::VERIFICATION_ERROR:
596 unset( $details['status'] );
597 $code = array_shift( $details['details'] );
598 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
599 break;
600 case UploadBase::HOOK_ABORTED:
601 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
602 $args = $details['error'];
603 $error = array_shift( $args );
604 } else {
605 $error = $details['error'];
606 $args = null;
607 }
608
609 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
610 break;
611 default:
612 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
613 }
614 }
615
616 /**
617 * Remove a temporarily kept file stashed by saveTempUploadedFile().
618 *
619 * @return Boolean: success
620 */
621 protected function unsaveUploadedFile() {
622 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
623 return true;
624 }
625 $success = $this->mUpload->unsaveUploadedFile();
626 if ( !$success ) {
627 $this->getOutput()->showFileDeleteError( $this->mUpload->getTempPath() );
628 return false;
629 } else {
630 return true;
631 }
632 }
633
634 /*** Functions for formatting warnings ***/
635
636 /**
637 * Formats a result of UploadBase::getExistsWarning as HTML
638 * This check is static and can be done pre-upload via AJAX
639 *
640 * @param $exists Array: the result of UploadBase::getExistsWarning
641 * @return String: empty string if there is no warning or an HTML fragment
642 */
643 public static function getExistsWarning( $exists ) {
644 if ( !$exists ) {
645 return '';
646 }
647
648 $file = $exists['file'];
649 $filename = $file->getTitle()->getPrefixedText();
650 $warning = '';
651
652 if( $exists['warning'] == 'exists' ) {
653 // Exact match
654 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
655 } elseif( $exists['warning'] == 'page-exists' ) {
656 // Page exists but file does not
657 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
658 } elseif ( $exists['warning'] == 'exists-normalized' ) {
659 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
660 $exists['normalizedFile']->getTitle()->getPrefixedText() );
661 } elseif ( $exists['warning'] == 'thumb' ) {
662 // Swapped argument order compared with other messages for backwards compatibility
663 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
664 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
665 } elseif ( $exists['warning'] == 'thumb-name' ) {
666 // Image w/o '180px-' does not exists, but we do not like these filenames
667 $name = $file->getName();
668 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
669 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
670 } elseif ( $exists['warning'] == 'bad-prefix' ) {
671 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
672 } elseif ( $exists['warning'] == 'was-deleted' ) {
673 # If the file existed before and was deleted, warn the user of this
674 $ltitle = SpecialPage::getTitleFor( 'Log' );
675 $llink = Linker::linkKnown(
676 $ltitle,
677 wfMsgHtml( 'deletionlog' ),
678 array(),
679 array(
680 'type' => 'delete',
681 'page' => $filename
682 )
683 );
684 $warning = wfMsgExt( 'filewasdeleted', array( 'parse', 'replaceafter' ), $llink );
685 }
686
687 return $warning;
688 }
689
690 /**
691 * Get a list of warnings
692 *
693 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
694 * @return Array: list of warning messages
695 */
696 public static function ajaxGetExistsWarning( $filename ) {
697 $file = wfFindFile( $filename );
698 if( !$file ) {
699 // Force local file so we have an object to do further checks against
700 // if there isn't an exact match...
701 $file = wfLocalFile( $filename );
702 }
703 $s = '&#160;';
704 if ( $file ) {
705 $exists = UploadBase::getExistsWarning( $file );
706 $warning = self::getExistsWarning( $exists );
707 if ( $warning !== '' ) {
708 $s = "<div>$warning</div>";
709 }
710 }
711 return $s;
712 }
713
714 /**
715 * Construct a warning and a gallery from an array of duplicate files.
716 * @param $dupes array
717 * @return string
718 */
719 public static function getDupeWarning( $dupes ) {
720 global $wgOut;
721 if( $dupes ) {
722 $msg = '<gallery>';
723 foreach( $dupes as $file ) {
724 $title = $file->getTitle();
725 $msg .= $title->getPrefixedText() .
726 '|' . $title->getText() . "\n";
727 }
728 $msg .= '</gallery>';
729 return '<li>' .
730 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
731 $wgOut->parse( $msg ) .
732 "</li>\n";
733 } else {
734 return '';
735 }
736 }
737
738 }
739
740 /**
741 * Sub class of HTMLForm that provides the form section of SpecialUpload
742 */
743 class UploadForm extends HTMLForm {
744 protected $mWatch;
745 protected $mForReUpload;
746 protected $mSessionKey;
747 protected $mHideIgnoreWarning;
748 protected $mDestWarningAck;
749 protected $mDestFile;
750
751 protected $mComment;
752 protected $mTextTop;
753 protected $mTextAfterSummary;
754
755 protected $mSourceIds;
756
757 protected $mMaxFileSize = array();
758
759 protected $mMaxUploadSize = array();
760
761 public function __construct( array $options = array(), IContextSource $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()->getLanguage()->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()->getLanguage()->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()->getLanguage()->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()->getLanguage()->commaList( $wgFileExtensions ) ) .
910 "</div>\n" .
911 '<div id="mw-upload-prohibited">' .
912 wfMsgExt( 'upload-prohibited', 'parse', $this->getContext()->getLanguage()->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 'rows' => 8,
969 )
970 );
971 if ( $this->mTextAfterSummary ) {
972 $descriptor['UploadFormTextAfterSummary'] = array(
973 'type' => 'info',
974 'section' => 'description',
975 'default' => $this->mTextAfterSummary,
976 'raw' => true,
977 );
978 }
979
980 $descriptor += array(
981 'EditTools' => array(
982 'type' => 'edittools',
983 'section' => 'description',
984 'message' => 'edittools-upload',
985 )
986 );
987
988 if ( $this->mForReUpload ) {
989 $descriptor['DestFile']['readonly'] = true;
990 } else {
991 $descriptor['License'] = array(
992 'type' => 'select',
993 'class' => 'Licenses',
994 'section' => 'description',
995 'id' => 'wpLicense',
996 'label-message' => 'license',
997 );
998 }
999
1000 global $wgUseCopyrightUpload;
1001 if ( $wgUseCopyrightUpload ) {
1002 $descriptor['UploadCopyStatus'] = array(
1003 'type' => 'text',
1004 'section' => 'description',
1005 'id' => 'wpUploadCopyStatus',
1006 'label-message' => 'filestatus',
1007 );
1008 $descriptor['UploadSource'] = array(
1009 'type' => 'text',
1010 'section' => 'description',
1011 'id' => 'wpUploadSource',
1012 'label-message' => 'filesource',
1013 );
1014 }
1015
1016 return $descriptor;
1017 }
1018
1019 /**
1020 * Get the descriptor of the fieldset that contains the upload options,
1021 * such as "watch this file". The section is 'options'
1022 *
1023 * @return Array: descriptor array
1024 */
1025 protected function getOptionsSection() {
1026 $user = $this->getUser();
1027 if ( $user->isLoggedIn() ) {
1028 $descriptor = array(
1029 'Watchthis' => array(
1030 'type' => 'check',
1031 'id' => 'wpWatchthis',
1032 'label-message' => 'watchthisupload',
1033 'section' => 'options',
1034 'default' => $user->getOption( 'watchcreations' ),
1035 )
1036 );
1037 }
1038 if ( !$this->mHideIgnoreWarning ) {
1039 $descriptor['IgnoreWarning'] = array(
1040 'type' => 'check',
1041 'id' => 'wpIgnoreWarning',
1042 'label-message' => 'ignorewarnings',
1043 'section' => 'options',
1044 );
1045 }
1046
1047 $descriptor['DestFileWarningAck'] = array(
1048 'type' => 'hidden',
1049 'id' => 'wpDestFileWarningAck',
1050 'default' => $this->mDestWarningAck ? '1' : '',
1051 );
1052
1053 if ( $this->mForReUpload ) {
1054 $descriptor['ForReUpload'] = array(
1055 'type' => 'hidden',
1056 'id' => 'wpForReUpload',
1057 'default' => '1',
1058 );
1059 }
1060
1061 return $descriptor;
1062 }
1063
1064 /**
1065 * Add the upload JS and show the form.
1066 */
1067 public function show() {
1068 $this->addUploadJS();
1069 parent::show();
1070 }
1071
1072 /**
1073 * Add upload JS to the OutputPage
1074 */
1075 protected function addUploadJS() {
1076 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1077
1078 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1079 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1080 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1081
1082 $scriptVars = array(
1083 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1084 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1085 'wgUploadAutoFill' => !$this->mForReUpload &&
1086 // If we received mDestFile from the request, don't autofill
1087 // the wpDestFile textbox
1088 $this->mDestFile === '',
1089 'wgUploadSourceIds' => $this->mSourceIds,
1090 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1091 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1092 'wgMaxUploadSize' => $this->mMaxUploadSize,
1093 );
1094
1095 $out = $this->getOutput();
1096 $out->addJsConfigVars( $scriptVars );
1097
1098
1099 $out->addModules( array(
1100 'mediawiki.action.edit', // For <charinsert> support
1101 'mediawiki.legacy.upload', // Old form stuff...
1102 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1103 ) );
1104 }
1105
1106 /**
1107 * Empty function; submission is handled elsewhere.
1108 *
1109 * @return bool false
1110 */
1111 function trySubmit() {
1112 return false;
1113 }
1114
1115 }
1116
1117 /**
1118 * A form field that contains a radio box in the label
1119 */
1120 class UploadSourceField extends HTMLTextField {
1121
1122 /**
1123 * @param $cellAttributes array
1124 * @return string
1125 */
1126 function getLabelHtml( $cellAttributes = array() ) {
1127 $id = "wpSourceType{$this->mParams['upload-type']}";
1128 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1129
1130 if ( !empty( $this->mParams['radio'] ) ) {
1131 $attribs = array(
1132 'name' => 'wpSourceType',
1133 'type' => 'radio',
1134 'id' => $id,
1135 'value' => $this->mParams['upload-type'],
1136 );
1137 if ( !empty( $this->mParams['checked'] ) ) {
1138 $attribs['checked'] = 'checked';
1139 }
1140 $label .= Html::element( 'input', $attribs );
1141 }
1142
1143 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1144 }
1145
1146 /**
1147 * @return int
1148 */
1149 function getSize() {
1150 return isset( $this->mParams['size'] )
1151 ? $this->mParams['size']
1152 : 60;
1153 }
1154 }
1155