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