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