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