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