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