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