001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.
018 */
019package org.apache.wiki.attachment;
020
021import org.apache.commons.fileupload.FileItem;
022import org.apache.commons.fileupload.FileItemFactory;
023import org.apache.commons.fileupload.FileUploadException;
024import org.apache.commons.fileupload.ProgressListener;
025import org.apache.commons.fileupload.disk.DiskFileItemFactory;
026import org.apache.logging.log4j.LogManager;
027import org.apache.logging.log4j.Logger;
028import org.apache.wiki.api.core.Attachment;
029import org.apache.wiki.api.core.Context;
030import org.apache.wiki.api.core.ContextEnum;
031import org.apache.wiki.api.core.Engine;
032import org.apache.wiki.api.core.Page;
033import org.apache.wiki.api.core.Session;
034import org.apache.wiki.api.exceptions.ProviderException;
035import org.apache.wiki.api.exceptions.RedirectException;
036import org.apache.wiki.api.exceptions.WikiException;
037import org.apache.wiki.api.providers.WikiProvider;
038import org.apache.wiki.api.spi.Wiki;
039import org.apache.wiki.auth.AuthorizationManager;
040import org.apache.wiki.auth.permissions.PermissionFactory;
041import org.apache.wiki.http.filter.CsrfProtectionFilter;
042import org.apache.wiki.i18n.InternationalizationManager;
043import org.apache.wiki.preferences.Preferences;
044import org.apache.wiki.ui.progress.ProgressItem;
045import org.apache.wiki.ui.progress.ProgressManager;
046import org.apache.wiki.util.HttpUtil;
047import org.apache.wiki.util.TextUtil;
048
049import javax.servlet.ServletConfig;
050import javax.servlet.ServletContext;
051import javax.servlet.ServletException;
052import javax.servlet.http.HttpServlet;
053import javax.servlet.http.HttpServletRequest;
054import javax.servlet.http.HttpServletResponse;
055import java.io.File;
056import java.io.IOException;
057import java.io.InputStream;
058import java.io.OutputStream;
059import java.net.SocketException;
060import java.nio.charset.StandardCharsets;
061import java.security.Permission;
062import java.security.Principal;
063import java.util.ArrayList;
064import java.util.List;
065import java.util.Properties;
066import java.util.ResourceBundle;
067import java.util.Set;
068import org.apache.commons.fileupload.servlet.ServletFileUpload;
069
070
071/**
072 *  This is the chief JSPWiki attachment management servlet.  It is used for
073 *  both uploading new content and downloading old content.  It can handle
074 *  most common cases, e.g. check for modifications and return 304's as necessary.
075 *  <p>
076 *  Authentication is done using JSPWiki's normal AAA framework.
077 *  <p>
078 *  This servlet is also capable of managing dynamically created attachments.
079 *
080 *
081 *  @since 1.9.45.
082 */
083public class AttachmentServlet extends HttpServlet {
084
085    private static final long serialVersionUID = 3257282552187531320L;
086    private static final int BUFFER_SIZE = 8192;
087
088    private Engine m_engine;
089    private static final Logger LOG = LogManager.getLogger( AttachmentServlet.class );
090    private static final String HDR_VERSION = "version";
091
092    /** Allowlist of passive content types which may be served inline; everything else forces a download. */
093    private static final Set< String > INLINE_SAFE_TYPES = Set.of(
094            "image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp",
095            "image/avif", "image/tiff", "image/x-icon", "image/vnd.microsoft.icon",
096            "text/plain" );
097
098    /** The maximum size that an attachment can be. */
099    private int m_maxSize = Integer.MAX_VALUE;
100
101    /** List of attachment types which are allowed */
102    private String[] m_allowedPatterns;
103    private String[] m_forbiddenPatterns;
104
105    //
106    // Not static as DateFormat objects are not thread safe.
107    // Used to handle the RFC date format = Sat, 13 Apr 2002 13:23:01 GMT
108    //
109    //private final DateFormat rfcDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
110
111    /**
112     *  Initializes the servlet from Engine properties.
113     */
114    @Override
115    public void init( final ServletConfig config ) throws ServletException {
116        m_engine = Wiki.engine().find( config );
117        final Properties props = m_engine.getWikiProperties();
118        final String tmpDir = m_engine.getWorkDir() + File.separator + "attach-tmp";
119        final String allowed = TextUtil.getStringProperty( props, AttachmentManager.PROP_ALLOWEDEXTENSIONS, null );
120        m_maxSize = TextUtil.getIntegerProperty( props, AttachmentManager.PROP_MAXSIZE, Integer.MAX_VALUE );
121
122        if( allowed != null && !allowed.isEmpty() ) {
123            m_allowedPatterns = allowed.toLowerCase().split( "\\s" );
124        } else {
125            m_allowedPatterns = new String[ 0 ];
126        }
127
128        final String forbidden = TextUtil.getStringProperty( props, AttachmentManager.PROP_FORBIDDENEXTENSIONS,null );
129        if( forbidden != null && !forbidden.isEmpty() ) {
130            m_forbiddenPatterns = forbidden.toLowerCase().split("\\s");
131        } else {
132            m_forbiddenPatterns = new String[0];
133        }
134
135        final File f = new File( tmpDir );
136        if( !f.exists() ) {
137            f.mkdirs();
138        } else if( !f.isDirectory() ) {
139            LOG.fatal( "A file already exists where the temporary dir is supposed to be: {}. Please remove it.", tmpDir );
140        }
141
142        LOG.debug( "UploadServlet initialized. Using {} for temporary storage.", tmpDir );
143    }
144
145    private boolean isTypeAllowed( String name )
146    {
147        if( name == null || name.isEmpty() ) return false;
148
149        name = name.toLowerCase();
150
151        for( final String m_forbiddenPattern : m_forbiddenPatterns ) {
152            if( name.endsWith( m_forbiddenPattern ) && !m_forbiddenPattern.isEmpty() )
153                return false;
154        }
155
156        for( final String m_allowedPattern : m_allowedPatterns ) {
157            if( name.endsWith( m_allowedPattern ) && !m_allowedPattern.isEmpty() )
158                return true;
159        }
160
161        return m_allowedPatterns.length == 0;
162    }
163
164    /**
165     *  Implements the OPTIONS method.
166     *
167     *  @param req The servlet request
168     *  @param res The servlet response
169     */
170
171    @Override
172    protected void doOptions( final HttpServletRequest req, final HttpServletResponse res ) {
173        res.setHeader( "Allow", "GET, PUT, POST, OPTIONS, PROPFIND, PROPPATCH, MOVE, COPY, DELETE");
174        res.setStatus( HttpServletResponse.SC_OK );
175    }
176
177    /**
178     *  Serves a GET with two parameters: 'wikiname' specifying the wikiname
179     *  of the attachment, 'version' specifying the version indicator.
180     *
181     */
182    // FIXME: Messages would need to be localized somehow.
183    @Override
184    public void doGet( final HttpServletRequest  req, final HttpServletResponse res ) throws IOException {
185        final Context context = Wiki.context().create( m_engine, req, ContextEnum.PAGE_ATTACH.getRequestContext() );
186        final AttachmentManager mgr = m_engine.getManager( AttachmentManager.class );
187        final AuthorizationManager authmgr = m_engine.getManager( AuthorizationManager.class );
188        final String version = req.getParameter( HDR_VERSION );
189        final String nextPage = req.getParameter( "nextpage" );
190        final String page = context.getPage().getName();
191        int ver = WikiProvider.LATEST_VERSION;
192
193        if( page == null ) {
194            LOG.info( "Invalid attachment name." );
195            res.sendError( HttpServletResponse.SC_BAD_REQUEST );
196            return;
197        }
198
199        try( final OutputStream out = res.getOutputStream() ) {
200            LOG.debug("Attempting to download att "+page+", version "+version);
201            if( version != null ) {
202                ver = Integer.parseInt( version );
203            }
204
205            final Attachment att = mgr.getAttachmentInfo( page, ver );
206            if( att != null ) {
207                //
208                //  Check if the user has permission for this attachment
209                //
210
211                final Permission permission = PermissionFactory.getPagePermission( att, "view" );
212                if( !authmgr.checkPermission( context.getWikiSession(), permission ) ) {
213                    LOG.debug("User does not have permission for this");
214                    res.sendError( HttpServletResponse.SC_FORBIDDEN );
215                    return;
216                }
217
218                //
219                //  Check if the client already has a version of this attachment.
220                //
221                if( HttpUtil.checkFor304( req, att.getName(), att.getLastModified() ) ) {
222                    LOG.debug( "Client has latest version already, sending 304..." );
223                    res.sendError( HttpServletResponse.SC_NOT_MODIFIED );
224                    return;
225                }
226
227                final String mimetype = getMimeType( context, att.getFileName() );
228                res.setContentType( mimetype );
229
230                final String contentDisposition = getContentDisposition( att, mimetype );
231                res.addHeader( "Content-Disposition", contentDisposition );
232                res.addDateHeader("Last-Modified",att.getLastModified().getTime());
233
234                if( !att.isCacheable() ) {
235                    res.addHeader( "Pragma", "no-cache" );
236                    res.addHeader( "Cache-control", "no-cache" );
237                }
238
239                // If a size is provided by the provider, report it.
240                if( att.getSize() >= 0 ) {
241                    // LOG.info("size:"+att.getSize());
242                    res.setContentLength( (int)att.getSize() );
243                }
244
245                try( final InputStream  in = mgr.getAttachmentStream( context, att ) ) {
246                    int read;
247                    final byte[] buffer = new byte[ BUFFER_SIZE ];
248
249                    while( ( read = in.read( buffer ) ) > -1 ) {
250                        out.write( buffer, 0, read );
251                    }
252                }
253                LOG.debug( "Attachment {} sent to {} on {}", att.getFileName(), req.getRemoteUser(), HttpUtil.getRemoteAddress(req) );
254                if( nextPage != null ) {
255                    res.sendRedirect(
256                        validateNextPage(
257                            TextUtil.urlEncodeUTF8(nextPage),
258                            m_engine.getURL( ContextEnum.WIKI_ERROR.getRequestContext(), "", null )
259                        )
260                    );
261                }
262
263            } else {
264                final String msg = "Attachment '" + page + "', version " + ver + " does not exist.";
265                LOG.info( msg );
266                res.sendError( HttpServletResponse.SC_NOT_FOUND, msg );
267            }
268        } catch( final ProviderException pe ) {
269            LOG.warn("Provider failed while reading", pe);
270            //
271            //  This might fail, if the response is already committed.  So in that
272            //  case we just log it.
273            //
274            final ResourceBundle rb = ResourceBundle.getBundle( InternationalizationManager.CORE_BUNDLE, req.getLocale() );
275            sendError( res, rb.getString("operation.failed") );
276        } catch( final NumberFormatException nfe ) {
277            LOG.warn( "Invalid version number: " + version );
278            res.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid version number" );
279        } catch( final SocketException se ) {
280            //
281            //  These are very common in download situations due to aggressive
282            //  clients.  No need to try and send an error.
283            //
284            LOG.debug( "I/O exception during download", se );
285        } catch( final IOException ioe ) {
286            //
287            //  Client dropped the connection or something else happened.
288            //  We don't know where the error came from, so we'll at least
289            //  try to send an error and catch it quietly if it doesn't quite work.
290            //
291            LOG.debug( "I/O exception during download", ioe );
292            final ResourceBundle rb = ResourceBundle.getBundle( InternationalizationManager.CORE_BUNDLE, req.getLocale() );
293            sendError( res, rb.getString("operation.failed") );
294        }
295    }
296
297    String getContentDisposition( final Attachment att, final String mimetype ) {
298        // Default-deny: only passive content types which cannot execute script on the wiki's origin
299        // are served inline, so that user agents can try to automatically open them.  Everything
300        // else - including anything the container resolves to an actively rendering type such as
301        // text/html, application/xhtml+xml or image/svg+xml - is forced to download.
302        String contentDisposition = "attachment; filename=\"";
303        if( isInlineRenderSafe( mimetype ) && !m_engine.getManager( AttachmentManager.class ).forceDownload( att.getFileName() ) ) {
304            contentDisposition = "inline; filename=\"";
305        }
306        contentDisposition += att.getFileName() + "\";";
307        return contentDisposition;
308    }
309
310    /**
311     * Checks whether the given content type is safe to render inline on the wiki origin, i.e. it is a
312     * passive media type which cannot carry script.  Actively rendering types (text/html,
313     * application/xhtml+xml, image/svg+xml, XML, PDF, ...) are deliberately not on the allowlist.
314     *
315     * @param mimetype The resolved content type of the attachment.
316     * @return {@code true} if the attachment may be served with {@code Content-Disposition: inline}.
317     */
318    static boolean isInlineRenderSafe( final String mimetype ) {
319        if( mimetype == null ) {
320            return false;
321        }
322        final String type = mimetype.toLowerCase();
323        return INLINE_SAFE_TYPES.contains( type ) || type.startsWith( "audio/" ) || type.startsWith( "video/" );
324    }
325
326    void sendError( final HttpServletResponse res, final String message ) throws IOException {
327        try {
328            res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message );
329        } catch( final IllegalStateException e ) {
330            // ignore
331        }
332    }
333
334    /**
335     *  Returns the mime type for this particular file.  Case does not matter.
336     *
337     * @param ctx WikiContext; required to access the ServletContext of the request.
338     * @param fileName The name to check for.
339     * @return A valid mime type, or application/binary, if not recognized
340     */
341    private static String getMimeType( final Context ctx, final String fileName ) {
342        String mimetype = null;
343
344        final HttpServletRequest req = ctx.getHttpRequest();
345        if( req != null ) {
346            final ServletContext s = req.getSession().getServletContext();
347
348            if( s != null ) {
349                mimetype = s.getMimeType( fileName.toLowerCase() );
350            }
351        }
352
353        if( mimetype == null ) {
354            mimetype = "application/binary";
355        }
356
357        return mimetype;
358    }
359
360
361    /**
362     * Grabs mime/multipart data and stores it into the temporary area.
363     * Uses other parameters to determine which name to store as.
364     *
365     * <p>The input to this servlet is generated by an HTML FORM with
366     * two parts. The first, named 'page', is the WikiName identifier
367     * for the parent file. The second, named 'content', is the binary
368     * content of the file.
369     *
370     */
371    @Override
372    public void doPost( final HttpServletRequest req, final HttpServletResponse res ) throws IOException {
373        try {
374            final String nextPage = upload( req );
375            req.getSession().removeAttribute("msg");
376            res.sendRedirect( nextPage );
377        } catch( final RedirectException e ) {
378            final Session session = Wiki.session().find( m_engine, req );
379            session.addMessage( e.getMessage() );
380
381            req.getSession().setAttribute("msg", e.getMessage());
382            res.sendRedirect( e.getRedirect() );
383        }
384    }
385
386    /**
387     *  Validates the next page to be on the same server as this webapp.
388     *  Fixes [JSPWIKI-46].
389     */
390    private String validateNextPage( String nextPage, final String errorPage ) {
391        if( nextPage.contains( "://" ) ) {
392            // It's an absolute link, so unless it starts with our address, we'll log an error.
393            if( !nextPage.startsWith( m_engine.getBaseURL() ) ) {
394                LOG.warn("Detected phishing attempt by redirecting to an unsecure location: "+nextPage);
395                nextPage = errorPage;
396            }
397        }
398
399        return nextPage;
400    }
401
402    /**
403     *  Uploads a specific mime multipart input set, intercepts exceptions.
404     *
405     *  @param req The servlet request
406     *  @return The page to which we should go next.
407     *  @throws RedirectException If there's an error and a redirection is needed
408     *  @throws IOException If upload fails
409     */
410    protected String upload( final HttpServletRequest req ) throws RedirectException, IOException {
411        final String msg;
412        final String attName = "(unknown)";
413        final String errorPage = m_engine.getURL( ContextEnum.WIKI_ERROR.getRequestContext(), "", null ); // If something bad happened, Upload should be able to take care of most stuff
414        String nextPage = errorPage;
415        final String progressId = req.getParameter( "progressid" );
416        String csrfToken = req.getParameter( CsrfProtectionFilter.ANTICSRF_PARAM );
417
418        // Check that we have a file upload request
419        if( !ServletFileUpload.isMultipartContent(req) ) {
420            throw new RedirectException( "Not a file upload", errorPage );
421        }
422
423        try {
424            final FileItemFactory factory = new DiskFileItemFactory();
425
426            // Create the context _before_ Multipart operations, otherwise strict servlet containers may fail when setting encoding.
427            final Context context = Wiki.context().create( m_engine, req, ContextEnum.PAGE_ATTACH.getRequestContext() );
428            final UploadListener pl = new UploadListener();
429
430            m_engine.getManager( ProgressManager.class ).startProgress( pl, progressId );
431
432            final ServletFileUpload upload = new ServletFileUpload( factory );
433            upload.setHeaderEncoding( StandardCharsets.UTF_8.name() );
434            if( !context.hasAdminPermissions() ) {
435                upload.setFileSizeMax( m_maxSize );
436            }
437            upload.setProgressListener( pl );
438            final List<FileItem> items = upload.parseRequest( req );
439
440            String   wikipage   = null;
441            String   changeNote = null;
442            //FileItem actualFile = null;
443            final List<FileItem> fileItems = new ArrayList<>();
444
445            for( final FileItem item : items ) {
446                if( item.isFormField() ) {
447                    switch( item.getFieldName() ) {
448                    case "page":
449                        // FIXME: Kludge alert.  We must end up with the parent page name, if this is an upload of a new revision
450                        wikipage = item.getString( StandardCharsets.UTF_8.name() );
451                        final int x = wikipage.indexOf( "/" );
452                        if( x != -1 ) {
453                            wikipage = wikipage.substring( 0, x );
454                        }
455                        break;
456                    case "changenote":
457                        changeNote = item.getString( StandardCharsets.UTF_8.name() );
458                        if( changeNote != null ) {
459                            changeNote = TextUtil.replaceEntities( changeNote );
460                        }
461                        break;
462                    case "nextpage":
463                        nextPage = validateNextPage( item.getString( StandardCharsets.UTF_8.name() ), errorPage );
464                        break;
465                    case CsrfProtectionFilter.ANTICSRF_PARAM:
466                        csrfToken = item.getString( StandardCharsets.UTF_8.name() );
467                        break;
468                    }
469                } else {
470                    fileItems.add( item );
471                }
472            }
473
474            // The CsrfProtectionFilter delegates multipart requests to this servlet, since it cannot read the
475            // token from a multipart body without consuming it. Enforce the token here - taken from the multipart
476            // form field written by <wiki:CsrfProtection/> (or, for older clients, the query string) - before
477            // acting on anything else in the request, including the "Broken file upload" redirect below.
478            final Session session = Wiki.session().find( m_engine, req );
479            if( csrfToken == null || !csrfToken.equals( session.antiCsrfToken() ) ) {
480                LOG.error( "Incorrect {} received for {}", CsrfProtectionFilter.ANTICSRF_PARAM, req.getPathInfo() );
481                throw new RedirectException( "Missing or invalid CSRF token", errorPage );
482            }
483
484            if(fileItems.isEmpty()) {
485                throw new RedirectException( "Broken file upload", errorPage );
486
487            } else {
488                for( final FileItem actualFile : fileItems ) {
489                    final String filename = actualFile.getName();
490                    final long   fileSize = actualFile.getSize();
491                    try( final InputStream in  = actualFile.getInputStream() ) {
492                        executeUpload( context, in, filename, nextPage, wikipage, changeNote, fileSize );
493                    }
494                }
495            }
496
497        } catch( final ProviderException e ) {
498            msg = "Upload failed because the provider failed: "+e.getMessage();
499            LOG.warn( msg + " (attachment: " + attName + ")", e );
500
501            throw new IOException( msg );
502        } catch( final FileUploadException e ) {
503            // Show the submit page again, but with a bit more intimidating output.
504            msg = "Upload failure: " + e.getMessage();
505            LOG.warn( msg + " (attachment: " + attName + ")", e );
506
507            throw new IOException( msg, e );
508        } catch( final IOException e ) {
509            // Show the submit page again, but with a bit more intimidating output.
510            msg = "Upload failure: " + e.getMessage();
511            LOG.warn( msg + " (attachment: " + attName + ")", e );
512
513            throw e;
514        } finally {
515            m_engine.getManager( ProgressManager.class ).stopProgress( progressId );
516            // FIXME: In case of exceptions should absolutely remove the uploaded file.
517        }
518
519        return nextPage;
520    }
521
522    /**
523     *
524     * @param context the wiki context
525     * @param data the input stream data
526     * @param filename the name of the file to upload
527     * @param errorPage the place to which you want to get a redirection
528     * @param parentPage the page to which the file should be attached
529     * @param changenote The change note
530     * @param contentLength The content length
531     * @return <code>true</code> if upload results in the creation of a new page;
532     * <code>false</code> otherwise
533     * @throws RedirectException If the content needs to be redirected
534     * @throws IOException       If there is a problem in the upload.
535     * @throws ProviderException If there is a problem in the backend.
536     */
537    protected boolean executeUpload( final Context context, final InputStream data,
538                                     String filename, final String errorPage,
539                                     final String parentPage, final String changenote,
540                                     final long contentLength )
541            throws RedirectException, IOException, ProviderException {
542        boolean created = false;
543
544        try {
545            filename = AttachmentManager.validateFileName( filename );
546        } catch( final WikiException e ) {
547            // this is a kludge, the exception that is caught here contains the i18n key
548            // here we have the context available, so we can internationalize it properly :
549            throw new RedirectException (Preferences.getBundle( context, InternationalizationManager.CORE_BUNDLE )
550                    .getString( e.getMessage() ), errorPage );
551        }
552
553        //
554        //  FIXME: This has the unfortunate side effect that it will receive the
555        //  contents.  But we can't figure out the page to redirect to
556        //  before we receive the file, due to the stupid constructor of MultipartRequest.
557        //
558
559        if( !context.hasAdminPermissions() ) {
560            if( contentLength > m_maxSize ) {
561                // FIXME: Does not delete the received files.
562                throw new RedirectException( "File exceeds maximum size ("+m_maxSize+" bytes)", errorPage );
563            }
564
565            if( !isTypeAllowed(filename) ) {
566                throw new RedirectException( "Files of this type may not be uploaded to this wiki", errorPage );
567            }
568        }
569
570        final Principal user    = context.getCurrentUser();
571        final AttachmentManager mgr = m_engine.getManager( AttachmentManager.class );
572
573        LOG.debug("file="+filename);
574
575        if( data == null ) {
576            LOG.error("File could not be opened.");
577            throw new RedirectException("File could not be opened.", errorPage);
578        }
579
580        //  Check whether we already have this kind of page. If the "page" parameter already defines an attachment
581        //  name for an update, then we just use that file. Otherwise, we create a new attachment, and use the
582        //  filename given.  Incidentally, this will also mean that if the user uploads a file with the exact
583        //  same name than some other previous attachment, then that attachment gains a new version.
584        Attachment att = mgr.getAttachmentInfo( context.getPage().getName() );
585        if( att == null ) {
586            att = new org.apache.wiki.attachment.Attachment( m_engine, parentPage, filename );
587            created = true;
588        }
589        att.setSize( contentLength );
590
591        //  Check if we're allowed to do this?
592        final Permission permission = PermissionFactory.getPagePermission( att, "upload" );
593        if( m_engine.getManager( AuthorizationManager.class ).checkPermission( context.getWikiSession(), permission ) ) {
594            if( user != null ) {
595                att.setAuthor( user.getName() );
596            }
597
598            if( changenote != null && !changenote.isEmpty() ) {
599                att.setAttribute( Page.CHANGENOTE, changenote );
600            }
601
602            try {
603                m_engine.getManager( AttachmentManager.class ).storeAttachment( att, data );
604            } catch( final ProviderException pe ) {
605                // this is a kludge, the exception that is caught here contains the i18n key
606                // here we have the context available, so we can internationalize it properly :
607                throw new ProviderException( Preferences.getBundle( context, InternationalizationManager.CORE_BUNDLE ).getString( pe.getMessage() ) );
608            }
609
610            LOG.info( "User " + user + " uploaded attachment to " + parentPage + " called "+filename+", size " + att.getSize() );
611        } else {
612            throw new RedirectException( "No permission to upload a file", errorPage );
613        }
614
615        return created;
616    }
617
618    /**
619     *  Provides tracking for upload progress.
620     *
621     */
622    private static class UploadListener extends ProgressItem implements ProgressListener {
623        public long m_currentBytes;
624        public long m_totalBytes;
625
626        @Override
627        public void update( final long recvdBytes, final long totalBytes, final int item) {
628            m_currentBytes = recvdBytes;
629            m_totalBytes   = totalBytes;
630        }
631
632        @Override
633        public int getProgress() {
634            return ( int )( ( ( float )m_currentBytes / m_totalBytes ) * 100 + 0.5 );
635        }
636    }
637
638}
639
640