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