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