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