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