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