49bac540f1aa662744a55c81104d1bfc6c1b593f
[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 } else {
300 $pageText = false;
301 }
302 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $wgUser );
303
304 if ( !$status->isGood() ) {
305 return array( 'status' => UploadBase::INTERNAL_ERROR, 'internal' => $status );
306 } else {
307 // Success, redirect to description page
308 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
309 return UploadBase::SUCCESS;
310 }
311 }
312
313 /**
314 * Do existence checks on a file and produce a warning
315 * This check is static and can be done pre-upload via AJAX
316 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
317 * Returns an empty string if there is no warning
318 */
319 static function getExistsWarning( $exists ) {
320 global $wgUser, $wgContLang;
321 // Check for uppercase extension. We allow these filenames but check if an image
322 // with lowercase extension exists already
323 $warning = '';
324 $align = $wgContLang->isRtl() ? 'left' : 'right';
325
326 if( $exists === false )
327 return '';
328
329 $warning = '';
330 $align = $wgContLang->isRtl() ? 'left' : 'right';
331
332 list( $existsType, $file ) = $exists;
333
334 $sk = $wgUser->getSkin();
335
336 if( $existsType == 'exists' ) {
337 // Exact match
338 $dlink = $sk->linkKnown( $file->getTitle() );
339 if ( $file->allowInlineDisplay() ) {
340 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
341 $file->getName(), $align, array(), false, true );
342 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
343 $icon = $file->iconThumb();
344 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
345 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
346 } else {
347 $dlink2 = '';
348 }
349
350 $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
351
352 } elseif( $existsType == 'page-exists' ) {
353 $lnk = $sk->linkKnown( $file->getTitle(), '', '',array('redirect'=>'no') );
354 $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
355 } elseif ( $existsType == 'exists-normalized' ) {
356 # Check if image with lowercase extension exists.
357 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
358 $dlink = $sk->linkKnown( $nt_lc );
359 if ( $file_lc->allowInlineDisplay() ) {
360 // FIXME: replace deprecated makeImageLinkObj by link()
361 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline' ),
362 $nt_lc->getText(), $align, array(), false, true );
363 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
364 $icon = $file_lc->iconThumb();
365 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
366 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
367 } else {
368 $dlink2 = '';
369 }
370
371 $warning .= '<li>' .
372 wfMsgExt( 'fileexists-extension', 'parsemag',
373 $file->getTitle()->getPrefixedText(), $dlink ) .
374 '</li>' . $dlink2;
375
376 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' || substr( $partname , 2, 3 ) == 'px-' )
377 && preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) ) )
378 {
379 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
380 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $rawExtension );
381 $file_thb = wfLocalFile( $nt_thb );
382 if ($file_thb->exists() ) {
383 # Check if an image without leading '180px-' (or similiar) exists
384 $dlink = $sk->linkKnown( $nt_thb );
385 if ( $file_thb->allowInlineDisplay() ) {
386 // FIXME: replace deprecated makeImageLinkObj by link()
387 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
388 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
389 $nt_thb->getText(), $align, array(), false, true );
390 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
391 $icon = $file_thb->iconThumb();
392 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
393 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
394 $dlink . '</div>';
395 } else {
396 $dlink2 = '';
397 }
398
399 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
400 '</li>' . $dlink2;
401 } else {
402 # Image w/o '180px-' does not exists, but we do not like these filenames
403 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
404 substr( $partname , 0, strpos( $partname , '-' ) +1 ) ) . '</li>';
405 }
406 }
407
408 $filenamePrefixBlacklist = UploadBase::getFilenamePrefixBlacklist();
409 # Do the match
410 if(!isset($partname))
411 $partname = '';
412 foreach( $filenamePrefixBlacklist as $prefix ) {
413 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
414 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
415 break;
416 }
417 }
418
419 if ( $file->wasDeleted() && !$file->exists() ) {
420 # If the file existed before and was deleted, warn the user of this
421 # Don't bother doing so if the file exists now, however
422 $ltitle = SpecialPage::getTitleFor( 'Log' );
423 $llink = $sk->linkKnown(
424 $ltitle,
425 wfMsgHtml( 'deletionlog' ),
426 array(),
427 array(
428 'type' => 'delete',
429 'page' => $file->getTitle()->getPrefixedText()
430 )
431 );
432 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
433 }
434 return $warning;
435 }
436
437 /**
438 * Get a list of warnings
439 *
440 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
441 * @return array list of warning messages
442 */
443 static function ajaxGetExistsWarning( $filename ) {
444 $file = wfFindFile( $filename );
445 if( !$file ) {
446 // Force local file so we have an object to do further checks against
447 // if there isn't an exact match...
448 $file = wfLocalFile( $filename );
449 }
450 $s = '&nbsp;';
451 if ( $file ) {
452 $exists = UploadBase::getExistsWarning( $file );
453 $warning = self::getExistsWarning( $exists );
454 // FIXME: We probably also want the prefix blacklist and the wasdeleted check here
455 if ( $warning !== '' ) {
456 $s = "<ul>$warning</ul>";
457 }
458 }
459 return $s;
460 }
461
462 /**
463 * Render a preview of a given license for the AJAX preview on upload
464 *
465 * @param string $license
466 * @return string
467 */
468 public static function ajaxGetLicensePreview( $license ) {
469 global $wgParser, $wgUser;
470 $text = '{{' . $license . '}}';
471 $title = Title::makeTitle( NS_FILE, 'Sample.jpg' );
472 $options = ParserOptions::newFromUser( $wgUser );
473
474 // Expand subst: first, then live templates...
475 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
476 $output = $wgParser->parse( $text, $title, $options );
477
478 return $output->getText();
479 }
480
481 /**
482 * Construct the human readable warning message from an array of duplicate files
483 */
484 public static function getDupeWarning( $dupes ) {
485 if( $dupes ) {
486 global $wgOut;
487 $msg = "<gallery>";
488 foreach( $dupes as $file ) {
489 $title = $file->getTitle();
490 $msg .= $title->getPrefixedText() .
491 "|" . $title->getText() . "\n";
492 }
493 $msg .= "</gallery>";
494 return "<li>" .
495 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
496 $wgOut->parse( $msg ) .
497 "</li>\n";
498 } else {
499 return '';
500 }
501 }
502
503
504 /**
505 * Remove a temporarily kept file stashed by saveTempUploadedFile().
506 * @access private
507 * @return success
508 */
509 function unsaveUploadedFile() {
510 global $wgOut;
511 $success = $this->mUpload->unsaveUploadedFile();
512 if ( ! $success ) {
513 $wgOut->showFileDeleteError( $this->mUpload->getTempPath() );
514 return false;
515 } else {
516 return true;
517 }
518 }
519
520 /* Interface code starts below this line *
521 * -------------------------------------------------------------- */
522
523
524 /**
525 * @param string $error as HTML
526 * @access private
527 */
528 function uploadError( $error ) {
529 global $wgOut;
530 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
531 $wgOut->addHTML( '<span class="error">' . $error . '</span>' );
532 }
533
534 /**
535 * There's something wrong with this file, not enough to reject it
536 * totally but we require manual intervention to save it for real.
537 * Stash it away, then present a form asking to confirm or cancel.
538 *
539 * @param string $warning as HTML
540 * @access private
541 */
542 function uploadWarning( $warnings ) {
543 global $wgOut, $wgUser;
544 global $wgUseCopyrightUpload;
545
546 $this->mSessionKey = $this->mUpload->stashSession();
547
548 if( $this->mSessionKey === false ) {
549 # Couldn't save file; an error has been displayed so let's go.
550 return;
551 }
552
553 $sk = $wgUser->getSkin();
554
555 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
556 $wgOut->addHTML( '<ul class="warning">' );
557 foreach( $warnings as $warning => $args ) {
558 $msg = null;
559 if( $warning == 'exists' ) {
560
561 //we should not have produced this warning if the user already acknowledged the destination warning
562 //at any rate I don't see why we should hid this warning if mDestWarningAck has been checked
563 //(it produces an empty warning page when no other warnings are fired)
564 //if ( !$this->mDestWarningAck )
565 $msg = self::getExistsWarning( $args );
566
567 } elseif( $warning == 'duplicate' ) {
568 $msg = $this->getDupeWarning( $args );
569 } elseif( $warning == 'duplicate-archive' ) {
570 $titleText = Title::makeTitle( NS_FILE, $args )->getPrefixedText();
571 $msg = Xml::tags( 'li', null, wfMsgExt( 'file-deleted-duplicate', array( 'parseinline' ), array( $titleText ) ) );
572 } elseif( $warning == 'filewasdeleted' ) {
573 $ltitle = SpecialPage::getTitleFor( 'Log' );
574 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
575 'type=delete&page=' . $args->getPrefixedUrl() );
576 $msg = "\t<li>" . wfMsgWikiHtml( 'filewasdeleted', $llink ) . "</li>\n";
577 } else {
578 if( is_bool( $args ) )
579 $args = array();
580 elseif( !is_array( $args ) )
581 $args = array( $args );
582 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
583 }
584 if( $msg )
585 $wgOut->addHTML( $msg );
586 }
587
588 $titleObj = SpecialPage::getTitleFor( 'Upload' );
589
590 if ( $wgUseCopyrightUpload ) {
591 $copyright = Xml::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus ) . "\n" .
592 Xml::hidden( 'wpUploadSource', $this->mCopyrightSource ) . "\n";
593 } else {
594 $copyright = '';
595 }
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', $wgUser->editToken()) .
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()->linkKnown(
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 if( $wgStrictFileExtensions ) {
706 # Everything not permitted is banned
707 $extensionsList =
708 '<div id="mw-upload-permitted">' .
709 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
710 "</div>\n";
711 } else {
712 # We have to list both preferred and prohibited
713 $extensionsList =
714 '<div id="mw-upload-preferred">' .
715 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
716 "</div>\n" .
717 '<div id="mw-upload-prohibited">' .
718 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileExtensions ) ) .
719 "</div>\n";
720 }
721 } else {
722 # Everything is permitted.
723 $extensionsList = '';
724 }
725
726 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
727 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
728 $val = trim( ini_get( 'upload_max_filesize' ) );
729 $last = strtoupper( ( substr( $val, -1 ) ) );
730 switch( $last ) {
731 case 'G':
732 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
733 break;
734 case 'M':
735 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
736 break;
737 case 'K':
738 $val2 = substr( $val, 0, -1 ) * 1024;
739 break;
740 default:
741 $val2 = $val;
742 }
743 $maxUploadSize = '<div id="mw-upload-maxfilesize">' .
744 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
745 $wgLang->formatSize( $val2 ) ) .
746 "</div>\n";
747 //add a hidden filed for upload by url (uses the $wgMaxUploadSize var)
748 if( UploadFromUrl::isEnabled() ){
749 $maxUploadSize.='<div id="mw-upload-maxfilesize-url" style="display:none">' .
750 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
751 $wgLang->formatSize( $wgMaxUploadSize ) ) .
752 "</div>\n";
753 }
754
755 $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
756 $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) );
757
758 $msg = ( $this->mForReUpload ) ? 'filereuploadsummary' : 'fileuploadsummary';
759 $summary = wfMsgExt( $msg, 'parseinline' );
760
761 $licenses = new Licenses();
762 $license = wfMsgExt( 'license', array( 'parseinline' ) );
763 $nolicense = wfMsgHtml( 'nolicense' );
764 $licenseshtml = $licenses->getHtml();
765
766 $ulb = wfMsgHtml( 'uploadbtn' );
767
768
769 $titleObj = SpecialPage::getTitleFor( 'Upload' );
770
771 $encDestName = htmlspecialchars( $this->mDesiredDestName );
772
773 $watchChecked = $this->watchCheck() ? 'checked="checked"' : '';
774 # Re-uploads should not need "file exist already" warnings
775 $warningChecked = ($this->mIgnoreWarning || $this->mForReUpload) ? 'checked="checked"' : '';
776
777 // Prepare form for upload or upload/copy
778 //javascript moved from inline calls to setup:
779 if( UploadFromUrl::isEnabled() && $wgUser->isAllowed( 'upload_by_url' ) ) {
780 if($wgEnableJS2system){
781 $filename_form =
782 Xml::input( 'wpSourceType', false, 'file', array( 'id'=>'wpSourceTypeFile', 'type' => 'radio', 'checked' => 'checked' ) ) .
783 Xml::input( 'wpUploadFile', 60, false, array( 'id'=>'wpUploadFile', 'type'=>'file', 'tabindex' => '1' ) ) .
784 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
785 Xml::input( 'wpSourceType', false, 'Url', array( 'id'=>'wpSourceTypeURL', 'type' => 'radio' )) .
786 Xml::input( 'wpUploadFileURL', 60, false, array( 'id'=>'wpUploadFileURL', 'type' => 'text', 'tabindex' => '1')) .
787 wfMsgHtml( 'upload_source_url' ) ;
788 }else{
789 //@@todo depreciate (not needed once $wgEnableJS2system is turned on)
790 $filename_form =
791 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
792 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
793 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
794 " onfocus='" .
795 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
796 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
797 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
798 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
799 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
800 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
801 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
802 "onfocus='" .
803 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
804 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
805 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
806 wfMsgHtml( 'upload_source_url' ) ;
807
808 }
809 } else {
810 if($wgEnableJS2system){
811 $filename_form =
812 Xml::input( 'wpUploadFile', 60, false, array( 'id'=>'wpUploadFile', 'type'=>'file', 'tabindex' => '1' ) ) .
813 Xml::hidden( 'wpSourceType', 'file');
814 }else{
815 $filename_form =
816 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' size='60' ".
817 "onchange='fillDestFilename(\"wpUploadFile\")' />" .
818 "<input type='hidden' name='wpSourceType' value='file' />" ;
819 }
820 }
821 $warningRow = '';
822 $destOnkeyup = '';
823 if($wgEnableJS2system){
824 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'>&nbsp;</td></tr>";
825 }else{
826 if ( $useAjaxDestCheck ) {
827 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'>&nbsp;</td></tr>";
828 $destOnkeyup = 'onchange=\'wgUploadWarningObj.checkNow(this.value);\'';
829 }
830 }
831 # Uploading a new version? If so, the name is fixed.
832 $on = $this->mForReUpload ? "readonly='readonly'" : "";
833
834 $encComment = htmlspecialchars( $this->mComment );
835
836 //add the wpEditToken
837 $wgOut->addHTML(
838 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
839 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
840 Xml::hidden('wpEditToken', $wgUser->editToken()) .
841 Xml::openElement( 'fieldset' ) .
842 Xml::element( 'legend', null, wfMsg( 'upload' ) ) .
843 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
844 "<tr>
845 {$this->uploadFormTextTop}
846 <td class='mw-label'>
847 <label for='wpUploadFile'>{$sourcefilename}</label>
848 </td>
849 <td class='mw-input'>
850 {$filename_form}
851 </td>
852 </tr>
853 <tr>
854 <td></td>
855 <td>
856 {$maxUploadSize}
857 {$extensionsList}
858 </td>
859 </tr>
860 <tr>
861 <td class='mw-label'>
862 <label for='wpDestFile'>{$destfilename}</label>
863 </td>
864 <td class='mw-input'>"
865 );
866 if( $this->mForReUpload ) {
867 $wgOut->addHTML(
868 Xml::hidden( 'wpDestFile', $this->mDesiredDestName, array('id'=>'wpDestFile','tabindex'=>2) ) .
869 "<tt>" .
870 $encDestName .
871 "</tt>"
872 );
873 }
874 else {
875 $wgOut->addHTML(
876 "<input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
877 value=\"{$encDestName}\" $destOnkeyup />"
878 );
879 }
880
881
882 $wgOut->addHTML(
883 "</td>
884 </tr>
885 <tr>
886 <td class='mw-label'>
887 <label for='wpUploadDescription'>{$summary}</label>
888 </td>
889 <td class='mw-input'>
890 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
891 cols='{$cols}'{$width}>$encComment</textarea>
892 {$this->uploadFormTextAfterSummary}
893 </td>
894 </tr>
895 <tr>"
896 );
897
898 # Re-uploads should not need license info
899 if ( !$this->mForReUpload && $licenseshtml != '' ) {
900 global $wgStylePath;
901 $wgOut->addHTML( "
902 <td class='mw-label'>
903 <label for='wpLicense'>$license</label>
904 </td>
905 <td class='mw-input'>
906 <select name='wpLicense' id='wpLicense' tabindex='4'
907 onchange='licenseSelectorCheck()'>
908 <option value=''>$nolicense</option>
909 $licenseshtml
910 </select>
911 </td>
912 </tr>
913 <tr>"
914 );
915 if( $useAjaxLicensePreview ) {
916 $wgOut->addHTML( "
917 <td></td>
918 <td id=\"mw-license-preview\"></td>
919 </tr>
920 <tr>"
921 );
922 }
923 }
924
925 if ( !$this->mForReUpload && $wgUseCopyrightUpload ) {
926 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
927 $copystatus = htmlspecialchars( $this->mCopyrightStatus );
928 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
929 $uploadsource = htmlspecialchars( $this->mCopyrightSource );
930
931 $wgOut->addHTML( "
932 <td class='mw-label' style='white-space: nowrap;'>
933 <label for='wpUploadCopyStatus'>$filestatus</label></td>
934 <td class='mw-input'>
935 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
936 value=\"$copystatus\" size='60' />
937 </td>
938 </tr>
939 <tr>
940 <td class='mw-label'>
941 <label for='wpUploadCopyStatus'>$filesource</label>
942 </td>
943 <td class='mw-input'>
944 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
945 value=\"$uploadsource\" size='60' />
946 </td>
947 </tr>
948 <tr>"
949 );
950 }
951
952 $wgOut->addHTML( "
953 <td></td>
954 <td>
955 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
956 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
957 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked />
958 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
959 </td>
960 </tr>
961 $warningRow
962 <tr>
963 <td></td>
964 <td class='mw-input'>
965 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" .
966 $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
967 </td>
968 </tr>
969 <tr>
970 <td></td>
971 <td class='mw-input'>"
972 );
973 $wgOut->addHTML( '<div class="mw-editTools">' );
974 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
975 $wgOut->addHTML( '</div>' );
976 $wgOut->addHTML( "
977 </td>
978 </tr>" .
979 Xml::closeElement( 'table' ) .
980 Xml::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
981 Xml::hidden( 'wpForReUpload', $this->mForReUpload, array( 'id' => 'wpForReUpload' ) ) .
982 Xml::closeElement( 'fieldset' ) .
983 Xml::closeElement( 'form' )
984 );
985 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
986 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
987 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
988 }
989 }
990
991 /* -------------------------------------------------------------- */
992
993 /**
994 * See if we should check the 'watch this page' checkbox on the form
995 * based on the user's preferences and whether we're being asked
996 * to create a new file or update an existing one.
997 *
998 * In the case where 'watch edits' is off but 'watch creations' is on,
999 * we'll leave the box unchecked.
1000 *
1001 * Note that the page target can be changed *on the form*, so our check
1002 * state can get out of sync.
1003 */
1004 function watchCheck() {
1005 global $wgUser;
1006 if( $wgUser->getOption( 'watchdefault' ) ) {
1007 // Watch all edits!
1008 return true;
1009 }
1010
1011 $local = wfLocalFile( $this->mDesiredDestName );
1012 if( $local && $local->exists() ) {
1013 // We're uploading a new version of an existing file.
1014 // No creation, so don't watch it if we're not already.
1015 return $local->getTitle()->userIsWatching();
1016 } else {
1017 // New page should get watched if that's our option.
1018 return $wgUser->getOption( 'watchcreations' );
1019 }
1020 }
1021
1022 /**
1023 * Check if a user is the last uploader
1024 *
1025 * @param User $user
1026 * @param string $img, image name
1027 * @return bool
1028 * @deprecated Use UploadBase::userCanReUpload
1029 */
1030 public static function userCanReUpload( User $user, $img ) {
1031 wfDeprecated( __METHOD__ );
1032
1033 if( $user->isAllowed( 'reupload' ) )
1034 return true; // non-conditional
1035 if( !$user->isAllowed( 'reupload-own' ) )
1036 return false;
1037
1038 $dbr = wfGetDB( DB_SLAVE );
1039 $row = $dbr->selectRow('image',
1040 /* SELECT */ 'img_user',
1041 /* WHERE */ array( 'img_name' => $img )
1042 );
1043 if ( !$row )
1044 return false;
1045
1046 return $user->getId() == $row->img_user;
1047 }
1048
1049 /**
1050 * Display an error with a wikitext description
1051 */
1052 function showError( $description ) {
1053 global $wgOut;
1054 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1055 $wgOut->setRobotPolicy( "noindex,nofollow" );
1056 $wgOut->setArticleRelated( false );
1057 $wgOut->enableClientCache( false );
1058 $wgOut->addWikiText( $description );
1059 }
1060
1061 /**
1062 * Get the initial image page text based on a comment and optional file status information
1063 */
1064 static function getInitialPageText( $comment='', $license='', $copyStatus='', $source='' ) {
1065 global $wgUseCopyrightUpload;
1066 if ( $wgUseCopyrightUpload ) {
1067 if ( $license != '' ) {
1068 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1069 }
1070 $pageText = '== ' . wfMsgForContent ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1071 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1072 "$licensetxt" .
1073 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1074 } else {
1075 if ( $license != '' ) {
1076 $filedesc = $comment == '' ? '' : '== ' . wfMsgForContent ( 'filedesc' ) . " ==\n" . $comment . "\n";
1077 $pageText = $filedesc .
1078 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1079 } else {
1080 $pageText = $comment;
1081 }
1082 }
1083 return $pageText;
1084 }
1085
1086 /**
1087 * If there are rows in the deletion log for this file, show them,
1088 * along with a nice little note for the user
1089 *
1090 * @param OutputPage $out
1091 * @param string filename
1092 */
1093 private function showDeletionLog( $out, $filename ) {
1094 global $wgUser;
1095 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1096 $pager = new LogPager( $loglist, 'delete', false, $filename );
1097 if( $pager->getNumRows() > 0 ) {
1098 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1099 $out->addWikiMsg( 'upload-wasdeleted' );
1100 $out->addHTML(
1101 $loglist->beginLogEventsList() .
1102 $pager->getBody() .
1103 $loglist->endLogEventsList()
1104 );
1105 $out->addHTML( '</div>' );
1106 }
1107 }
1108 }