Comments and whitespace fixes only.
[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',
784 array( 'id' => 'wpSourceTypeFile', 'type' => 'radio', 'checked' => 'checked' ) ) .
785 Xml::input( 'wpUploadFile', 60, false,
786 array( 'id' => 'wpUploadFile', 'type' => 'file', 'tabindex' => '1' ) ) .
787 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
788 Xml::input( 'wpSourceType', false, 'Url',
789 array( 'id' => 'wpSourceTypeURL', 'type' => 'radio' ) ) .
790 Xml::input( 'wpUploadFileURL', 60, false,
791 array( 'id' => 'wpUploadFileURL', 'type' => 'text', 'tabindex' => '1' ) ) .
792 wfMsgHtml( 'upload_source_url' ) ;
793 } else {
794 //@@todo deprecate (not needed once $wgEnableJS2system is turned on)
795 $filename_form =
796 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
797 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
798 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
799 " onfocus='" .
800 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
801 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
802 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
803 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
804 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='Url' " .
805 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
806 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
807 "onfocus='" .
808 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
809 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
810 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
811 wfMsgHtml( 'upload_source_url' ) ;
812
813 }
814 } else {
815 if( $wgEnableJS2system ) {
816 $filename_form =
817 Xml::input( 'wpUploadFile', 60, false,
818 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',
845 array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
846 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
847 Xml::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) .
848 Xml::openElement( 'fieldset' ) .
849 Xml::element( 'legend', null, wfMsg( 'upload' ) ) .
850 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
851 "<tr>
852 {$this->uploadFormTextTop}
853 <td class='mw-label'>
854 <label for='wpUploadFile'>{$sourcefilename}</label>
855 </td>
856 <td class='mw-input'>
857 {$filename_form}
858 </td>
859 </tr>
860 <tr>
861 <td></td>
862 <td>
863 {$maxUploadSize}
864 {$extensionsList}
865 </td>
866 </tr>
867 <tr>
868 <td class='mw-label'>
869 <label for='wpDestFile'>{$destfilename}</label>
870 </td>
871 <td class='mw-input'>"
872 );
873 if( $this->mForReUpload ) {
874 $wgOut->addHTML(
875 Xml::hidden( 'wpDestFile', $this->mDesiredDestName, array('id'=>'wpDestFile','tabindex'=>2) ) .
876 "<tt>" .
877 $encDestName .
878 "</tt>"
879 );
880 }
881 else {
882 $wgOut->addHTML(
883 "<input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
884 value=\"{$encDestName}\" $destOnkeyup />"
885 );
886 }
887
888
889 $wgOut->addHTML(
890 "</td>
891 </tr>
892 <tr>
893 <td class='mw-label'>
894 <label for='wpUploadDescription'>{$summary}</label>
895 </td>
896 <td class='mw-input'>
897 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
898 cols='{$cols}'{$width}>$encComment</textarea>
899 {$this->uploadFormTextAfterSummary}
900 </td>
901 </tr>
902 <tr>"
903 );
904
905 # Re-uploads should not need license info
906 if ( !$this->mForReUpload && $licenseshtml != '' ) {
907 global $wgStylePath;
908 $wgOut->addHTML( "
909 <td class='mw-label'>
910 <label for='wpLicense'>$license</label>
911 </td>
912 <td class='mw-input'>
913 <select name='wpLicense' id='wpLicense' tabindex='4'
914 onchange='licenseSelectorCheck()'>
915 <option value=''>$nolicense</option>
916 $licenseshtml
917 </select>
918 </td>
919 </tr>
920 <tr>"
921 );
922 if( $useAjaxLicensePreview ) {
923 $wgOut->addHTML( "
924 <td></td>
925 <td id=\"mw-license-preview\"></td>
926 </tr>
927 <tr>"
928 );
929 }
930 }
931
932 if ( !$this->mForReUpload && $wgUseCopyrightUpload ) {
933 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
934 $copystatus = htmlspecialchars( $this->mCopyrightStatus );
935 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
936 $uploadsource = htmlspecialchars( $this->mCopyrightSource );
937
938 $wgOut->addHTML( "
939 <td class='mw-label' style='white-space: nowrap;'>
940 <label for='wpUploadCopyStatus'>$filestatus</label></td>
941 <td class='mw-input'>
942 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
943 value=\"$copystatus\" size='60' />
944 </td>
945 </tr>
946 <tr>
947 <td class='mw-label'>
948 <label for='wpUploadCopyStatus'>$filesource</label>
949 </td>
950 <td class='mw-input'>
951 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
952 value=\"$uploadsource\" size='60' />
953 </td>
954 </tr>
955 <tr>"
956 );
957 }
958
959 $wgOut->addHTML( "
960 <td></td>
961 <td>
962 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
963 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
964 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked />
965 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
966 </td>
967 </tr>
968 $warningRow
969 <tr>
970 <td></td>
971 <td class='mw-input'>
972 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" .
973 $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
974 </td>
975 </tr>
976 <tr>
977 <td></td>
978 <td class='mw-input'>"
979 );
980 $wgOut->addHTML( '<div class="mw-editTools">' );
981 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
982 $wgOut->addHTML( '</div>' );
983 $wgOut->addHTML( "
984 </td>
985 </tr>" .
986 Xml::closeElement( 'table' ) .
987 Xml::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
988 Xml::hidden( 'wpForReUpload', $this->mForReUpload, array( 'id' => 'wpForReUpload' ) ) .
989 Xml::closeElement( 'fieldset' ) .
990 Xml::closeElement( 'form' )
991 );
992 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
993 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
994 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
995 }
996 }
997
998 /* -------------------------------------------------------------- */
999
1000 /**
1001 * See if we should check the 'watch this page' checkbox on the form
1002 * based on the user's preferences and whether we're being asked
1003 * to create a new file or update an existing one.
1004 *
1005 * In the case where 'watch edits' is off but 'watch creations' is on,
1006 * we'll leave the box unchecked.
1007 *
1008 * Note that the page target can be changed *on the form*, so our check
1009 * state can get out of sync.
1010 */
1011 function watchCheck() {
1012 global $wgUser;
1013 if( $wgUser->getOption( 'watchdefault' ) ) {
1014 // Watch all edits!
1015 return true;
1016 }
1017
1018 $local = wfLocalFile( $this->mDesiredDestName );
1019 if( $local && $local->exists() ) {
1020 // We're uploading a new version of an existing file.
1021 // No creation, so don't watch it if we're not already.
1022 return $local->getTitle()->userIsWatching();
1023 } else {
1024 // New page should get watched if that's our option.
1025 return $wgUser->getOption( 'watchcreations' );
1026 }
1027 }
1028
1029 /**
1030 * Check if a user is the last uploader
1031 *
1032 * @param User $user
1033 * @param string $img, image name
1034 * @return bool
1035 * @deprecated Use UploadBase::userCanReUpload
1036 */
1037 public static function userCanReUpload( User $user, $img ) {
1038 wfDeprecated( __METHOD__ );
1039
1040 if( $user->isAllowed( 'reupload' ) )
1041 return true; // non-conditional
1042 if( !$user->isAllowed( 'reupload-own' ) )
1043 return false;
1044
1045 $dbr = wfGetDB( DB_SLAVE );
1046 $row = $dbr->selectRow('image',
1047 /* SELECT */ 'img_user',
1048 /* WHERE */ array( 'img_name' => $img )
1049 );
1050 if ( !$row )
1051 return false;
1052
1053 return $user->getId() == $row->img_user;
1054 }
1055
1056 /**
1057 * Display an error with a wikitext description
1058 */
1059 function showError( $description ) {
1060 global $wgOut;
1061 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1062 $wgOut->setRobotPolicy( "noindex,nofollow" );
1063 $wgOut->setArticleRelated( false );
1064 $wgOut->enableClientCache( false );
1065 $wgOut->addWikiText( $description );
1066 }
1067
1068 /**
1069 * Get the initial image page text based on a comment and optional file status information
1070 */
1071 static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
1072 global $wgUseCopyrightUpload;
1073 if ( $wgUseCopyrightUpload ) {
1074 $licensetxt = '';
1075 if ( $license != '' ) {
1076 $licensetxt = '== ' . wfMsgForContent( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1077 }
1078 $pageText = '== ' . wfMsgForContent ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1079 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1080 "$licensetxt" .
1081 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1082 } else {
1083 if ( $license != '' ) {
1084 $filedesc = $comment == '' ? '' : '== ' . wfMsgForContent ( 'filedesc' ) . " ==\n" . $comment . "\n";
1085 $pageText = $filedesc .
1086 '== ' . wfMsgForContent ( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1087 } else {
1088 $pageText = $comment;
1089 }
1090 }
1091 return $pageText;
1092 }
1093
1094 /**
1095 * If there are rows in the deletion log for this file, show them,
1096 * along with a nice little note for the user
1097 *
1098 * @param OutputPage $out
1099 * @param string filename
1100 */
1101 private function showDeletionLog( $out, $filename ) {
1102 global $wgUser;
1103 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1104 $pager = new LogPager( $loglist, 'delete', false, $filename );
1105 if( $pager->getNumRows() > 0 ) {
1106 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1107 $out->addWikiMsg( 'upload-wasdeleted' );
1108 $out->addHTML(
1109 $loglist->beginLogEventsList() .
1110 $pager->getBody() .
1111 $loglist->endLogEventsList()
1112 );
1113 $out->addHTML( '</div>' );
1114 }
1115 }
1116 }