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