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