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