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