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