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