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