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