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.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
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.core.Session;
029import org.apache.wiki.api.providers.WikiProvider;
030import org.apache.wiki.api.spi.Wiki;
031import org.apache.wiki.auth.AuthorizationManager;
032import org.apache.wiki.auth.permissions.PagePermission;
033import org.apache.wiki.diff.DifferenceManager;
034import org.apache.wiki.pages.PageManager;
035import org.apache.wiki.pages.PageTimeComparator;
036import org.apache.wiki.render.RenderingManager;
037import org.apache.wiki.util.HttpUtil;
038import org.apache.wiki.util.Synchronizer;
039import org.apache.wiki.util.TextUtil;
040import org.apache.wiki.variables.VariableManager;
041
042import java.io.File;
043import java.util.Iterator;
044import java.util.List;
045import java.util.Objects;
046import java.util.Properties;
047import java.util.Set;
048import java.util.concurrent.locks.ReentrantLock;
049
050
051/**
052 * Default implementation for {@link RSSGenerator}.
053 * {@inheritDoc}
054 */
055// FIXME: Limit diff and page content size.
056public class DefaultRSSGenerator implements RSSGenerator {
057
058    private static final Logger LOG = LogManager.getLogger( DefaultRSSGenerator.class );
059    private final Engine m_engine;
060
061    /** The RSS file to generate. */
062    private final String m_rssFile;
063    private String m_channelDescription = "";
064    private String m_channelLanguage = "en-us";
065    private boolean m_enabled = true;
066
067    private static final int MAX_CHARACTERS = Integer.MAX_VALUE-1;
068
069    /**
070     * A lock used to ensure thread safety when accessing shared resources.
071     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
072     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
073     * waiting to acquire a lock.
074     *
075     * @see java.util.concurrent.locks.ReentrantLock
076     */
077    private final ReentrantLock lock = new ReentrantLock();
078
079    /**
080     *  Builds the RSS generator for a given Engine.
081     *
082     *  @param engine The Engine.
083     *  @param properties The properties.
084     */
085    public DefaultRSSGenerator( final Engine engine, final Properties properties ) {
086        m_engine = engine;
087        m_channelDescription = properties.getProperty( PROP_CHANNEL_DESCRIPTION, m_channelDescription );
088        m_channelLanguage = properties.getProperty( PROP_CHANNEL_LANGUAGE, m_channelLanguage );
089        m_rssFile = TextUtil.getStringProperty( properties, DefaultRSSGenerator.PROP_RSSFILE, "rss.rdf" );
090    }
091
092    /**
093     * {@inheritDoc}
094     *
095     * Start the RSS generator & generator thread
096     */
097    @Override
098    public void initialize( final Engine engine, final Properties properties ) {
099        final File rssFile;
100        if( m_rssFile.startsWith( File.separator ) ) { // honor absolute pathnames
101            rssFile = new File( m_rssFile );
102        } else { // relative path names are anchored from the webapp root path
103            rssFile = new File( engine.getRootPath(), m_rssFile );
104        }
105        if (!rssFile.getParentFile().exists()) {
106            if (!rssFile.getParentFile().mkdirs()) {
107                LOG.warn("Failed to mkdirs at " + rssFile.getParentFile().getAbsolutePath() + " rss feeds will probably fail");
108            }
109        }
110        final int rssInterval = TextUtil.getIntegerProperty( properties, DefaultRSSGenerator.PROP_INTERVAL, 3600 );
111        final RSSThread rssThread = new RSSThread( engine, rssFile, rssInterval );
112        rssThread.start();
113    }
114
115    /** Feed readers need absolute links; without a request there is no origin to derive one from, so the URL is returned as is. */
116    private String toAbsoluteUrl( final Context wikiContext, final String url ) {
117        if( wikiContext.getHttpRequest() == null || !( url.isEmpty() || url.startsWith( "/" ) ) ) {
118            return url;
119        }
120        return HttpUtil.getAbsoluteUrl( wikiContext.getHttpRequest(), url );
121    }
122
123    private String getAuthor( final Page page ) {
124        String author = page.getAuthor();
125        if( author == null ) {
126            author = "An unknown author";
127        }
128
129        return author;
130    }
131
132    private String getAttachmentDescription( final Attachment att ) {
133        final String author = getAuthor( att );
134        final StringBuilder sb = new StringBuilder();
135
136        if( att.getVersion() != 1 ) {
137            sb.append( author ).append( " uploaded a new version of this attachment on " ).append( att.getLastModified() );
138        } else {
139            sb.append( author ).append( " created this attachment on " ).append( att.getLastModified() );
140        }
141
142        sb.append( "<br /><hr /><br />" )
143          .append( "Parent page: <a href=\"" )
144          .append( m_engine.getURL( ContextEnum.PAGE_VIEW.getRequestContext(), att.getParentName(), null ) )
145          .append( "\">" ).append( att.getParentName() ).append( "</a><br />" )
146          .append( "Info page: <a href=\"" )
147          .append( m_engine.getURL( ContextEnum.PAGE_INFO.getRequestContext(), att.getName(), null ) )
148          .append( "\">" ).append( att.getName() ).append( "</a>" );
149
150        return sb.toString();
151    }
152
153    /**
154     * Returns the latest version of a page that is older than the given one, or 0 if there is none. The versions of a page need not be
155     * contiguous, as any of them can have been deleted.
156     */
157    private int previousVersion( final Page page ) {
158        final List< Page > history = m_engine.getManager( PageManager.class ).getVersionHistory( page.getName() );
159        int previous = 0;
160        if( history != null ) {
161            for( final Page version : history ) {
162                if( version.getVersion() < page.getVersion() && version.getVersion() > previous ) {
163                    previous = version.getVersion();
164                }
165            }
166        }
167        return previous;
168    }
169
170    private String getPageDescription( final Page page ) {
171        final StringBuilder buf = new StringBuilder();
172        final String author = getAuthor( page );
173        final Context ctx = Wiki.context().create( m_engine, page );
174        final int previous = previousVersion( page );
175        if( previous > 0 ) {
176            final String diff = m_engine.getManager( DifferenceManager.class ).getDiff( ctx, previous, page.getVersion() );
177
178            buf.append( author ).append( " changed this page on " ).append( page.getLastModified() ).append( ":<br /><hr /><br />" );
179            buf.append( diff );
180        } else {
181            buf.append( author ).append( " created this page on " ).append( page.getLastModified() ).append( ":<br /><hr /><br />" );
182            buf.append( m_engine.getManager( RenderingManager.class ).getHTML( page.getName() ) );
183        }
184
185        return buf.toString();
186    }
187
188    private String getEntryDescription( final Page page ) {
189        final String res;
190        if( page instanceof Attachment ) {
191            res = getAttachmentDescription( (Attachment)page );
192        } else {
193            res = getPageDescription( page );
194        }
195
196        return res;
197    }
198
199    // FIXME: This should probably return something more intelligent
200    private String getEntryTitle( final Page page ) {
201        return page.getName() + ", version " + page.getVersion();
202    }
203
204    /** {@inheritDoc} */
205    @Override
206    public String generate() {
207        final Context context = Wiki.context().create( m_engine, Wiki.contents().page( m_engine, "__DUMMY" ) );
208        context.setRequestContext( ContextEnum.PAGE_RSS.getRequestContext() );
209        final Feed feed = new RSS10Feed( context );
210        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + generateFullWikiRSS( context, feed );
211    }
212
213    /** {@inheritDoc} */
214    @Override
215    public String generateFeed( final Context wikiContext, final List< Page > changed, final String mode, final String type ) throws IllegalArgumentException {
216        final Feed feed;
217        final String res;
218
219        if( ATOM.equals(type) ) {
220            feed = new AtomFeed( wikiContext );
221        } else if( RSS20.equals( type ) ) {
222            feed = new RSS20Feed( wikiContext );
223        } else {
224            feed = new RSS10Feed( wikiContext );
225        }
226
227        feed.setMode( mode );
228
229        if( MODE_BLOG.equals( mode ) ) {
230            res = generateBlogRSS( wikiContext, changed, feed );
231        } else if( MODE_FULL.equals(mode) ) {
232            res = generateFullWikiRSS( wikiContext, feed );
233        } else if( MODE_WIKI.equals(mode) ) {
234            res = generateWikiPageRSS( wikiContext, changed, feed );
235        } else {
236            throw new IllegalArgumentException( "Invalid value for feed mode: "+mode );
237        }
238
239        return res;
240    }
241
242    /** {@inheritDoc} */
243    @Override
244    public boolean isEnabled() {
245      return  Synchronizer.synchronize(lock, () -> m_enabled);
246    }
247
248    /** {@inheritDoc} */
249    @Override
250    public void setEnabled( final boolean enabled ) {
251        Synchronizer.synchronize(lock, () -> {
252            m_enabled = enabled;
253        });
254    }
255
256    /** {@inheritDoc} */
257    @Override
258    public String getRssFile() {
259        return m_rssFile;
260    }
261
262    /** {@inheritDoc} */
263    @Override
264    public String generateFullWikiRSS( final Context wikiContext, final Feed feed ) {
265        feed.setChannelTitle( m_engine.getApplicationName() );
266        feed.setFeedURL( toAbsoluteUrl( wikiContext, m_engine.getBaseURL() ) );
267        feed.setChannelLanguage( m_channelLanguage );
268        feed.setChannelDescription( m_channelDescription );
269
270        final Set< Page > changed = m_engine.getManager( PageManager.class ).getRecentChanges();
271        final AuthorizationManager mgr = wikiContext.getEngine().getManager(AuthorizationManager.class);
272
273        final Session session = Wiki.session().guest( m_engine );
274        int items = 0;
275        for( final Iterator< Page > i = changed.iterator(); i.hasNext() && items < 15; items++ ) {
276            final Page page = i.next();
277
278            //  Check if the anonymous user has view access to this page.
279            if( !mgr.checkPermission(session, new PagePermission(page,PagePermission.VIEW_ACTION) ) ) {
280                // No permission, skip to the next one.
281                continue;
282            }
283
284            final String url;
285            if( page instanceof Attachment ) {
286                url = m_engine.getURL( ContextEnum.PAGE_ATTACH.getRequestContext(), page.getName(),null );
287            } else {
288                url = m_engine.getURL( ContextEnum.PAGE_VIEW.getRequestContext(), page.getName(), null );
289            }
290
291            final Entry e = new Entry();
292            e.setPage( page );
293            e.setURL( toAbsoluteUrl( wikiContext, url ) );
294            e.setTitle( page.getName() );
295            e.setContent( getEntryDescription(page) );
296            e.setAuthor( getAuthor(page) );
297
298            feed.addEntry( e );
299        }
300
301        return feed.getString();
302    }
303
304    /** {@inheritDoc} */
305    @Override
306    public String generateWikiPageRSS( final Context wikiContext, final List< Page > changed, final Feed feed ) {
307        feed.setChannelTitle( m_engine.getApplicationName()+": "+wikiContext.getPage().getName() );
308        feed.setFeedURL( toAbsoluteUrl( wikiContext, wikiContext.getViewURL( wikiContext.getPage().getName() ) ) );
309        final String language = m_engine.getManager( VariableManager.class ).getVariable( wikiContext, PROP_CHANNEL_LANGUAGE );
310
311        if( language != null ) {
312            feed.setChannelLanguage( language );
313        } else {
314            feed.setChannelLanguage( m_channelLanguage );
315        }
316        final String channelDescription = m_engine.getManager( VariableManager.class ).getVariable( wikiContext, PROP_CHANNEL_DESCRIPTION );
317
318        if( channelDescription != null ) {
319            feed.setChannelDescription( channelDescription );
320        }
321
322        changed.sort( new PageTimeComparator() );
323        final AuthorizationManager mgr = wikiContext.getEngine().getManager(AuthorizationManager.class);
324
325        int items = 0;
326        for( final Iterator< Page > i = changed.iterator(); i.hasNext() && items < 15; items++ ) {
327            final Page page = i.next();
328            if( !mgr.checkPermission( wikiContext.getWikiSession(), new PagePermission(page, PagePermission.VIEW_ACTION) ) ) {
329                continue;
330            }
331            final Entry e = new Entry();
332            e.setPage( page );
333            String url;
334
335            if( page instanceof Attachment ) {
336                url = m_engine.getURL( ContextEnum.PAGE_ATTACH.getRequestContext(), page.getName(), "version=" + page.getVersion() );
337            } else {
338                url = m_engine.getURL( ContextEnum.PAGE_VIEW.getRequestContext(), page.getName(), "version=" + page.getVersion() );
339            }
340
341            // Unfortunately, this is needed because the code will again go through replacement conversion
342            url = TextUtil.replaceString( url, "&amp;", "&" );
343            e.setURL( toAbsoluteUrl( wikiContext, url ) );
344            e.setTitle( getEntryTitle(page) );
345            e.setContent( getEntryDescription(page) );
346            e.setAuthor( getAuthor(page) );
347
348            feed.addEntry( e );
349        }
350
351        return feed.getString();
352    }
353
354
355    /** {@inheritDoc} */
356    @Override
357    public String generateBlogRSS( final Context wikiContext, final List< Page > changed, final Feed feed ) {
358        LOG.debug( "Generating RSS for blog, size={}", changed.size() );
359
360        final String ctitle = m_engine.getManager( VariableManager.class ).getVariable( wikiContext, PROP_CHANNEL_TITLE );
361        feed.setChannelTitle(Objects.requireNonNullElseGet(ctitle, () -> m_engine.getApplicationName() + ":" + wikiContext.getPage().getName()));
362
363        feed.setFeedURL( toAbsoluteUrl( wikiContext, wikiContext.getViewURL( wikiContext.getPage().getName() ) ) );
364
365        final String language = m_engine.getManager( VariableManager.class ).getVariable( wikiContext, PROP_CHANNEL_LANGUAGE );
366        if( language != null ) {
367            feed.setChannelLanguage( language );
368        } else {
369            feed.setChannelLanguage( m_channelLanguage );
370        }
371
372        final String channelDescription = m_engine.getManager( VariableManager.class ).getVariable( wikiContext, PROP_CHANNEL_DESCRIPTION );
373        if( channelDescription != null ) {
374            feed.setChannelDescription( channelDescription );
375        }
376
377        changed.sort( new PageTimeComparator() );
378
379        final Session session = Wiki.session().guest( m_engine );
380        int items = 0;
381        for( final Iterator< Page > i = changed.iterator(); i.hasNext() && items < 15; items++ ) {
382            final Page page = i.next();
383
384            //  The feed is cached and shared, so it lists only the entries that the anonymous user may view.
385            if( !m_engine.getManager( AuthorizationManager.class ).checkPermission( session, new PagePermission( page, PagePermission.VIEW_ACTION ) ) ) {
386                continue;
387            }
388
389            final Entry e = new Entry();
390            e.setPage( page );
391            final String url;
392
393            if( page instanceof Attachment ) {
394                url = m_engine.getURL( ContextEnum.PAGE_ATTACH.getRequestContext(), page.getName(),null );
395            } else {
396                url = m_engine.getURL( ContextEnum.PAGE_VIEW.getRequestContext(), page.getName(),null );
397            }
398
399            e.setURL( toAbsoluteUrl( wikiContext, url ) );
400
401            //  Title
402            String pageText = m_engine.getManager( PageManager.class ).getPureText( page.getName(), WikiProvider.LATEST_VERSION );
403
404            String title = "";
405            final int firstLine = pageText.indexOf('\n');
406
407            if( firstLine > 0 ) {
408                title = pageText.substring( 0, firstLine ).trim();
409            }
410
411            if( title.isEmpty() ) {
412                title = page.getName();
413            }
414
415            // Remove wiki formatting
416            while( title.startsWith("!") ) {
417                title = title.substring(1);
418            }
419
420            e.setTitle( title );
421
422            //  Description
423            if( firstLine > 0 ) {
424                int maxlen = pageText.length();
425                if( maxlen > MAX_CHARACTERS ) {
426                    maxlen = MAX_CHARACTERS;
427                }
428                pageText = m_engine.getManager( RenderingManager.class ).textToHTML( wikiContext, pageText.substring( firstLine + 1, maxlen ).trim() );
429                if( maxlen == MAX_CHARACTERS ) {
430                    pageText += "...";
431                }
432                e.setContent( pageText );
433            } else {
434                e.setContent( title );
435            }
436            e.setAuthor( getAuthor(page) );
437            feed.addEntry( e );
438        }
439
440        return feed.getString();
441    }
442
443}