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