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