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