Follow up to r56639: Remove some existence check duplication and fix ApiUpload for...
[lhc/web/wiklou.git] / includes / specials / SpecialUpload.php
1 <?php
2 /**
3 * @file
4 * @ingroup SpecialPage
5 */
6
7 /**
8 * implements Special:Upload
9 * @ingroup SpecialPage
10 */
11 class UploadForm extends SpecialPage {
12 /**#@+
13 * @access private
14 */
15 var $mComment, $mLicense, $mIgnoreWarning;
16 var $mCopyrightStatus, $mCopyrightSource, $mReUpload, $mAction, $mUploadClicked;
17 var $mDestWarningAck;
18 var $mLocalFile;
19
20 var $mUpload; // Instance of UploadBase or derivative
21
22 # Placeholders for text injection by hooks (must be HTML)
23 # extensions should take care to _append_ to the present value
24 var $uploadFormTextTop;
25 var $uploadFormTextAfterSummary;
26 var $mTokenOk = false;
27 var $mForReUpload = false;
28 /**#@-*/
29
30 /**
31 * Constructor : initialise object
32 * Get data POSTed through the form and assign them to the object
33 * @param $request Data posted.
34 */
35 function __construct( $request = null ) {
36 parent::__construct( 'Upload', 'upload' );
37 $this->mRequest = $request;
38 }
39
40 protected function initForm() {
41 global $wgRequest, $wgUser;
42
43 if ( is_null( $this->mRequest ) ) {
44 $request = $wgRequest;
45 } else {
46 $request = $this->mRequest;
47 }
48 // Guess the desired name from the filename if not provided
49 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
50 if( !$this->mDesiredDestName )
51 $this->mDesiredDestName = $request->getText( 'wpUploadFile' );
52
53 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
54 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' );
55 $this->mComment = $request->getText( 'wpUploadDescription' );
56
57 if( !$request->wasPosted() ) {
58 # GET requests just give the main form; no data except destination
59 # filename and description
60 return;
61 }
62 //if it was posted check for the token (no remote POST'ing with user credentials)
63 $token = $request->getVal( 'wpEditToken' );
64 $this->mTokenOk = $wgUser->matchEditToken( $token );
65
66 # Placeholders for text injection by hooks (empty per default)
67 $this->uploadFormTextTop = "";
68 $this->uploadFormTextAfterSummary = "";
69
70 $this->mUploadClicked = $request->getCheck( 'wpUpload' );
71
72 $this->mLicense = $request->getText( 'wpLicense' );
73 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
74 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
75 $this->mWatchthis = $request->getBool( 'wpWatchthis' );
76 $this->mSourceType = $request->getText( 'wpSourceType' );
77 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
78
79 $this->mReUpload = $request->getCheck( 'wpReUpload' ); // retrying upload
80
81 $this->mAction = $request->getVal( 'action' );
82 $this->mUpload = UploadBase::createFromRequest( $request );
83 }
84
85 public function userCanExecute( $user ) {
86 return UploadBase::isEnabled() && parent::userCanExecute( $user );
87 }
88
89 /**
90 * Start doing stuff
91 * @access public
92 */
93 function execute( $par ) {
94 global $wgUser, $wgOut, $wgRequest;
95
96 $this->setHeaders();
97 $this->outputHeader();
98
99 $this->initForm();
100
101 # Check uploading enabled
102 if( !UploadBase::isEnabled() ) {
103 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
104 return;
105 }
106
107 # Check permissions
108 global $wgGroupPermissions;
109 if( !$wgUser->isAllowed( 'upload' ) ) {
110 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
111 || $wgGroupPermissions['autoconfirmed']['upload'] ) ) {
112 // Custom message if logged-in users without any special rights can upload
113 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
114 } else {
115 $wgOut->permissionRequired( 'upload' );
116 }
117 return;
118 }
119
120 # Check blocks
121 if( $wgUser->isBlocked() ) {
122 $wgOut->blockedPage();
123 return;
124 }
125
126 if( wfReadOnly() ) {
127 $wgOut->readOnlyPage();
128 return;
129 }
130 //check token if uploading or reUploading
131 if( !$this->mTokenOk && !$this->mReUpload && ($this->mUpload && (
132 'submit' == $this->mAction || $this->mUploadClicked ) ) )
133 {
134 $this->mainUploadForm ( wfMsg( 'session_fail_preview', 'parseinline' ) );
135 return ;
136 }
137
138
139 if( $this->mReUpload && $this->mUpload) {
140 // User choose to cancel upload
141 if( !$this->mUpload->unsaveUploadedFile() ) {
142 return;
143 }
144 # Because it is probably checked and shouldn't be
145 $this->mIgnoreWarning = false;
146 $this->mainUploadForm();
147 } elseif( $this->mUpload && (
148 'submit' == $this->mAction ||
149 $this->mUploadClicked
150 ) ) {
151 $this->processUpload();
152 } else {
153 $this->mainUploadForm();
154 }
155
156 if( $this->mUpload )
157 $this->mUpload->cleanupTempFile();
158 }
159
160 /**
161 * Do the upload
162 * Checks are made in SpecialUpload::execute()
163 *
164 * FIXME this should really use the standard Status class (instead of associative array)
165 * FIXME would be nice if we refactored this into the upload api.
166 * (the special upload page is not the only response point that needs clean localized error msgs)
167 *
168 * @access private
169 */
170 function processUpload() {
171 global $wgOut, $wgFileExtensions, $wgLang;
172 $details = $this->internalProcessUpload();
173 switch( $details['status'] ) {
174 case UploadBase::SUCCESS:
175 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
176 break;
177
178 case UploadBase::BEFORE_PROCESSING:
179 $this->uploadError( $details['error'] );
180 break;
181 case UploadBase::LARGE_FILE_SERVER:
182 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
183 break;
184
185 case UploadBase::EMPTY_FILE:
186 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
187 break;
188
189 case UploadBase::MIN_LENGTH_PARTNAME:
190 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
191 break;
192
193 case UploadBase::ILLEGAL_FILENAME:
194 $this->uploadError( wfMsgExt( 'illegalfilename',
195 'parseinline', $details['filtered'] ) );
196 break;
197
198 case UploadBase::PROTECTED_PAGE:
199 $wgOut->showPermissionsErrorPage( $details['permissionserrors'] );
200 break;
201
202 case UploadBase::OVERWRITE_EXISTING_FILE:
203 $this->uploadError( wfMsgExt( $details['overwrite'],
204 'parseinline' ) );
205 break;
206
207 case UploadBase::FILETYPE_MISSING:
208 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
209 break;
210
211 case UploadBase::FILETYPE_BADTYPE:
212 $finalExt = $details['finalExt'];
213 $this->uploadError(
214 wfMsgExt( 'filetype-banned-type',
215 array( 'parseinline' ),
216 htmlspecialchars( $finalExt ),
217 implode(
218 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
219 $wgFileExtensions
220 ),
221 $wgLang->formatNum( count( $wgFileExtensions ) )
222 )
223 );
224 break;
225
226 case UploadBase::VERIFICATION_ERROR:
227 unset( $details['status'] );
228 $code = array_shift( $details['details'] );
229 $this->uploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
230 break;
231
232 case UploadBase::UPLOAD_VERIFICATION_ERROR:
233 $error = $details['error'];
234 $this->uploadError( wfMsgExt( $error, 'parseinline' ) );
235 break;
236
237 case UploadBase::UPLOAD_WARNING:
238 unset( $details['status'] );
239 $this->uploadWarning( $details );
240 break;
241
242 case UploadBase::INTERNAL_ERROR:
243 $status = $details['internal'];
244 $this->showError( $wgOut->parse( $status->getWikiText() ) );
245 break;
246
247 default:
248 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
249 }
250 }
251
252 /**
253 * Really do the upload
254 * Checks are made in SpecialUpload::execute()
255 *
256 * @param array $resultDetails contains result-specific dict of additional values
257 *
258 * @access private
259 */
260 function internalProcessUpload() {
261 global $wgUser;
262
263 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
264 {
265 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
266 return array( 'status' => UploadBase::BEFORE_PROCESSING );
267 }
268
269 /**
270 * If the image is protected, non-sysop users won't be able
271 * to modify it by uploading a new revision.
272 */
273 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
274 if( $permErrors !== true ) {
275 return array( 'status' => UploadBase::PROTECTED_PAGE, 'permissionserrors' => $permErrors );
276 }
277
278 // Fetch the file if required
279 $status = $this->mUpload->fetchFile();
280 if( !$status->isOK() ) {
281 return array( 'status' => UploadBase::BEFORE_PROCESSING, 'error'=> $status->getWikiText() );
282 }
283
284 // Check whether this is a sane upload
285 $result = $this->mUpload->verifyUpload();
286 if( $result['status'] != UploadBase::OK )
287 return $result;
288
289 $this->mLocalFile = $this->mUpload->getLocalFile();
290
291 if( !$this->mIgnoreWarning ) {
292 $warnings = $this->mUpload->checkWarnings();
293
294 if( count( $warnings ) ) {
295 $warnings['status'] = UploadBase::UPLOAD_WARNING;
296 return $warnings;
297 }
298 }
299
300
301 /**
302 * Try actually saving the thing...
303 * It will show an error form on failure. No it will not.
304 */
305 if( !$this->mForReUpload ) {
306 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
307 $this->mCopyrightStatus, $this->mCopyrightSource );
308 } else {
309 $pageText = false;
310 }
311 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $wgUser );
312
313 if ( !$status->isGood() ) {
314 return array( 'status' => UploadBase::INTERNAL_ERROR, 'internal' => $status );
315 } else {
316 // Success, redirect to description page
317 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
318 return UploadBase::SUCCESS;
319 }
320 }
321
322 /**
323 * Formats a result of UploadBase::getExistsWarning as HTML
324 * This check is static and can be done pre-upload via AJAX
325 *
326 * @param array $exists The result of UploadBase::getExistsWarning
327 * @return string Empty string if there is no warning or an HTML fragment
328 * consisting of one or more <li> elements if there is a warning.
329 */
330 public static function getExistsWarning( $exists ) {
331 global $wgUser, $wgContLang;
332
333 if ( !$exists )
334 return '';
335
336 $file = $exists['file'];
337 $filename = $file->getTitle()->getPrefixedText();
338 $warning = array();
339
340 $sk = $wgUser->getSkin();
341
342 if( $exists['warning'] == 'exists' ) {
343 // Exact match
344 $warning[] = '<li>' . wfMsgExt( 'fileexists', 'parseinline', $filename ) . '</li>';
345 } elseif( $exists['warning'] == 'page-exists' ) {
346 // Page exists but file does not
347 $warning[] = '<li>' . wfMsgExt( 'filepageexists', 'parseinline', $filename ) . '</li>';
348 } elseif ( $exists['warning'] == 'exists-normalized' ) {
349 $warning[] = '<li>' . wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
350 $exists['normalizedFile']->getTitle()->getPrefixedText() ) . '</li>';
351 } elseif ( $exists['warning'] == 'thumb' ) {
352 // Swapped argument order compared with other messages for backwards compatibility
353 $warning[] = '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
354 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename ) . '</li>';
355 } elseif ( $exists['warning'] == 'thumb-name' ) {
356 # Image w/o '180px-' does not exists, but we do not like these filenames
357 $name = $file->getName();
358 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
359 $warning[] = '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart ) . '</li>';
360 } elseif ( $exists['warning'] == 'bad-prefix' ) {
361 $warning[] = '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] ) . '</li>';
362 } elseif ( $exists['warning'] == 'was-deleted' ) {
363 # If the file existed before and was deleted, warn the user of this
364 $ltitle = SpecialPage::getTitleFor( 'Log' );
365 $llink = $sk->linkKnown(
366 $ltitle,
367 wfMsgHtml( 'deletionlog' ),
368 array(),
369 array(
370 'type' => 'delete',
371 'page' => $filename
372 )
373 );
374 $warning[] = '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
375 }
376
377 return implode( "\n", $warning );
378 }
379
380 /**
381 * Get a list of warnings
382 *
383 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
384 * @return array list of warning messages
385 */
386 static function ajaxGetExistsWarning( $filename ) {
387 $file = wfFindFile( $filename );
388 if( !$file ) {
389 // Force local file so we have an object to do further checks against
390 // if there isn't an exact match...
391 $file = wfLocalFile( $filename );
392 }
393 $s = '&nbsp;';
394 if ( $file ) {
395 $exists = UploadBase::getExistsWarning( $file );
396 $warning = self::getExistsWarning( $exists );
397 // FIXME: We probably also want the prefix blacklist and the wasdeleted check here
398 if ( $warning !== '' ) {
399 $s = "<ul>$warning</ul>";
400 }
401 }
402 return $s;
403 }
404
405 /**
406 * Render a preview of a given license for the AJAX preview on upload
407 *
408 * @param string $license
409 * @return string
410 */
411 public static function ajaxGetLicensePreview( $license ) {
412 global $wgParser, $wgUser;
413 $text = '{{' . $license . '}}';
414 $title = Title::makeTitle( NS_FILE, 'Sample.jpg' );
415 $options = ParserOptions::newFromUser( $wgUser );
416
417 // Expand subst: first, then live templates...
418 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
419 $output = $wgParser->parse( $text, $title, $options );
420
421 return $output->getText();
422 }
423
424 /**
425 * Construct the human readable warning message from an array of duplicate files
426 */
427 public static function getDupeWarning( $dupes ) {
428 if( $dupes ) {
429 global $wgOut;
430 $msg = "<gallery>";
431 foreach( $dupes as $file ) {
432 $title = $file->getTitle();
433 $msg .= $title->getPrefixedText() .
434 "|" . $title->getText() . "\n";
435 }
436 $msg .= "</gallery>";
437 return "<li>" .
438 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
439 $wgOut->parse( $msg ) .
440 "</li>\n";
441 } else {
442 return '';
443 }
444 }
445
446
447 /**
448 * Remove a temporarily kept file stashed by saveTempUploadedFile().
449 * @access private
450 * @return success
451 */
452 function unsaveUploadedFile() {
453 global $wgOut;
454 $success = $this->mUpload->unsaveUploadedFile();
455 if ( ! $success ) {
456 $wgOut->showFileDeleteError( $this->mUpload->getTempPath() );
457 return false;
458 } else {
459 return true;
460 }
461 }
462
463 /* Interface code starts below this line *
464 * -------------------------------------------------------------- */
465
466
467 /**
468 * @param string $error as HTML
469 * @access private
470 */
471 function uploadError( $error ) {
472 global $wgOut;
473 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
474 $wgOut->addHTML( '<span class="error">' . $error . '</span>' );
475 }
476
477 /**
478 * There's something wrong with this file, not enough to reject it
479 * totally but we require manual intervention to save it for real.
480 * Stash it away, then present a form asking to confirm or cancel.
481 *
482 * @param string $warning as HTML
483 * @access private
484 */
485 function uploadWarning( $warnings ) {
486 global $wgOut, $wgUser;
487 global $wgUseCopyrightUpload;
488
489 $this->mSessionKey = $this->mUpload->stashSession();
490
491 if( $this->mSessionKey === false ) {
492 # Couldn't save file; an error has been displayed so let's go.
493 return;
494 }
495
496 $sk = $wgUser->getSkin();
497
498 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
499 $wgOut->addHTML( '<ul class="warning">' );
500 foreach( $warnings as $warning => $args ) {
501 $msg = null;
502 if( $warning == 'exists' ) {
503
504 //we should not have produced this warning if the user already acknowledged the destination warning
505 //at any rate I don't see why we should hid this warning if mDestWarningAck has been checked
506 //(it produces an empty warning page when no other warnings are fired)
507 //if ( !$this->mDestWarningAck )
508 $msg = self::getExistsWarning( $args );
509
510 } elseif( $warning == 'duplicate' ) {
511 $msg = $this->getDupeWarning( $args );
512 } elseif( $warning == 'duplicate-archive' ) {
513 $titleText = Title::makeTitle( NS_FILE, $args )->getPrefixedText();
514 $msg = Xml::tags( 'li', null, wfMsgExt( 'file-deleted-duplicate', array( 'parseinline' ), array( $titleText ) ) );
515 } else {
516 if( is_bool( $args ) )
517 $args = array();
518 elseif( !is_array( $args ) )
519 $args = array( $args );
520 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
521 }
522 if( $msg )
523 $wgOut->addHTML( $msg );
524 }
525
526 $titleObj = SpecialPage::getTitleFor( 'Upload' );
527
528 if ( $wgUseCopyrightUpload ) {
529 $copyright = Xml::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus ) . "\n" .
530 Xml::hidden( 'wpUploadSource', $this->mCopyrightSource ) . "\n";
531 } else {
532 $copyright = '';
533 }
534 $wgOut->addHTML(
535 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
536 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
537 Xml::hidden('wpEditToken', $wgUser->editToken(), array("id" => 'wpEditToken')) .
538 Xml::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
539 Xml::hidden( 'wpSourceType', 'stash' ) . "\n" .
540 Xml::hidden( 'wpSessionKey', $this->mSessionKey ) . "\n" .
541 Xml::hidden( 'wpUploadDescription', $this->mComment ) . "\n" .
542 Xml::hidden( 'wpLicense', $this->mLicense ) . "\n" .
543 Xml::hidden( 'wpDestFile', $this->mDesiredDestName ) . "\n" .
544 Xml::hidden( 'wpWatchthis', $this->mWatchthis ) . "\n" .
545 "{$copyright}<br />" .
546 Xml::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
547 Xml::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
548 Xml::closeElement( 'form' ) . "\n"
549 );
550 }
551
552 /**
553 * Displays the main upload form, optionally with a highlighted
554 * error message up at the top.
555 *
556 * @param string $msg as HTML
557 * @access private
558 */
559 function mainUploadForm( $msg='' ) {
560 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize, $wgEnableFirefogg;
561 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
562 global $wgRequest;
563 global $wgStylePath, $wgStyleVersion;
564 global $wgEnableJS2system;
565
566 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
567 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
568
569 $adc = wfBoolToStr( $useAjaxDestCheck );
570 $alp = wfBoolToStr( $useAjaxLicensePreview );
571 $uef = wfBoolToStr( $wgEnableFirefogg );
572 $autofill = wfBoolToStr( $this->mDesiredDestName == '' );
573
574
575 $wgOut->addScript( "<script type=\"text/javascript\">
576 wgAjaxUploadDestCheck = {$adc};
577 wgAjaxLicensePreview = {$alp};
578 wgEnableFirefogg = {$uef};
579 wgUploadAutoFill = {$autofill};
580 </script>" );
581
582 if( $wgEnableJS2system ) {
583 //js2version of upload page:
584 $wgOut->addScriptClass( 'uploadPage' );
585 }else{
586 //legacy upload code:
587 $wgOut->addScriptFile( 'upload.js' );
588 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
589 }
590
591 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
592 {
593 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
594 return false;
595 }
596
597 if( $this->mDesiredDestName != '' ) {
598 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
599 // Show a subtitle link to deleted revisions (to sysops et al only)
600 if( $title instanceof Title && ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
601 $link = wfMsgExt(
602 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
603 array( 'parse', 'replaceafter' ),
604 $wgUser->getSkin()->linkKnown(
605 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
606 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
607 )
608 );
609 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
610 }
611
612 // Show the relevant lines from deletion log (for still deleted files only)
613 if( $title instanceof Title && $title->isDeletedQuick() && !$title->exists() ) {
614 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
615 }
616 }
617
618 $cols = intval($wgUser->getOption( 'cols' ));
619
620 if( $wgUser->getOption( 'editwidth' ) ) {
621 $width = " style=\"width:100%\"";
622 } else {
623 $width = '';
624 }
625
626 if ( '' != $msg ) {
627 $sub = wfMsgHtml( 'uploaderror' );
628 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
629 "<span class='error'>{$msg}</span>\n" );
630 }
631
632 $wgOut->addHTML( '<div id="uploadtext">' );
633 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName );
634 $wgOut->addHTML( "</div>\n" );
635
636 # Print a list of allowed file extensions, if so configured. We ignore
637 # MIME type here, it's incomprehensible to most people and too long.
638 global $wgCheckFileExtensions, $wgStrictFileExtensions,
639 $wgFileExtensions, $wgFileBlacklist;
640
641 $allowedExtensions = '';
642 if( $wgCheckFileExtensions ) {
643 if( $wgStrictFileExtensions ) {
644 # Everything not permitted is banned
645 $extensionsList =
646 '<div id="mw-upload-permitted">' .
647 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
648 "</div>\n";
649 } else {
650 # We have to list both preferred and prohibited
651 $extensionsList =
652 '<div id="mw-upload-preferred">' .
653 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
654 "</div>\n" .
655 '<div id="mw-upload-prohibited">' .
656 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileExtensions ) ) .
657 "</div>\n";
658 }
659 } else {
660 # Everything is permitted.
661 $extensionsList = '';
662 }
663
664 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
665 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
666 $val = wfShorthandToInteger( ini_get( 'upload_max_filesize' ) );
667 $maxUploadSize = '<div id="mw-upload-maxfilesize">' .
668 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
669 $wgLang->formatSize( $val ) ) .
670 "</div>\n";
671 //add a hidden filed for upload by url (uses the $wgMaxUploadSize var)
672 if( UploadFromUrl::isEnabled() ) {
673 $maxUploadSize.='<div id="mw-upload-maxfilesize-url" style="display:none">' .
674 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
675 $wgLang->formatSize( $wgMaxUploadSize ) ) .
676 "</div>\n";
677 }
678
679 $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
680 $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) );
681
682 $msg = ( $this->mForReUpload ) ? 'filereuploadsummary' : 'fileuploadsummary';
683 $summary = wfMsgExt( $msg, 'parseinline' );
684
685 $licenses = new Licenses();
686 $license = wfMsgExt( 'license', array( 'parseinline' ) );
687 $nolicense = wfMsgHtml( 'nolicense' );
688 $licenseshtml = $licenses->getHtml();
689
690 $ulb = wfMsgHtml( 'uploadbtn' );
691
692
693 $titleObj = SpecialPage::getTitleFor( 'Upload' );
694
695 $encDestName = htmlspecialchars( $this->mDesiredDestName );
696
697 $watchChecked = $this->watchCheck() ? 'checked="checked"' : '';
698 # Re-uploads should not need "file exist already" warnings
699 $warningChecked = ($this->mIgnoreWarning || $this->mForReUpload) ? 'checked="checked"' : '';
700
701 // Prepare form for upload or upload/copy
702 //javascript moved from inline calls to setup:
703 if( UploadFromUrl::isEnabled() && $wgUser->isAllowed( 'upload_by_url' ) ) {
704 if( $wgEnableJS2system ) {
705 $filename_form =
706 Xml::input( 'wpSourceType', false, 'file',
707 array( 'id' => 'wpSourceTypeFile', 'type' => 'radio', 'checked' => 'checked' ) ) .
708 Xml::input( 'wpUploadFile', 60, false,
709 array( 'id' => 'wpUploadFile', 'type' => 'file', 'tabindex' => '1' ) ) .
710 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
711 Xml::input( 'wpSourceType', false, 'Url',
712 array( 'id' => 'wpSourceTypeURL', 'type' => 'radio' ) ) .
713 Xml::input( 'wpUploadFileURL', 60, false,
714 array( 'id' => 'wpUploadFileURL', 'type' => 'text', 'tabindex' => '1' ) ) .
715 wfMsgHtml( 'upload_source_url' ) ;
716 } else {
717 //@@todo deprecate (not needed once $wgEnableJS2system is turned on)
718 $filename_form =
719 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
720 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
721 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
722 " onfocus='" .
723 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
724 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
725 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
726 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
727 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='Url' " .
728 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
729 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
730 "onfocus='" .
731 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
732 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
733 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' />" .
734 wfMsgHtml( 'upload_source_url' ) ;
735
736 }
737 } else {
738 if( $wgEnableJS2system ) {
739 $filename_form =
740 Xml::input( 'wpUploadFile', 60, false,
741 array( 'id' => 'wpUploadFile', 'type' => 'file', 'tabindex' => '1' ) ) .
742 Xml::hidden( 'wpSourceType', 'file');
743 } else {
744 $filename_form =
745 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' size='60' ".
746 "onchange='fillDestFilename(\"wpUploadFile\")' />" .
747 "<input type='hidden' name='wpSourceType' value='file' />" ;
748 }
749 }
750 $warningRow = '';
751 $destOnkeyup = '';
752 if( $wgEnableJS2system ) {
753 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'>&nbsp;</td></tr>";
754 } else {
755 if ( $useAjaxDestCheck ) {
756 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'>&nbsp;</td></tr>";
757 $destOnkeyup = 'onchange=\'wgUploadWarningObj.checkNow(this.value);\'';
758 }
759 }
760 # Uploading a new version? If so, the name is fixed.
761 $on = $this->mForReUpload ? "readonly='readonly'" : "";
762
763 $encComment = htmlspecialchars( $this->mComment );
764
765 //add the wpEditToken
766 $wgOut->addHTML(
767 Xml::openElement( 'form',
768 array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
769 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
770 Xml::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) .
771 Xml::openElement( 'fieldset' ) .
772 Xml::element( 'legend', null, wfMsg( 'upload' ) ) .
773 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
774 "<tr>
775 {$this->uploadFormTextTop}
776 <td class='mw-label'>
777 <label for='wpUploadFile'>{$sourcefilename}</label>
778 </td>
779 <td class='mw-input'>
780 {$filename_form}
781 </td>
782 </tr>
783 <tr>
784 <td></td>
785 <td>
786 {$maxUploadSize}
787 {$extensionsList}
788 </td>
789 </tr>
790 <tr>
791 <td class='mw-label'>
792 <label for='wpDestFile'>{$destfilename}</label>
793 </td>
794 <td class='mw-input'>"
795 );
796 if( $this->mForReUpload ) {
797 $wgOut->addHTML(
798 Xml::hidden( 'wpDestFile', $this->mDesiredDestName, array('id'=>'wpDestFile','tabindex'=>2) ) .
799 "<tt>" .
800 $encDestName .
801 "</tt>"
802 );
803 }
804 else {
805 $wgOut->addHTML(
806 "<input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
807 value=\"{$encDestName}\" $destOnkeyup />"
808 );
809 }
810
811
812 $wgOut->addHTML(
813 "</td>
814 </tr>
815 <tr>
816 <td class='mw-label'>
817 <label for='wpUploadDescription'>{$summary}</label>
818 </td>
819 <td class='mw-input'>
820 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
821 cols='{$cols}'{$width}>$encComment</textarea>
822 {$this->uploadFormTextAfterSummary}
823 </td>
824 </tr>
825 <tr>"
826 );
827
828 # Re-uploads should not need license info
829 if ( !$this->mForReUpload && $licenseshtml != '' ) {
830 global $wgStylePath;
831 $wgOut->addHTML( "
832 <td class='mw-label'>
833 <label for='wpLicense'>$license</label>
834 </td>
835 <td class='mw-input'>
836 <select name='wpLicense' id='wpLicense' tabindex='4'
837 onchange='licenseSelectorCheck()'>
838 <option value=''>$nolicense</option>
839 $licenseshtml
840 </select>
841 </td>
842 </tr>
843 <tr>"
844 );
845 if( $useAjaxLicensePreview ) {
846 $wgOut->addHTML( "
847 <td></td>
848 <td id=\"mw-license-preview\"></td>
849 </tr>
850 <tr>"
851 );
852 }
853 }
854
855 if ( !$this->mForReUpload && $wgUseCopyrightUpload ) {
856 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
857 $copystatus = htmlspecialchars( $this->mCopyrightStatus );
858 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
859 $uploadsource = htmlspecialchars( $this->mCopyrightSource );
860
861 $wgOut->addHTML( "
862 <td class='mw-label' style='white-space: nowrap;'>
863 <label for='wpUploadCopyStatus'>$filestatus</label></td>
864 <td class='mw-input'>
865 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
866 value=\"$copystatus\" size='60' />
867 </td>
868 </tr>
869 <tr>
870 <td class='mw-label'>
871 <label for='wpUploadCopyStatus'>$filesource</label>
872 </td>
873 <td class='mw-input'>
874 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
875 value=\"$uploadsource\" size='60' />
876 </td>
877 </tr>
878 <tr>"
879 );
880 }
881
882 $wgOut->addHTML( "
883 <td></td>
884 <td>
885 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
886 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
887 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked />
888 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
889 </td>
890 </tr>
891 $warningRow
892 <tr>
893 <td></td>
894 <td class='mw-input'>
895 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" .
896 $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
897 </td>
898 </tr>
899 <tr>
900 <td></td>
901 <td class='mw-input'>"
902 );
903 $wgOut->addHTML( '<div class="mw-editTools">' );
904 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
905 $wgOut->addHTML( '</div>' );
906 $wgOut->addHTML( "
907 </td>
908 </tr>" .
909 Xml::closeElement( 'table' ) .
910 Xml::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
911 Xml::hidden( 'wpForReUpload', $this->mForReUpload, array( 'id' => 'wpForReUpload' ) ) .
912 Xml::closeElement( 'fieldset' ) .
913 Xml::closeElement( 'form' )
914 );
915 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
916 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
917 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
918 }
919 }
920
921 /* -------------------------------------------------------------- */
922
923 /**
924 * See if we should check the 'watch this page' checkbox on the form
925 * based on the user's preferences and whether we're being asked
926 * to create a new file or update an existing one.
927 *
928 * In the case where 'watch edits' is off but 'watch creations' is on,
929 * we'll leave the box unchecked.
930 *
931 * Note that the page target can be changed *on the form*, so our check
932 * state can get out of sync.
933 */
934 function watchCheck() {
935 global $wgUser;
936 if( $wgUser->getOption( 'watchdefault' ) ) {
937 // Watch all edits!
938 return true;
939 }
940
941 $local = wfLocalFile( $this->mDesiredDestName );
942 if( $local && $local->exists() ) {
943 // We're uploading a new version of an existing file.
944 // No creation, so don't watch it if we're not already.
945 return $local->getTitle()->userIsWatching();
946 } else {
947 // New page should get watched if that's our option.
948 return $wgUser->getOption( 'watchcreations' );
949 }
950 }
951
952 /**
953 * Check if a user is the last uploader
954 *
955 * @param User $user
956 * @param string $img, image name
957 * @return bool
958 * @deprecated Use UploadBase::userCanReUpload
959 */
960 public static function userCanReUpload( User $user, $img ) {
961 wfDeprecated( __METHOD__ );
962
963 if( $user->isAllowed( 'reupload' ) )
964 return true; // non-conditional
965 if( !$user->isAllowed( 'reupload-own' ) )
966 return false;
967
968 $dbr = wfGetDB( DB_SLAVE );
969 $row = $dbr->selectRow('image',
970 /* SELECT */ 'img_user',
971 /* WHERE */ array( 'img_name' => $img )
972 );
973 if ( !$row )
974 return false;
975
976 return $user->getId() == $row->img_user;
977 }
978
979 /**
980 * Display an error with a wikitext description
981 */
982 function showError( $description ) {
983 global $wgOut;
984 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
985 $wgOut->setRobotPolicy( "noindex,nofollow" );
986 $wgOut->setArticleRelated( false );
987 $wgOut->enableClientCache( false );
988 $wgOut->addWikiText( $description );
989 }
990
991 /**
992 * Get the initial image page text based on a comment and optional file status information
993 */
994 static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
995 global $wgUseCopyrightUpload;
996 if ( $wgUseCopyrightUpload ) {
997 $licensetxt = '';
998 if ( $license != '' ) {
999 $licensetxt = '== ' . wfMsgForContent( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1000 }
1001 $pageText = '== ' . wfMsgForContent ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1002 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1003 "$licensetxt" .
1004 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1005 } else {
1006 if ( $license != '' ) {
1007 $filedesc = $comment == '' ? '' : '== ' . wfMsgForContent ( 'filedesc' ) . " ==\n" . $comment . "\n";
1008 $pageText = $filedesc .
1009 '== ' . wfMsgForContent ( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1010 } else {
1011 $pageText = $comment;
1012 }
1013 }
1014 return $pageText;
1015 }
1016
1017 /**
1018 * If there are rows in the deletion log for this file, show them,
1019 * along with a nice little note for the user
1020 *
1021 * @param OutputPage $out
1022 * @param string filename
1023 */
1024 private function showDeletionLog( $out, $filename ) {
1025 global $wgUser;
1026 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1027 $pager = new LogPager( $loglist, 'delete', false, $filename );
1028 if( $pager->getNumRows() > 0 ) {
1029 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1030 $out->addWikiMsg( 'upload-wasdeleted' );
1031 $out->addHTML(
1032 $loglist->beginLogEventsList() .
1033 $pager->getBody() .
1034 $loglist->endLogEventsList()
1035 );
1036 $out->addHTML( '</div>' );
1037 }
1038 }
1039 }