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