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