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