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