Do not add the license selector when uploading a new version of a file
[lhc/web/wiklou.git] / includes / specials / SpecialUpload.php
1 <?php
2 /**
3 * @file
4 * @ingroup SpecialPage
5 * @ingroup Upload
6 *
7 * Form for handling uploads and special page.
8 */
9
10 class SpecialUpload extends SpecialPage {
11 /**
12 * Constructor : initialise object
13 * Get data POSTed through the form and assign them to the object
14 * @param $request WebRequest : data posted.
15 */
16 public function __construct( $request = null ) {
17 global $wgRequest;
18
19 parent::__construct( 'Upload', 'upload' );
20
21 $this->loadRequest( is_null( $request ) ? $wgRequest : $request );
22 }
23
24 /** Misc variables **/
25 protected $mRequest; // The WebRequest or FauxRequest this form is supposed to handle
26 protected $mSourceType;
27 protected $mUpload;
28 protected $mLocalFile;
29 protected $mUploadClicked;
30
31 /** User input variables from the "description" section **/
32 public $mDesiredDestName; // The requested target file name
33 protected $mComment;
34 protected $mLicense;
35
36 /** User input variables from the root section **/
37 protected $mIgnoreWarning;
38 protected $mWatchThis;
39 protected $mCopyrightStatus;
40 protected $mCopyrightSource;
41
42 /** Hidden variables **/
43 protected $mDestWarningAck;
44 protected $mForReUpload; // The user followed an "overwrite this file" link
45 protected $mCancelUpload; // The user clicked "Cancel and return to upload form" button
46 protected $mTokenOk;
47 protected $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
48
49 /** Text injection points for hooks not using HTMLForm **/
50 public $uploadFormTextTop;
51 public $uploadFormTextAfterSummary;
52
53 /**
54 * Initialize instance variables from request and create an Upload handler
55 *
56 * @param $request WebRequest: the request to extract variables from
57 */
58 protected function loadRequest( $request ) {
59 global $wgUser;
60
61 $this->mRequest = $request;
62 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
63 $this->mUpload = UploadBase::createFromRequest( $request );
64 $this->mUploadClicked = $request->wasPosted()
65 && ( $request->getCheck( 'wpUpload' )
66 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
67
68 // Guess the desired name from the filename if not provided
69 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
70 if( !$this->mDesiredDestName ) {
71 $this->mDesiredDestName = $request->getText( 'wpUploadFile' );
72 }
73 $this->mComment = $request->getText( 'wpUploadDescription' );
74 $this->mLicense = $request->getText( 'wpLicense' );
75
76
77 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
78 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
79 || $request->getCheck( 'wpUploadIgnoreWarning' );
80 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $wgUser->isLoggedIn();
81 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
82 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
83
84
85 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
86 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
87 || $request->getCheck( 'wpReUpload' ); // b/w compat
88
89 // If it was posted check for the token (no remote POST'ing with user credentials)
90 $token = $request->getVal( 'wpEditToken' );
91 if( $this->mSourceType == 'file' && $token == null ) {
92 // Skip token check for file uploads as that can't be faked via JS...
93 // Some client-side tools don't expect to need to send wpEditToken
94 // with their submissions, as that's new in 1.16.
95 $this->mTokenOk = true;
96 } else {
97 $this->mTokenOk = $wgUser->matchEditToken( $token );
98 }
99
100 $this->uploadFormTextTop = '';
101 $this->uploadFormTextAfterSummary = '';
102 }
103
104 /**
105 * This page can be shown if uploading is enabled.
106 * Handle permission checking elsewhere in order to be able to show
107 * custom error messages.
108 *
109 * @param $user User object
110 * @return Boolean
111 */
112 public function userCanExecute( $user ) {
113 return UploadBase::isEnabled() && parent::userCanExecute( $user );
114 }
115
116 /**
117 * Special page entry point
118 */
119 public function execute( $par ) {
120 global $wgUser, $wgOut, $wgRequest;
121
122 $this->setHeaders();
123 $this->outputHeader();
124
125 # Check uploading enabled
126 if( !UploadBase::isEnabled() ) {
127 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
128 return;
129 }
130
131 # Check permissions
132 global $wgGroupPermissions;
133 $permissionRequired = UploadBase::isAllowed( $wgUser );
134 if( $permissionRequired !== true ) {
135 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
136 || $wgGroupPermissions['autoconfirmed']['upload'] ) ) {
137 // Custom message if logged-in users without any special rights can upload
138 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
139 } else {
140 $wgOut->permissionRequired( $permissionRequired );
141 }
142 return;
143 }
144
145 # Check blocks
146 if( $wgUser->isBlocked() ) {
147 $wgOut->blockedPage();
148 return;
149 }
150
151 # Check whether we actually want to allow changing stuff
152 if( wfReadOnly() ) {
153 $wgOut->readOnlyPage();
154 return;
155 }
156
157 # Unsave the temporary file in case this was a cancelled upload
158 if ( $this->mCancelUpload ) {
159 if ( !$this->unsaveUploadedFile() ) {
160 # Something went wrong, so unsaveUploadedFile showed a warning
161 return;
162 }
163 }
164
165 # Process upload or show a form
166 if (
167 $this->mTokenOk && !$this->mCancelUpload &&
168 ( $this->mUpload && $this->mUploadClicked )
169 )
170 {
171 $this->processUpload();
172 } else {
173 # Backwards compatibility hook
174 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
175 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
176 return;
177 }
178
179 $this->showUploadForm( $this->getUploadForm() );
180 }
181
182 # Cleanup
183 if ( $this->mUpload ) {
184 $this->mUpload->cleanupTempFile();
185 }
186 }
187
188 /**
189 * Show the main upload form
190 *
191 * @param $form Mixed: an HTMLForm instance or HTML string to show
192 */
193 protected function showUploadForm( $form ) {
194 # Add links if file was previously deleted
195 if ( !$this->mDesiredDestName ) {
196 $this->showViewDeletedLinks();
197 }
198
199 if ( $form instanceof HTMLForm ) {
200 $form->show();
201 } else {
202 global $wgOut;
203 $wgOut->addHTML( $form );
204 }
205
206 }
207
208 /**
209 * Get an UploadForm instance with title and text properly set.
210 *
211 * @param $message String: HTML string to add to the form
212 * @param $sessionKey String: session key in case this is a stashed upload
213 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
214 * @return UploadForm
215 */
216 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
217 global $wgOut;
218
219 # Initialize form
220 $form = new UploadForm( array(
221 'watch' => $this->getWatchCheck(),
222 'forreupload' => $this->mForReUpload,
223 'sessionkey' => $sessionKey,
224 'hideignorewarning' => $hideIgnoreWarning,
225 'destwarningack' => (bool)$this->mDestWarningAck,
226
227 'texttop' => $this->uploadFormTextTop,
228 'textaftersummary' => $this->uploadFormTextAfterSummary,
229 ) );
230 $form->setTitle( $this->getTitle() );
231
232 # Check the token, but only if necessary
233 if(
234 !$this->mTokenOk && !$this->mCancelUpload &&
235 ( $this->mUpload && $this->mUploadClicked )
236 )
237 {
238 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
239 }
240
241 # Give a notice if the user is uploading a file that has been deleted or moved
242 # Note that this is independent from the message 'filewasdeleted' that requires JS
243 $desiredTitleObj = Title::newFromText( $this->mDesiredDestName, NS_FILE );
244 $delNotice = ''; // empty by default
245 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
246 LogEventsList::showLogExtract( $delNotice, array( 'delete', 'move' ),
247 $desiredTitleObj->getPrefixedText(),
248 '', array( 'lim' => 10,
249 'conds' => array( "log_action != 'revision'" ),
250 'showIfEmpty' => false,
251 'msgKey' => array( 'upload-recreate-warning' ) )
252 );
253 }
254 $form->addPreText( $delNotice );
255
256 # Add text to form
257 $form->addPreText( '<div id="uploadtext">' .
258 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName ) ) .
259 '</div>' );
260 # Add upload error message
261 $form->addPreText( $message );
262
263 # Add footer to form
264 $uploadFooter = wfMsgNoTrans( 'uploadfooter' );
265 if ( $uploadFooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadFooter ) ) {
266 $form->addPostText( '<div id="mw-upload-footer-message">'
267 . $wgOut->parse( $uploadFooter ) . "</div>\n" );
268 }
269
270 return $form;
271
272 }
273
274 /**
275 * Shows the "view X deleted revivions link""
276 */
277 protected function showViewDeletedLinks() {
278 global $wgOut, $wgUser;
279
280 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
281 // Show a subtitle link to deleted revisions (to sysops et al only)
282 if( $title instanceof Title ) {
283 $count = $title->isDeleted();
284 if ( $count > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
285 $link = wfMsgExt(
286 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
287 array( 'parse', 'replaceafter' ),
288 $wgUser->getSkin()->linkKnown(
289 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
290 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
291 )
292 );
293 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
294 }
295 }
296
297 // Show the relevant lines from deletion log (for still deleted files only)
298 if( $title instanceof Title && $title->isDeletedQuick() && !$title->exists() ) {
299 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
300 }
301 }
302
303 /**
304 * Stashes the upload and shows the main upload form.
305 *
306 * Note: only errors that can be handled by changing the name or
307 * description should be redirected here. It should be assumed that the
308 * file itself is sane and has passed UploadBase::verifyFile. This
309 * essentially means that UploadBase::VERIFICATION_ERROR and
310 * UploadBase::EMPTY_FILE should not be passed here.
311 *
312 * @param $message String: HTML message to be passed to mainUploadForm
313 */
314 protected function showRecoverableUploadError( $message ) {
315 $sessionKey = $this->mUpload->stashSession();
316 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
317 '<div class="error">' . $message . "</div>\n";
318
319 $form = $this->getUploadForm( $message, $sessionKey );
320 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
321 $this->showUploadForm( $form );
322 }
323 /**
324 * Stashes the upload, shows the main form, but adds an "continue anyway button".
325 * Also checks whether there are actually warnings to display.
326 *
327 * @param $warnings Array
328 * @return boolean true if warnings were displayed, false if there are no
329 * warnings and the should continue processing like there was no warning
330 */
331 protected function showUploadWarning( $warnings ) {
332 # If there are no warnings, or warnings we can ignore, return early.
333 # mDestWarningAck is set when some javascript has shown the warning
334 # to the user. mForReUpload is set when the user clicks the "upload a
335 # new version" link.
336 if ( !$warnings || ( count( $warnings ) == 1 &&
337 isset( $warnings['exists'] ) &&
338 ( $this->mDestWarningAck || $this->mForReUpload ) ) )
339 {
340 return false;
341 }
342
343 $sessionKey = $this->mUpload->stashSession();
344
345 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
346 . '<ul class="warning">';
347 foreach( $warnings as $warning => $args ) {
348 $msg = '';
349 if( $warning == 'exists' ) {
350 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
351 } elseif( $warning == 'duplicate' ) {
352 $msg = self::getDupeWarning( $args );
353 } elseif( $warning == 'duplicate-archive' ) {
354 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
355 array( Title::makeTitle( NS_FILE, $args )->getPrefixedText() ) )
356 . "</li>\n";
357 } else {
358 if ( $args === true ) {
359 $args = array();
360 } elseif ( !is_array( $args ) ) {
361 $args = array( $args );
362 }
363 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
364 }
365 $warningHtml .= $msg;
366 }
367 $warningHtml .= "</ul>\n";
368 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
369
370 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
371 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
372 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
373 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
374
375 $this->showUploadForm( $form );
376
377 # Indicate that we showed a form
378 return true;
379 }
380
381 /**
382 * Show the upload form with error message, but do not stash the file.
383 *
384 * @param $message HTML string
385 */
386 protected function showUploadError( $message ) {
387 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
388 '<div class="error">' . $message . "</div>\n";
389 $this->showUploadForm( $this->getUploadForm( $message ) );
390 }
391
392 /**
393 * Do the upload.
394 * Checks are made in SpecialUpload::execute()
395 */
396 protected function processUpload() {
397 global $wgUser, $wgOut;
398
399 // Verify permissions
400 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
401 if( $permErrors !== true ) {
402 $wgOut->showPermissionsErrorPage( $permErrors );
403 return;
404 }
405
406 if( $this->mUpload instanceOf UploadFromUrl ) {
407 return $this->showUploadError( wfMsg( 'uploadfromurl-queued' ) );
408 }
409
410 // Fetch the file if required
411 $status = $this->mUpload->fetchFile();
412 if( !$status->isOK() ) {
413 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
414 return;
415 }
416
417 // Deprecated backwards compatibility hook
418 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
419 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
420 return array( 'status' => UploadBase::BEFORE_PROCESSING );
421 }
422
423
424 // Upload verification
425 $details = $this->mUpload->verifyUpload();
426 if ( $details['status'] != UploadBase::OK ) {
427 $this->processVerificationError( $details );
428 return;
429 }
430
431 $this->mLocalFile = $this->mUpload->getLocalFile();
432
433 // Check warnings if necessary
434 if( !$this->mIgnoreWarning ) {
435 $warnings = $this->mUpload->checkWarnings();
436 if( $this->showUploadWarning( $warnings ) ) {
437 return;
438 }
439 }
440
441 // Get the page text if this is not a reupload
442 if( !$this->mForReUpload ) {
443 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
444 $this->mCopyrightStatus, $this->mCopyrightSource );
445 } else {
446 $pageText = false;
447 }
448 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $wgUser );
449 if ( !$status->isGood() ) {
450 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
451 return;
452 }
453
454 // Success, redirect to description page
455 $this->mUploadSuccessful = true;
456 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
457 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
458 }
459
460 /**
461 * Get the initial image page text based on a comment and optional file status information
462 */
463 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
464 global $wgUseCopyrightUpload;
465 if ( $wgUseCopyrightUpload ) {
466 $licensetxt = '';
467 if ( $license != '' ) {
468 $licensetxt = '== ' . wfMsgForContent( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
469 }
470 $pageText = '== ' . wfMsgForContent( 'filedesc' ) . " ==\n" . $comment . "\n" .
471 '== ' . wfMsgForContent( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
472 "$licensetxt" .
473 '== ' . wfMsgForContent( 'filesource' ) . " ==\n" . $source;
474 } else {
475 if ( $license != '' ) {
476 $filedesc = $comment == '' ? '' : '== ' . wfMsgForContent( 'filedesc' ) . " ==\n" . $comment . "\n";
477 $pageText = $filedesc .
478 '== ' . wfMsgForContent( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
479 } else {
480 $pageText = $comment;
481 }
482 }
483 return $pageText;
484 }
485
486 /**
487 * See if we should check the 'watch this page' checkbox on the form
488 * based on the user's preferences and whether we're being asked
489 * to create a new file or update an existing one.
490 *
491 * In the case where 'watch edits' is off but 'watch creations' is on,
492 * we'll leave the box unchecked.
493 *
494 * Note that the page target can be changed *on the form*, so our check
495 * state can get out of sync.
496 */
497 protected function getWatchCheck() {
498 global $wgUser;
499 if( $wgUser->getOption( 'watchdefault' ) ) {
500 // Watch all edits!
501 return true;
502 }
503
504 $local = wfLocalFile( $this->mDesiredDestName );
505 if( $local && $local->exists() ) {
506 // We're uploading a new version of an existing file.
507 // No creation, so don't watch it if we're not already.
508 return $local->getTitle()->userIsWatching();
509 } else {
510 // New page should get watched if that's our option.
511 return $wgUser->getOption( 'watchcreations' );
512 }
513 }
514
515
516 /**
517 * Provides output to the user for a result of UploadBase::verifyUpload
518 *
519 * @param $details Array: result of UploadBase::verifyUpload
520 */
521 protected function processVerificationError( $details ) {
522 global $wgFileExtensions, $wgLang;
523
524 switch( $details['status'] ) {
525
526 /** Statuses that only require name changing **/
527 case UploadBase::MIN_LENGTH_PARTNAME:
528 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
529 break;
530 case UploadBase::ILLEGAL_FILENAME:
531 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
532 'parseinline', $details['filtered'] ) );
533 break;
534 case UploadBase::OVERWRITE_EXISTING_FILE:
535 $this->showRecoverableUploadError( wfMsgExt( $details['overwrite'],
536 'parseinline' ) );
537 break;
538 case UploadBase::FILETYPE_MISSING:
539 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
540 'parseinline' ) );
541 break;
542
543 /** Statuses that require reuploading **/
544 case UploadBase::EMPTY_FILE:
545 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
546 break;
547 case UploadBase::FILE_TOO_LARGE:
548 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
549 break;
550 case UploadBase::FILETYPE_BADTYPE:
551 $finalExt = $details['finalExt'];
552 $this->showUploadError(
553 wfMsgExt( 'filetype-banned-type',
554 array( 'parseinline' ),
555 htmlspecialchars( $finalExt ),
556 implode(
557 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
558 $wgFileExtensions
559 ),
560 $wgLang->formatNum( count( $wgFileExtensions ) )
561 )
562 );
563 break;
564 case UploadBase::VERIFICATION_ERROR:
565 unset( $details['status'] );
566 $code = array_shift( $details['details'] );
567 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
568 break;
569 case UploadBase::HOOK_ABORTED:
570 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
571 $args = $details['error'];
572 $error = array_shift( $args );
573 } else {
574 $error = $details['error'];
575 $args = null;
576 }
577
578 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
579 break;
580 default:
581 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
582 }
583 }
584
585 /**
586 * Remove a temporarily kept file stashed by saveTempUploadedFile().
587 *
588 * @return Boolean: success
589 */
590 protected function unsaveUploadedFile() {
591 global $wgOut;
592 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
593 return true;
594 }
595 $success = $this->mUpload->unsaveUploadedFile();
596 if ( !$success ) {
597 $wgOut->showFileDeleteError( $this->mUpload->getTempPath() );
598 return false;
599 } else {
600 return true;
601 }
602 }
603
604 /*** Functions for formatting warnings ***/
605
606 /**
607 * Formats a result of UploadBase::getExistsWarning as HTML
608 * This check is static and can be done pre-upload via AJAX
609 *
610 * @param $exists Array: the result of UploadBase::getExistsWarning
611 * @return String: empty string if there is no warning or an HTML fragment
612 */
613 public static function getExistsWarning( $exists ) {
614 global $wgUser, $wgContLang;
615
616 if ( !$exists ) {
617 return '';
618 }
619
620 $file = $exists['file'];
621 $filename = $file->getTitle()->getPrefixedText();
622 $warning = '';
623
624 $sk = $wgUser->getSkin();
625
626 if( $exists['warning'] == 'exists' ) {
627 // Exact match
628 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
629 } elseif( $exists['warning'] == 'page-exists' ) {
630 // Page exists but file does not
631 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
632 } elseif ( $exists['warning'] == 'exists-normalized' ) {
633 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
634 $exists['normalizedFile']->getTitle()->getPrefixedText() );
635 } elseif ( $exists['warning'] == 'thumb' ) {
636 // Swapped argument order compared with other messages for backwards compatibility
637 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
638 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
639 } elseif ( $exists['warning'] == 'thumb-name' ) {
640 // Image w/o '180px-' does not exists, but we do not like these filenames
641 $name = $file->getName();
642 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
643 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
644 } elseif ( $exists['warning'] == 'bad-prefix' ) {
645 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
646 } elseif ( $exists['warning'] == 'was-deleted' ) {
647 # If the file existed before and was deleted, warn the user of this
648 $ltitle = SpecialPage::getTitleFor( 'Log' );
649 $llink = $sk->linkKnown(
650 $ltitle,
651 wfMsgHtml( 'deletionlog' ),
652 array(),
653 array(
654 'type' => 'delete',
655 'page' => $filename
656 )
657 );
658 $warning = wfMsgWikiHtml( 'filewasdeleted', $llink );
659 }
660
661 return $warning;
662 }
663
664 /**
665 * Get a list of warnings
666 *
667 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
668 * @return Array: list of warning messages
669 */
670 public static function ajaxGetExistsWarning( $filename ) {
671 $file = wfFindFile( $filename );
672 if( !$file ) {
673 // Force local file so we have an object to do further checks against
674 // if there isn't an exact match...
675 $file = wfLocalFile( $filename );
676 }
677 $s = '&nbsp;';
678 if ( $file ) {
679 $exists = UploadBase::getExistsWarning( $file );
680 $warning = self::getExistsWarning( $exists );
681 if ( $warning !== '' ) {
682 $s = "<div>$warning</div>";
683 }
684 }
685 return $s;
686 }
687
688 /**
689 * Construct a warning and a gallery from an array of duplicate files.
690 */
691 public static function getDupeWarning( $dupes ) {
692 if( $dupes ) {
693 global $wgOut;
694 $msg = '<gallery>';
695 foreach( $dupes as $file ) {
696 $title = $file->getTitle();
697 $msg .= $title->getPrefixedText() .
698 '|' . $title->getText() . "\n";
699 }
700 $msg .= '</gallery>';
701 return '<li>' .
702 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
703 $wgOut->parse( $msg ) .
704 "</li>\n";
705 } else {
706 return '';
707 }
708 }
709
710 }
711
712 /**
713 * Sub class of HTMLForm that provides the form section of SpecialUpload
714 */
715 class UploadForm extends HTMLForm {
716 protected $mWatch;
717 protected $mForReUpload;
718 protected $mSessionKey;
719 protected $mHideIgnoreWarning;
720 protected $mDestWarningAck;
721
722 protected $mTextTop;
723 protected $mTextAfterSummary;
724
725 protected $mSourceIds;
726
727 public function __construct( $options = array() ) {
728 $this->mWatch = !empty( $options['watch'] );
729 $this->mForReUpload = !empty( $options['forreupload'] );
730 $this->mSessionKey = isset( $options['sessionkey'] )
731 ? $options['sessionkey'] : '';
732 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
733 $this->mDestWarningAck = !empty( $options['destwarningack'] );
734
735 $this->mTextTop = $options['texttop'];
736 $this->mTextAfterSummary = $options['textaftersummary'];
737
738 $sourceDescriptor = $this->getSourceSection();
739 $descriptor = $sourceDescriptor
740 + $this->getDescriptionSection()
741 + $this->getOptionsSection();
742
743 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
744 parent::__construct( $descriptor, 'upload' );
745
746 # Set some form properties
747 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
748 $this->setSubmitName( 'wpUpload' );
749 # Used message keys: 'accesskey-upload', 'tooltip-upload'
750 $this->setSubmitTooltip( 'upload' );
751 $this->setId( 'mw-upload-form' );
752
753 # Build a list of IDs for javascript insertion
754 $this->mSourceIds = array();
755 foreach ( $sourceDescriptor as $key => $field ) {
756 if ( !empty( $field['id'] ) ) {
757 $this->mSourceIds[] = $field['id'];
758 }
759 }
760
761 }
762
763 /**
764 * Get the descriptor of the fieldset that contains the file source
765 * selection. The section is 'source'
766 *
767 * @return Array: descriptor array
768 */
769 protected function getSourceSection() {
770 global $wgLang, $wgUser, $wgRequest;
771 global $wgMaxUploadSize;
772
773 if ( $this->mSessionKey ) {
774 return array(
775 'wpSessionKey' => array(
776 'type' => 'hidden',
777 'default' => $this->mSessionKey,
778 ),
779 'wpSourceType' => array(
780 'type' => 'hidden',
781 'default' => 'Stash',
782 ),
783 );
784 }
785
786 $canUploadByUrl = UploadFromUrl::isEnabled() && $wgUser->isAllowed( 'upload_by_url' );
787 $radio = $canUploadByUrl;
788 $selectedSourceType = strtolower( $wgRequest->getText( 'wpSourceType', 'File' ) );
789
790 $descriptor = array();
791 if ( $this->mTextTop ) {
792 $descriptor['UploadFormTextTop'] = array(
793 'type' => 'info',
794 'section' => 'source',
795 'default' => $this->mTextTop,
796 'raw' => true,
797 );
798 }
799
800 $descriptor['UploadFile'] = array(
801 'class' => 'UploadSourceField',
802 'section' => 'source',
803 'type' => 'file',
804 'id' => 'wpUploadFile',
805 'label-message' => 'sourcefilename',
806 'upload-type' => 'File',
807 'radio' => &$radio,
808 'help' => wfMsgExt( 'upload-maxfilesize',
809 array( 'parseinline', 'escapenoentities' ),
810 $wgLang->formatSize(
811 wfShorthandToInteger( min(
812 wfShorthandToInteger(
813 ini_get( 'upload_max_filesize' )
814 ), $wgMaxUploadSize
815 ) )
816 )
817 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
818 'checked' => $selectedSourceType == 'file',
819 );
820 if ( $canUploadByUrl ) {
821 $descriptor['UploadFileURL'] = array(
822 'class' => 'UploadSourceField',
823 'section' => 'source',
824 'id' => 'wpUploadFileURL',
825 'label-message' => 'sourceurl',
826 'upload-type' => 'url',
827 'radio' => &$radio,
828 'help' => wfMsgExt( 'upload-maxfilesize',
829 array( 'parseinline', 'escapenoentities' ),
830 $wgLang->formatSize( $wgMaxUploadSize )
831 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
832 'checked' => $selectedSourceType == 'url',
833 );
834 }
835 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
836
837 $descriptor['Extensions'] = array(
838 'type' => 'info',
839 'section' => 'source',
840 'default' => $this->getExtensionsMessage(),
841 'raw' => true,
842 );
843 return $descriptor;
844 }
845
846 /**
847 * Get the messages indicating which extensions are preferred and prohibitted.
848 *
849 * @return String: HTML string containing the message
850 */
851 protected function getExtensionsMessage() {
852 # Print a list of allowed file extensions, if so configured. We ignore
853 # MIME type here, it's incomprehensible to most people and too long.
854 global $wgLang, $wgCheckFileExtensions, $wgStrictFileExtensions,
855 $wgFileExtensions, $wgFileBlacklist;
856
857 $allowedExtensions = '';
858 if( $wgCheckFileExtensions ) {
859 if( $wgStrictFileExtensions ) {
860 # Everything not permitted is banned
861 $extensionsList =
862 '<div id="mw-upload-permitted">' .
863 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
864 "</div>\n";
865 } else {
866 # We have to list both preferred and prohibited
867 $extensionsList =
868 '<div id="mw-upload-preferred">' .
869 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
870 "</div>\n" .
871 '<div id="mw-upload-prohibited">' .
872 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
873 "</div>\n";
874 }
875 } else {
876 # Everything is permitted.
877 $extensionsList = '';
878 }
879 return $extensionsList;
880 }
881
882 /**
883 * Get the descriptor of the fieldset that contains the file description
884 * input. The section is 'description'
885 *
886 * @return Array: descriptor array
887 */
888 protected function getDescriptionSection() {
889 global $wgUser, $wgOut;
890
891 $cols = intval( $wgUser->getOption( 'cols' ) );
892 if( $wgUser->getOption( 'editwidth' ) ) {
893 $wgOut->addInlineStyle( '#mw-htmlform-description { width: 100%; }' );
894 }
895
896 $descriptor = array(
897 'DestFile' => array(
898 'type' => 'text',
899 'section' => 'description',
900 'id' => 'wpDestFile',
901 'label-message' => 'destfilename',
902 'size' => 60,
903 ),
904 'UploadDescription' => array(
905 'type' => 'textarea',
906 'section' => 'description',
907 'id' => 'wpUploadDescription',
908 'label-message' => $this->mForReUpload
909 ? 'filereuploadsummary'
910 : 'fileuploadsummary',
911 'cols' => $cols,
912 'rows' => 8,
913 )
914 );
915 if ( $this->mTextAfterSummary ) {
916 $descriptor['UploadFormTextAfterSummary'] = array(
917 'type' => 'info',
918 'section' => 'description',
919 'default' => $this->mTextAfterSummary,
920 'raw' => true,
921 );
922 }
923
924 $descriptor += array(
925 'EditTools' => array(
926 'type' => 'edittools',
927 'section' => 'description',
928 )
929 );
930
931 if ( $this->mForReUpload ) {
932 $descriptor['DestFile']['readonly'] = true;
933 } else {
934 $descriptor['License'] = array(
935 'type' => 'select',
936 'class' => 'Licenses',
937 'section' => 'description',
938 'id' => 'wpLicense',
939 'label-message' => 'license',
940 );
941 }
942
943 global $wgUseCopyrightUpload;
944 if ( $wgUseCopyrightUpload ) {
945 $descriptor['UploadCopyStatus'] = array(
946 'type' => 'text',
947 'section' => 'description',
948 'id' => 'wpUploadCopyStatus',
949 'label-message' => 'filestatus',
950 );
951 $descriptor['UploadSource'] = array(
952 'type' => 'text',
953 'section' => 'description',
954 'id' => 'wpUploadSource',
955 'label-message' => 'filesource',
956 );
957 }
958
959 return $descriptor;
960 }
961
962 /**
963 * Get the descriptor of the fieldset that contains the upload options,
964 * such as "watch this file". The section is 'options'
965 *
966 * @return Array: descriptor array
967 */
968 protected function getOptionsSection() {
969 global $wgUser;
970
971 if ( $wgUser->isLoggedIn() ) {
972 $descriptor = array(
973 'Watchthis' => array(
974 'type' => 'check',
975 'id' => 'wpWatchthis',
976 'label-message' => 'watchthisupload',
977 'section' => 'options',
978 'default' => $wgUser->getOption( 'watchcreations' ),
979 )
980 );
981 }
982 if ( !$this->mHideIgnoreWarning ) {
983 $descriptor['IgnoreWarning'] = array(
984 'type' => 'check',
985 'id' => 'wpIgnoreWarning',
986 'label-message' => 'ignorewarnings',
987 'section' => 'options',
988 );
989 }
990
991 $descriptor['wpDestFileWarningAck'] = array(
992 'type' => 'hidden',
993 'id' => 'wpDestFileWarningAck',
994 'default' => $this->mDestWarningAck ? '1' : '',
995 );
996
997 if ( $this->mForReUpload ) {
998 $descriptor['wpForReUpload'] = array(
999 'type' => 'hidden',
1000 'id' => 'wpForReUpload',
1001 'default' => '1',
1002 );
1003 }
1004
1005 return $descriptor;
1006 }
1007
1008 /**
1009 * Add the upload JS and show the form.
1010 */
1011 public function show() {
1012 $this->addUploadJS();
1013 parent::show();
1014 }
1015
1016 /**
1017 * Add upload JS to $wgOut
1018 */
1019 protected function addUploadJS() {
1020 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI;
1021 global $wgOut;
1022
1023 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1024 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1025
1026 $scriptVars = array(
1027 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1028 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1029 'wgUploadAutoFill' => !$this->mForReUpload,
1030 'wgUploadSourceIds' => $this->mSourceIds,
1031 );
1032
1033 $wgOut->addScript( Skin::makeVariablesScript( $scriptVars ) );
1034
1035 // For <charinsert> support
1036 $wgOut->addScriptFile( 'edit.js' );
1037 $wgOut->addScriptFile( 'upload.js' );
1038 }
1039
1040 /**
1041 * Empty function; submission is handled elsewhere.
1042 *
1043 * @return bool false
1044 */
1045 function trySubmit() {
1046 return false;
1047 }
1048
1049 }
1050
1051 /**
1052 * A form field that contains a radio box in the label
1053 */
1054 class UploadSourceField extends HTMLTextField {
1055 function getLabelHtml() {
1056 $id = "wpSourceType{$this->mParams['upload-type']}";
1057 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1058
1059 if ( !empty( $this->mParams['radio'] ) ) {
1060 $attribs = array(
1061 'name' => 'wpSourceType',
1062 'type' => 'radio',
1063 'id' => $id,
1064 'value' => $this->mParams['upload-type'],
1065 );
1066 if ( !empty( $this->mParams['checked'] ) ) {
1067 $attribs['checked'] = 'checked';
1068 }
1069 $label .= Html::element( 'input', $attribs );
1070 }
1071
1072 return Html::rawElement( 'td', array( 'class' => 'mw-label' ), $label );
1073 }
1074
1075 function getSize() {
1076 return isset( $this->mParams['size'] )
1077 ? $this->mParams['size']
1078 : 60;
1079 }
1080 }
1081