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.rss;
020
021import org.apache.commons.lang3.time.DateFormatUtils;
022import org.apache.wiki.api.Release;
023import org.apache.wiki.api.core.Attachment;
024import org.apache.wiki.api.core.Context;
025import org.apache.wiki.api.core.ContextEnum;
026import org.apache.wiki.api.core.Engine;
027import org.apache.wiki.api.core.Page;
028import org.apache.wiki.api.exceptions.ProviderException;
029import org.apache.wiki.attachment.AttachmentManager;
030import org.jdom2.Element;
031import org.jdom2.Namespace;
032import org.jdom2.output.Format;
033import org.jdom2.output.XMLOutputter;
034
035import jakarta.servlet.ServletContext;
036import java.io.IOException;
037import java.io.StringWriter;
038import java.util.ArrayList;
039import java.util.Collection;
040import java.util.Date;
041import java.util.List;
042import org.apache.logging.log4j.LogManager;
043import org.apache.logging.log4j.Logger;
044import org.apache.wiki.auth.AuthorizationManager;
045import org.apache.wiki.auth.permissions.PagePermission;
046
047/**
048 *  Provides an Atom 1.0 standard feed, with enclosures.
049 *
050 */
051public class AtomFeed extends Feed {
052    
053    private static final Logger LOG = LogManager.getLogger( AtomFeed.class );
054
055    private final Namespace m_atomNameSpace = Namespace.getNamespace("http://www.w3.org/2005/Atom");
056
057    /** Defines a SimpleDateFormat string for RFC3339-formatted dates. */
058    public static final String RFC3339FORMAT = "yyyy-MM-dd'T'HH:mm:ssZZ";
059
060    /**
061     *  Create a new AtomFeed for a given WikiContext.
062     *  
063     *  @param c A WikiContext.
064     */
065    public AtomFeed( final Context c )
066    {
067        super(c);
068    }
069
070    /**
071     *   This is a bit complicated right now, as there is no proper metadata store in JSPWiki.
072     *
073     *   @return An unique feed ID.
074     */
075    private String getFeedID()
076    {
077        return m_wikiContext.getEngine().getBaseURL(); // FIXME: This is not a feed id
078    }
079
080    private String getEntryID( final Entry e )
081    {
082        return e.getURL(); // FIXME: Not really a feed id!
083    }
084
085    private Collection<Element> getItems() {
086        final ArrayList< Element > list = new ArrayList<>();
087        final Engine engine = m_wikiContext.getEngine();
088        ServletContext servletContext = null;
089        if( m_wikiContext.getHttpRequest() != null ) {
090            servletContext = m_wikiContext.getHttpRequest().getSession().getServletContext();
091        }
092        final AuthorizationManager mgr = m_wikiContext.getEngine().getManager(AuthorizationManager.class);
093
094        for( final Entry e : m_entries ) {
095            final Page p = e.getPage();
096            if( !m_wikiContext.getEngine().getManager( AuthorizationManager.class ).checkPermission(m_wikiContext.getWikiSession(), 
097                    new PagePermission(p,PagePermission.VIEW_ACTION) ) ) {
098                // No permission, skip to the next one.
099                continue;
100            }
101            final Element entryEl = getElement( "entry" );
102
103            //  Mandatory elements
104            entryEl.addContent( getElement( "id" ).setText( getEntryID( e ) ) );
105            entryEl.addContent( getElement( "title" ).setAttribute( "type", "html" ).setText( e.getTitle() ) );
106            entryEl.addContent( getElement( "updated" ).setText( DateFormatUtils.formatUTC( p.getLastModified(), RFC3339FORMAT ) ) );
107
108            //  Optional elements
109            entryEl.addContent( getElement( "author" ).addContent( getElement( "name" ).setText( e.getAuthor() ) ) );
110            entryEl.addContent( getElement( "link" ).setAttribute( "rel", "alternate" ).setAttribute( "href", e.getURL() ) );
111            entryEl.addContent( getElement( "content" ).setAttribute( "type", "html" ).setText( e.getContent() ) );
112
113            //  Check for enclosures
114            if( engine.getManager( AttachmentManager.class ).hasAttachments( p ) && servletContext != null ) {
115                try {
116                    final List< Attachment > c = engine.getManager( AttachmentManager.class ).listAttachments( p );
117                    for( final Attachment att : c ) {
118                        final Element attEl = getElement( "link" );
119                        attEl.setAttribute( "rel", "enclosure" );
120                        attEl.setAttribute( "href", engine.getURL( ContextEnum.PAGE_ATTACH.getRequestContext(), att.getName(), null ) );
121                        attEl.setAttribute( "length", Long.toString( att.getSize() ) );
122                        attEl.setAttribute( "type", getMimeType( servletContext, att.getFileName() ) );
123
124                        entryEl.addContent( attEl );
125                    }
126                } catch( final ProviderException ex ) {
127                    LOG.info("Can't get attachment data",ex);
128                }
129            }
130
131            list.add( entryEl );
132        }
133
134        return list;
135    }
136
137    /**
138     *  {@inheritDoc}
139     */
140    @Override
141    public String getString() {
142        final Element root = getElement("feed");
143        final Engine engine = m_wikiContext.getEngine();
144
145        Date lastModified = new Date(0L);
146
147        for( final Entry e : m_entries ) {
148            if( e.getPage().getLastModified().after( lastModified ) ) {
149                lastModified = e.getPage().getLastModified();
150            }
151        }
152
153        //  Mandatory parts
154        root.addContent( getElement( "title" ).setText( getChannelTitle() ) );
155        root.addContent( getElement( "id" ).setText( getFeedID() ) );
156        root.addContent( getElement( "updated" ).setText( DateFormatUtils.formatUTC( lastModified, RFC3339FORMAT ) ) );
157
158        //  Optional
159        // root.addContent( getElement("author").addContent(getElement("name").setText(format())))
160        root.addContent( getElement( "link" ).setAttribute( "href", engine.getBaseURL() ) );
161        root.addContent( getElement( "generator" ).setText( "JSPWiki " + Release.VERSTR ) );
162
163        final String rssFeedURL  = engine.getURL( ContextEnum.PAGE_NONE.getRequestContext(), "rss.jsp",
164                                                 "page=" + engine.encodeName( m_wikiContext.getPage().getName() ) +
165                                                 "&mode=" + m_mode +
166                                                 "&type=atom" );
167        final Element self = getElement( "link" ).setAttribute( "rel","self" );
168        self.setAttribute( "href", rssFeedURL );
169        root.addContent( self );
170
171        //  Items
172        root.addContent( getItems() );
173
174        //  aaand output
175        final XMLOutputter output = new XMLOutputter();
176        output.setFormat( Format.getPrettyFormat() );
177
178        try {
179            final StringWriter res = new StringWriter();
180            output.output( root, res );
181
182            return res.toString();
183        } catch( final IOException e ) {
184            LOG.debug(e.getMessage(), e);
185            return null;
186        }
187    }
188
189    private Element getElement( final String name ) {
190        return new Element( name, m_atomNameSpace );
191    }
192
193}