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