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