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