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