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