fixed unset partname
[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 # Check permissions
98 if( $this->mUpload ) {
99 $permission = $this->mUpload->isAllowed( $wgUser );
100 } else {
101 $permission = $wgUser->isAllowed( 'upload' ) ? true : 'upload';
102 }
103 if( $permission !== true ) {
104 if( !$wgUser->isLoggedIn() ) {
105 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
106 } else {
107 $wgOut->permissionRequired( $permission );
108 }
109 return;
110 }
111
112 # Check blocks
113 if( $wgUser->isBlocked() ) {
114 $wgOut->blockedPage();
115 return;
116 }
117
118 if( wfReadOnly() ) {
119 $wgOut->readOnlyPage();
120 return;
121 }
122 //check token if uploading or reUploading
123 if( !$this->mTokenOk && !$this->mReUpload && ($this->mUpload && (
124 'submit' == $this->mAction ||
125 $this->mUploadClicked
126 )
127 )
128 ){
129 $this->mainUploadForm ( wfMsg( 'session_fail_preview' ) );
130 return ;
131 }
132
133
134 if( $this->mReUpload ) {
135 // User choose to cancel upload
136 if( !$this->mUpload->unsaveUploadedFile() ) {
137 return;
138 }
139 # Because it is probably checked and shouldn't be
140 $this->mIgnoreWarning = false;
141 $this->mainUploadForm();
142 } elseif( $this->mUpload && (
143 'submit' == $this->mAction ||
144 $this->mUploadClicked
145 ) ) {
146 $this->processUpload();
147 } else {
148 $this->mainUploadForm();
149 }
150
151 if( $this->mUpload )
152 $this->mUpload->cleanupTempFile();
153 }
154
155 /**
156 * Do the upload
157 * Checks are made in SpecialUpload::execute()
158 *
159 * FIXME this should really use the standard Status class (instead of associative array)
160 * FIXME would be nice if we refactored this into the upload api.
161 * (the special upload page is not the only response point that needs clean localized error msgs)
162 *
163 * @access private
164 */
165 function processUpload(){
166 global $wgOut, $wgFileExtensions, $wgLang;
167 $details = $this->internalProcessUpload();
168 switch( $details['status'] ) {
169 case UploadBase::SUCCESS:
170 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
171 break;
172
173 case UploadBase::BEFORE_PROCESSING:
174 $this->uploadError( $details['error'] );
175 break;
176 case UploadBase::LARGE_FILE_SERVER:
177 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
178 break;
179
180 case UploadBase::EMPTY_FILE:
181 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
182 break;
183
184 case UploadBase::MIN_LENGTH_PARTNAME:
185 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
186 break;
187
188 case UploadBase::ILLEGAL_FILENAME:
189 $this->uploadError( wfMsgExt( 'illegalfilename',
190 'parseinline', $details['filtered'] ) );
191 break;
192
193 case UploadBase::PROTECTED_PAGE:
194 $wgOut->showPermissionsErrorPage( $details['permissionserrors'] );
195 break;
196
197 case UploadBase::OVERWRITE_EXISTING_FILE:
198 $this->uploadError( wfMsgExt( $details['overwrite'],
199 'parseinline' ) );
200 break;
201
202 case UploadBase::FILETYPE_MISSING:
203 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
204 break;
205
206 case UploadBase::FILETYPE_BADTYPE:
207 $finalExt = $details['finalExt'];
208 $this->uploadError(
209 wfMsgExt( 'filetype-banned-type',
210 array( 'parseinline' ),
211 htmlspecialchars( $finalExt ),
212 implode(
213 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
214 $wgFileExtensions
215 ),
216 $wgLang->formatNum( count( $wgFileExtensions ) )
217 )
218 );
219 break;
220
221 case UploadBase::VERIFICATION_ERROR:
222 unset( $details['status'] );
223 $code = array_shift( $details );
224 $this->uploadError( wfMsgExt( $code, 'parseinline', $details ) );
225 break;
226
227 case UploadBase::UPLOAD_VERIFICATION_ERROR:
228 $error = $details['error'];
229 $this->uploadError( wfMsgExt( $error, 'parseinline' ) );
230 break;
231
232 case UploadBase::UPLOAD_WARNING:
233 unset( $details['status'] );
234 $this->uploadWarning( $details );
235 break;
236
237 case UploadBase::INTERNAL_ERROR:
238 $status = $details['internal'];
239 $this->showError( $wgOut->parse( $status->getWikiText() ) );
240 break;
241
242 default:
243 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
244 }
245 }
246
247 /**
248 * Really do the upload
249 * Checks are made in SpecialUpload::execute()
250 *
251 * @param array $resultDetails contains result-specific dict of additional values
252 *
253 * @access private
254 */
255 function internalProcessUpload() {
256 global $wgUser;
257
258 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
259 {
260 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
261 return array( 'status' => UploadBase::BEFORE_PROCESSING );
262 }
263
264 /**
265 * If the image is protected, non-sysop users won't be able
266 * to modify it by uploading a new revision.
267 */
268 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
269 if( $permErrors !== true ) {
270 return array( 'status' => UploadBase::PROTECTED_PAGE, 'permissionserrors' => $permErrors );
271 }
272
273 // Fetch the file if required
274 $status = $this->mUpload->fetchFile();
275 if( !$status->isOK() ){
276 return array( 'status' =>UploadBase::BEFORE_PROCESSING, 'error'=>$status->getWikiText() );
277 }
278
279 // Check whether this is a sane upload
280 $result = $this->mUpload->verifyUpload();
281 if( $result != UploadBase::OK )
282 return $result;
283
284 $this->mLocalFile = $this->mUpload->getLocalFile();
285
286 if( !$this->mIgnoreWarning ) {
287 $warnings = $this->mUpload->checkWarnings();
288
289 if( count( $warnings ) ) {
290 $warnings['status'] = UploadBase::UPLOAD_WARNING;
291 return $warnings;
292 }
293 }
294
295
296 /**
297 * Try actually saving the thing...
298 * It will show an error form on failure. No it will not.
299 */
300 if( !$this->mForReUpload ) {
301 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
302 $this->mCopyrightStatus, $this->mCopyrightSource );
303 }
304 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $wgUser );
305
306 if ( !$status->isGood() ) {
307 return array( 'status' => UploadBase::INTERNAL_ERROR, 'internal' => $status );
308 } else {
309 // Success, redirect to description page
310 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
311 return UploadBase::SUCCESS;
312 }
313 }
314
315 /**
316 * Do existence checks on a file and produce a warning
317 * This check is static and can be done pre-upload via AJAX
318 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
319 * Returns an empty string if there is no warning
320 */
321 static function getExistsWarning( $exists ) {
322 global $wgUser, $wgContLang;
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->makeKnownLinkObj( $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->makeKnownLinkObj( $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( $sessionData === 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 //add the wpEditToken
595 $token = htmlspecialchars( $wgUser->editToken() );
596 $wgOut->addHTML(
597 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
598 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
599 Xml::hidden('wpEditToken', $token) .
600 Xml::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
601 Xml::hidden( 'wpSourceType', 'stash' ) . "\n" .
602 Xml::hidden( 'wpSessionKey', $this->mSessionKey ) . "\n" .
603 Xml::hidden( 'wpUploadDescription', $this->mComment ) . "\n" .
604 Xml::hidden( 'wpLicense', $this->mLicense ) . "\n" .
605 Xml::hidden( 'wpDestFile', $this->mDesiredDestName ) . "\n" .
606 Xml::hidden( 'wpWatchthis', $this->mWatchthis ) . "\n" .
607 "{$copyright}<br />" .
608 Xml::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
609 Xml::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
610 Xml::closeElement( 'form' ) . "\n"
611 );
612 }
613
614 /**
615 * Displays the main upload form, optionally with a highlighted
616 * error message up at the top.
617 *
618 * @param string $msg as HTML
619 * @access private
620 */
621 function mainUploadForm( $msg='' ) {
622 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize, $wgEnableFirefogg;
623 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
624 global $wgRequest;
625 global $wgStylePath, $wgStyleVersion;
626 global $wgEnableJS2system;
627
628 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
629 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
630
631 $adc = wfBoolToStr( $useAjaxDestCheck );
632 $alp = wfBoolToStr( $useAjaxLicensePreview );
633 $uef = wfBoolToStr( $wgEnableFirefogg );
634 $autofill = wfBoolToStr( $this->mDesiredDestName == '' );
635
636
637 $wgOut->addScript( "<script type=\"text/javascript\">
638 wgAjaxUploadDestCheck = {$adc};
639 wgAjaxLicensePreview = {$alp};
640 wgEnableFirefogg = {$uef};
641 wgUploadAutoFill = {$autofill};
642 </script>" );
643
644 if( $wgEnableJS2system ){
645 //js2version of upload page:
646 $wgOut->addScriptClass( 'uploadPage' );
647 }else{
648 //legacy upload code:
649 $wgOut->addScriptFile( 'upload.js' );
650 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
651 }
652
653 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
654 {
655 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
656 return false;
657 }
658
659 if( $this->mDesiredDestName ) {
660 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
661 // Show a subtitle link to deleted revisions (to sysops et al only)
662 if( $title instanceof Title && ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
663 $link = wfMsgExt(
664 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
665 array( 'parse', 'replaceafter' ),
666 $wgUser->getSkin()->makeKnownLinkObj(
667 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
668 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
669 )
670 );
671 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
672 }
673
674 // Show the relevant lines from deletion log (for still deleted files only)
675 if( $title instanceof Title && $title->isDeletedQuick() && !$title->exists() ) {
676 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
677 }
678 }
679
680 $cols = intval($wgUser->getOption( 'cols' ));
681
682 if( $wgUser->getOption( 'editwidth' ) ) {
683 $width = " style=\"width:100%\"";
684 } else {
685 $width = '';
686 }
687
688 if ( '' != $msg ) {
689 $sub = wfMsgHtml( 'uploaderror' );
690 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
691 "<span class='error'>{$msg}</span>\n" );
692 }
693
694 $wgOut->addHTML( '<div id="uploadtext">' );
695 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName );
696 $wgOut->addHTML( "</div>\n" );
697
698 # Print a list of allowed file extensions, if so configured. We ignore
699 # MIME type here, it's incomprehensible to most people and too long.
700 global $wgCheckFileExtensions, $wgStrictFileExtensions,
701 $wgFileExtensions, $wgFileBlacklist;
702
703 $allowedExtensions = '';
704 if( $wgCheckFileExtensions ) {
705 $delim = wfMsgExt( 'comma-separator', array( 'escapenoentities' ) );
706 if( $wgStrictFileExtensions ) {
707 # Everything not permitted is banned
708 $extensionsList =
709 '<div id="mw-upload-permitted">' .
710 wfMsgWikiHtml( 'upload-permitted', implode( $wgFileExtensions, $delim ) ) .
711 "</div>\n";
712 } else {
713 # We have to list both preferred and prohibited
714 $extensionsList =
715 '<div id="mw-upload-preferred">' .
716 wfMsgWikiHtml( 'upload-preferred', implode( $wgFileExtensions, $delim ) ) .
717 "</div>\n" .
718 '<div id="mw-upload-prohibited">' .
719 wfMsgWikiHtml( 'upload-prohibited', implode( $wgFileBlacklist, $delim ) ) .
720 "</div>\n";
721 }
722 } else {
723 # Everything is permitted.
724 $extensionsList = '';
725 }
726
727 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
728 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
729 $val = trim( ini_get( 'upload_max_filesize' ) );
730 $last = strtoupper( ( substr( $val, -1 ) ) );
731 switch( $last ) {
732 case 'G':
733 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
734 break;
735 case 'M':
736 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
737 break;
738 case 'K':
739 $val2 = substr( $val, 0, -1 ) * 1024;
740 break;
741 default:
742 $val2 = $val;
743 }
744 $maxUploadSize = '<div id="mw-upload-maxfilesize">' .
745 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
746 $wgLang->formatSize( $val2 ) ) .
747 "</div>\n";
748 //add a hidden filed for upload by url (uses the $wgMaxUploadSize var)
749 if( UploadFromUrl::isEnabled() ){
750 $maxUploadSize.='<div id="mw-upload-maxfilesize-url" style="display:none">' .
751 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
752 $wgLang->formatSize( $wgMaxUploadSize ) ) .
753 "</div>\n";
754 }
755
756 $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
757 $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) );
758
759 $msg = ( $this->mForReUpload ) ? 'filereuploadsummary' : 'fileuploadsummary';
760 $summary = wfMsgExt( $msg, 'parseinline' );
761
762 $licenses = new Licenses();
763 $license = wfMsgExt( 'license', array( 'parseinline' ) );
764 $nolicense = wfMsgHtml( 'nolicense' );
765 $licenseshtml = $licenses->getHtml();
766
767 $ulb = wfMsgHtml( 'uploadbtn' );
768
769
770 $titleObj = SpecialPage::getTitleFor( 'Upload' );
771
772 $encDestName = htmlspecialchars( $this->mDesiredDestName );
773
774 $watchChecked = $this->watchCheck() ? 'checked="checked"' : '';
775 # Re-uploads should not need "file exist already" warnings
776 $warningChecked = ($this->mIgnoreWarning || $this->mForReUpload) ? 'checked="checked"' : '';
777
778 // Prepare form for upload or upload/copy
779 //javascript moved from inline calls to setup:
780 if( UploadFromUrl::isEnabled() && $wgUser->isAllowed( 'upload_by_url' ) ) {
781 if($wgEnableJS2system){
782 $filename_form =
783 Xml::input( 'wpSourceType', false, 'file', array( 'id'=>'wpSourceTypeFile', 'type' => 'radio', 'checked' => 'checked' ) ) .
784 Xml::input( 'wpUploadFile', 60, false, array( 'id'=>'wpUploadFile', 'type'=>'file', 'tabindex' => '1' ) ) .
785 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
786 Xml::input( 'wpSourceType', false, 'Url', array( 'id'=>'wpSourceTypeURL', 'type' => 'radio' )) .
787 Xml::input( 'wpUploadFileURL', 60, false, array( 'id'=>'wpUploadFileURL', 'type' => 'text', 'tabindex' => '1')) .
788 wfMsgHtml( 'upload_source_url' ) ;
789 }else{
790 //@@todo depreciate (not needed once $wgEnableJS2system is turned on)
791 $filename_form =
792 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
793 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
794 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
795 "onfocus='" .
796 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
797 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
798 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
799 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
800 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='Url' " .
801 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
802 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
803 "onfocus='" .
804 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
805 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
806 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
807 wfMsgHtml( 'upload_source_url' ) ;
808
809 }
810 } else {
811 $filename_form =
812 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' size='60' />" .
813 "<input type='hidden' name='wpSourceType' value='upload' />" ;
814 }
815
816 if ( $useAjaxDestCheck ) {
817 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'>&nbsp;</td></tr>";
818 $destOnkeyup = '';
819 } else {
820 $warningRow = '';
821 $destOnkeyup = '';
822 }
823 # Uploading a new version? If so, the name is fixed.
824 $on = $this->mForReUpload ? "readonly='readonly'" : "";
825
826 $encComment = htmlspecialchars( $this->mComment );
827
828 //add the wpEditToken
829 $token = htmlspecialchars( $wgUser->editToken() );
830 $wgOut->addHTML(
831 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
832 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
833 Xml::hidden('wpEditToken', $token) .
834 Xml::openElement( 'fieldset' ) .
835 Xml::element( 'legend', null, wfMsg( 'upload' ) ) .
836 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
837 "<tr>
838 {$this->uploadFormTextTop}
839 <td class='mw-label'>
840 <label for='wpUploadFile'>{$sourcefilename}</label>
841 </td>
842 <td class='mw-input'>
843 {$filename_form}
844 </td>
845 </tr>
846 <tr>
847 <td></td>
848 <td>
849 {$maxUploadSize}
850 {$extensionsList}
851 </td>
852 </tr>
853 <tr>
854 <td class='mw-label'>
855 <label for='wpDestFile'>{$destfilename}</label>
856 </td>
857 <td class='mw-input'>"
858 );
859 if( $this->mForReUpload ) {
860 $wgOut->addHTML(
861 Xml::hidden( 'wpDestFile', $this->mDesiredDestName, array('id'=>'wpDestFile','tabindex'=>2) ) .
862 "<tt>" .
863 $encDestName .
864 "</tt>"
865 );
866 }
867 else {
868 $wgOut->addHTML(
869 "<input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
870 value=\"{$encDestName}\" $destOnkeyup />"
871 );
872 }
873
874
875 $wgOut->addHTML(
876 "</td>
877 </tr>
878 <tr>
879 <td class='mw-label'>
880 <label for='wpUploadDescription'>{$summary}</label>
881 </td>
882 <td class='mw-input'>
883 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
884 cols='{$cols}'{$width}>$encComment</textarea>
885 {$this->uploadFormTextAfterSummary}
886 </td>
887 </tr>
888 <tr>"
889 );
890
891 # Re-uploads should not need license info
892 if ( !$this->mForReUpload && $licenseshtml != '' ) {
893 global $wgStylePath;
894 $wgOut->addHTML( "
895 <td class='mw-label'>
896 <label for='wpLicense'>$license</label>
897 </td>
898 <td class='mw-input'>
899 <select name='wpLicense' id='wpLicense' tabindex='4'
900 onchange='licenseSelectorCheck()'>
901 <option value=''>$nolicense</option>
902 $licenseshtml
903 </select>
904 </td>
905 </tr>
906 <tr>"
907 );
908 if( $useAjaxLicensePreview ) {
909 $wgOut->addHTML( "
910 <td></td>
911 <td id=\"mw-license-preview\"></td>
912 </tr>
913 <tr>"
914 );
915 }
916 }
917
918 if ( !$this->mForReUpload && $wgUseCopyrightUpload ) {
919 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
920 $copystatus = htmlspecialchars( $this->mCopyrightStatus );
921 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
922 $uploadsource = htmlspecialchars( $this->mCopyrightSource );
923
924 $wgOut->addHTML( "
925 <td class='mw-label' style='white-space: nowrap;'>
926 <label for='wpUploadCopyStatus'>$filestatus</label></td>
927 <td class='mw-input'>
928 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
929 value=\"$copystatus\" size='60' />
930 </td>
931 </tr>
932 <tr>
933 <td class='mw-label'>
934 <label for='wpUploadCopyStatus'>$filesource</label>
935 </td>
936 <td class='mw-input'>
937 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
938 value=\"$uploadsource\" size='60' />
939 </td>
940 </tr>
941 <tr>"
942 );
943 }
944
945 $wgOut->addHTML( "
946 <td></td>
947 <td>
948 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
949 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
950 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked />
951 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
952 </td>
953 </tr>
954 $warningRow
955 <tr>
956 <td></td>
957 <td class='mw-input'>
958 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" .
959 $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
960 </td>
961 </tr>
962 <tr>
963 <td></td>
964 <td class='mw-input'>"
965 );
966 $wgOut->addHTML( '<div class="mw-editTools">' );
967 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
968 $wgOut->addHTML( '</div>' );
969 $wgOut->addHTML( "
970 </td>
971 </tr>" .
972 Xml::closeElement( 'table' ) .
973 Xml::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
974 Xml::hidden( 'wpForReUpload', $this->mForReUpload, array( 'id' => 'wpForReUpload' ) ) .
975 Xml::closeElement( 'fieldset' ) .
976 Xml::closeElement( 'form' )
977 );
978 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
979 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
980 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
981 }
982 }
983
984 /* -------------------------------------------------------------- */
985
986 /**
987 * See if we should check the 'watch this page' checkbox on the form
988 * based on the user's preferences and whether we're being asked
989 * to create a new file or update an existing one.
990 *
991 * In the case where 'watch edits' is off but 'watch creations' is on,
992 * we'll leave the box unchecked.
993 *
994 * Note that the page target can be changed *on the form*, so our check
995 * state can get out of sync.
996 */
997 function watchCheck() {
998 global $wgUser;
999 if( $wgUser->getOption( 'watchdefault' ) ) {
1000 // Watch all edits!
1001 return true;
1002 }
1003
1004 $local = wfLocalFile( $this->mDesiredDestName );
1005 if( $local && $local->exists() ) {
1006 // We're uploading a new version of an existing file.
1007 // No creation, so don't watch it if we're not already.
1008 return $local->getTitle()->userIsWatching();
1009 } else {
1010 // New page should get watched if that's our option.
1011 return $wgUser->getOption( 'watchcreations' );
1012 }
1013 }
1014
1015 /**
1016 * Check if a user is the last uploader
1017 *
1018 * @param User $user
1019 * @param string $img, image name
1020 * @return bool
1021 * @deprecated Use UploadBase::userCanReUpload
1022 */
1023 public static function userCanReUpload( User $user, $img ) {
1024 wfDeprecated( __METHOD__ );
1025
1026 if( $user->isAllowed( 'reupload' ) )
1027 return true; // non-conditional
1028 if( !$user->isAllowed( 'reupload-own' ) )
1029 return false;
1030
1031 $dbr = wfGetDB( DB_SLAVE );
1032 $row = $dbr->selectRow('image',
1033 /* SELECT */ 'img_user',
1034 /* WHERE */ array( 'img_name' => $img )
1035 );
1036 if ( !$row )
1037 return false;
1038
1039 return $user->getId() == $row->img_user;
1040 }
1041
1042 /**
1043 * Display an error with a wikitext description
1044 */
1045 function showError( $description ) {
1046 global $wgOut;
1047 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1048 $wgOut->setRobotPolicy( "noindex,nofollow" );
1049 $wgOut->setArticleRelated( false );
1050 $wgOut->enableClientCache( false );
1051 $wgOut->addWikiText( $description );
1052 }
1053
1054 /**
1055 * Get the initial image page text based on a comment and optional file status information
1056 */
1057 static function getInitialPageText( $comment='', $license='', $copyStatus='', $source='' ) {
1058 global $wgUseCopyrightUpload;
1059 if ( $wgUseCopyrightUpload ) {
1060 if ( $license != '' ) {
1061 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1062 }
1063 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1064 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1065 "$licensetxt" .
1066 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1067 } else {
1068 if ( $license != '' ) {
1069 $filedesc = $comment == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1070 $pageText = $filedesc .
1071 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1072 } else {
1073 $pageText = $comment;
1074 }
1075 }
1076 return $pageText;
1077 }
1078
1079 /**
1080 * If there are rows in the deletion log for this file, show them,
1081 * along with a nice little note for the user
1082 *
1083 * @param OutputPage $out
1084 * @param string filename
1085 */
1086 private function showDeletionLog( $out, $filename ) {
1087 global $wgUser;
1088 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1089 $pager = new LogPager( $loglist, 'delete', false, $filename );
1090 if( $pager->getNumRows() > 0 ) {
1091 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1092 $out->addWikiMsg( 'upload-wasdeleted' );
1093 $out->addHTML(
1094 $loglist->beginLogEventsList() .
1095 $pager->getBody() .
1096 $loglist->endLogEventsList()
1097 );
1098 $out->addHTML( '</div>' );
1099 }
1100 }
1101 }