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