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.plugin;
020
021import org.apache.commons.lang3.StringUtils;
022import org.apache.logging.log4j.LogManager;
023import org.apache.logging.log4j.Logger;
024import org.apache.wiki.WikiContext;
025import org.apache.wiki.api.core.Context;
026import org.apache.wiki.api.core.ContextEnum;
027import org.apache.wiki.api.core.Engine;
028import org.apache.wiki.api.core.Page;
029import org.apache.wiki.api.exceptions.PluginException;
030import org.apache.wiki.api.plugin.Plugin;
031import org.apache.wiki.attachment.Attachment;
032import org.apache.wiki.auth.AuthorizationManager;
033import org.apache.wiki.auth.permissions.PermissionFactory;
034import org.apache.wiki.i18n.InternationalizationManager;
035import org.apache.wiki.pages.PageManager;
036import org.apache.wiki.preferences.Preferences;
037import org.apache.wiki.preferences.Preferences.TimeFormat;
038import org.apache.wiki.render.RenderingManager;
039import org.apache.wiki.util.TextUtil;
040import org.apache.wiki.util.XHTML;
041import org.apache.wiki.util.XhtmlUtil;
042import org.jdom2.Element;
043
044import java.text.DateFormat;
045import java.text.SimpleDateFormat;
046import java.util.Calendar;
047import java.util.Collection;
048import java.util.Date;
049import java.util.GregorianCalendar;
050import java.util.Locale;
051import java.util.Map;
052import java.util.ResourceBundle;
053import java.util.stream.Collectors;
054
055
056/**
057 *  Returns the Recent Changes in the wiki being a date-sorted list of page names.
058 *
059 *  <p>Parameters: </p>
060 *  <ul>
061 *  <li><b>since</b> - show changes from the last n days, for example since=5 shows only the pages that were changed in the last five days</li>
062 *  <li><b>format</b> - (full|compact) : if "full", then display a long version with all possible info. If "compact", then be as compact as possible.</li>
063 *  <li><b>timeFormat</b> - the time format to use, the default is "HH:mm:ss"</li>
064 *  <li><b>dateFormat</b> - the date format to use, the default is "dd.MM.yyyy"</li>
065 *  </ul>
066 */
067public class RecentChangesPlugin extends AbstractReferralPlugin implements Plugin {
068    
069    private static final Logger LOG = LogManager.getLogger( RecentChangesPlugin.class );
070    
071    /** Parameter name for the separator format.  Value is <tt>{@value}</tt>. */
072    public static final String PARAM_FORMAT      = "format";
073    /** Parameter name for the separator timeFormat.  Value is <tt>{@value}</tt>. */
074    public static final String PARAM_TIME_FORMAT = "timeFormat";
075    /** Parameter name for the separator dateFormat.  Value is <tt>{@value}</tt>. */
076    public static final String PARAM_DATE_FORMAT = "dateFormat";
077
078    /** How many days we show by default. */
079    private static final int   DEFAULT_DAYS = 100*365;
080    public static final String DEFAULT_TIME_FORMAT ="HH:mm:ss";
081    public static final String DEFAULT_DATE_FORMAT ="dd.MM.yyyy";
082
083
084    @Override
085    public String getDisplayName(Locale locale) {
086        final ResourceBundle rb = ResourceBundle.getBundle(PluginManager.PLUGIN_I18N_RESOURCE, locale);
087        return rb.getString(this.getClass().getSimpleName());
088    }
089   
090    
091    /**
092     * {@inheritDoc}
093     */
094    @Override
095    public String execute( final Context context, final Map< String, String > params ) throws PluginException {
096        final int since = TextUtil.parseIntParameter( params.get( "since" ), DEFAULT_DAYS );
097        String spacing  = "4";
098        boolean showAuthor = true;
099        boolean showChangenote = true;
100        String tablewidth = "4";
101        
102        final Engine engine = context.getEngine();
103
104        //
105        //  Which format we want to see?
106        //
107        if( "compact".equals( params.get( PARAM_FORMAT ) ) ) {
108            spacing  = "0";
109            showAuthor = false;
110            showChangenote = false;
111            tablewidth = "2";
112        }
113
114        final Calendar sincedate = new GregorianCalendar();
115        sincedate.add( Calendar.DAY_OF_MONTH, -since );
116
117        LOG.debug("Calculating recent changes from "+sincedate.getTime());
118
119        // FIXME: Should really have a since date on the getRecentChanges method.
120        Collection< Page > changes = engine.getManager( PageManager.class ).getRecentChanges();
121        super.initialize( context, params );
122        changes = filterWikiPageCollection( changes );
123
124        // The list is shown to everybody, so it holds only the pages and attachments that the viewer may view.
125        final AuthorizationManager authorizationManager = engine.getManager( AuthorizationManager.class );
126        changes = changes.stream()
127                         .filter( page -> authorizationManager.checkPermission( context.getWikiSession(),
128                                                                                PermissionFactory.getPagePermission( page, "view" ) ) )
129                         .collect( Collectors.toList() );
130        
131        if ( changes != null ) {
132            Date olddate = new Date( 0 );
133
134            final DateFormat fmt = getDateFormat( context, params );
135            final DateFormat tfmt = getTimeFormat( context, params );
136
137            final Element rt = XhtmlUtil.element( XHTML.table );
138            rt.setAttribute( XHTML.ATTR_class, "recentchanges" );
139            rt.setAttribute( XHTML.ATTR_cellpadding, spacing );
140
141            for( final Page pageref : changes ) {
142                final Date lastmod = pageref.getLastModified();
143
144                if( lastmod.before( sincedate.getTime() ) ) {
145                    break;
146                }
147
148                if( !isSameDay( lastmod, olddate ) ) {
149                    final Element row = XhtmlUtil.element( XHTML.tr );
150                    final Element col = XhtmlUtil.element( XHTML.td );
151                    col.setAttribute( XHTML.ATTR_colspan, tablewidth );
152                    col.setAttribute( XHTML.ATTR_class, "date" );
153                    col.addContent( XhtmlUtil.element( XHTML.b, fmt.format( lastmod ) ) );
154
155                    rt.addContent( row );
156                    row.addContent( col );
157                    olddate = lastmod;
158                }
159
160                final String href = context.getURL( pageref instanceof Attachment ? ContextEnum.PAGE_ATTACH.getRequestContext()
161                                                                                  : ContextEnum.PAGE_VIEW.getRequestContext(), pageref.getName() );
162                Element link = XhtmlUtil.link( href, engine.getManager( RenderingManager.class ).beautifyTitle( pageref.getName() ) );
163                final Element row = XhtmlUtil.element( XHTML.tr );
164                final Element col = XhtmlUtil.element( XHTML.td );
165                col.setAttribute( XHTML.ATTR_width, "30%" );
166                col.addContent( link );
167
168                //
169                //  Add the direct link to the attachment info.
170                //
171                if( pageref instanceof Attachment ) {
172                    link = XhtmlUtil.link( context.getURL( WikiContext.INFO, pageref.getName() ), null );
173                    link.setAttribute( XHTML.ATTR_class, "infolink" );
174
175                    final Element img = XhtmlUtil.img( context.getURL( WikiContext.NONE, "images/attachment_small.png" ), null );
176                    link.addContent( img );
177
178                    col.addContent( link );
179                }
180
181                row.addContent( col );
182                rt.addContent( row );
183
184                if( pageref instanceof Attachment ) {
185                    final Element td = XhtmlUtil.element( XHTML.td, tfmt.format( lastmod ) );
186                    td.setAttribute( XHTML.ATTR_class, "lastchange" );
187                    row.addContent( td );
188                } else {
189                    final Element infocol = XhtmlUtil.element( XHTML.td );
190                    infocol.setAttribute( XHTML.ATTR_class, "lastchange" );
191                    infocol.addContent( XhtmlUtil.link( context.getURL( WikiContext.DIFF, pageref.getName(), "r1=-1" ),
192                                                        tfmt.format( lastmod ) ) );
193                    row.addContent( infocol );
194                }
195
196                //
197                //  Display author information.
198                //
199                if( showAuthor ) {
200                    final String author = pageref.getAuthor();
201
202                    final Element authorinfo = XhtmlUtil.element( XHTML.td );
203                    authorinfo.setAttribute( XHTML.ATTR_class, "author" );
204
205                    if( author != null ) {
206                        if( engine.getManager( PageManager.class ).wikiPageExists( author ) ) {
207                            authorinfo.addContent( XhtmlUtil.link( context.getURL( WikiContext.VIEW, author ), author ) );
208                        } else {
209                            authorinfo.addContent( author );
210                        }
211                    } else {
212                        authorinfo.addContent( Preferences.getBundle( context, InternationalizationManager.CORE_BUNDLE )
213                                .getString( "common.unknownauthor" ) );
214                    }
215
216                    row.addContent( authorinfo );
217                }
218
219                // Change note
220                if( showChangenote ) {
221                    final String changenote = pageref.getAttribute( Page.CHANGENOTE );
222                    final Element td_changenote = XhtmlUtil.element( XHTML.td, changenote );
223                    td_changenote.setAttribute( XHTML.ATTR_class, "changenote" );
224                    row.addContent( td_changenote );
225                }
226
227                //  Revert note
228/*                
229                if( context.hasAdminPermissions() )
230                {
231                    row.addElement( new td("Revert") );
232                }
233 */
234            }
235            return XhtmlUtil.serialize( rt, XhtmlUtil.EXPAND_EMPTY_NODES );
236        }
237        return "";
238    }
239
240    
241    private boolean isSameDay( final Date a, final Date b ) {
242        final Calendar aa = Calendar.getInstance(); aa.setTime( a );
243        final Calendar bb = Calendar.getInstance(); bb.setTime( b );
244
245        return aa.get( Calendar.YEAR ) == bb.get( Calendar.YEAR ) 
246            && aa.get( Calendar.DAY_OF_YEAR ) == bb.get( Calendar.DAY_OF_YEAR );
247    }
248    
249
250    // TODO: Ideally the default behavior should be to return the default format for the default
251    // locale, but that is at odds with the 1st version of this plugin. We seek to preserve the
252    // behaviour of that first version, so to get the default format, the user must explicitly do
253    // something like: dateFormat='' timeformat='' which is a odd, but probably okay.
254    private DateFormat getTimeFormat( final Context context, final Map< String, String > params ) {
255        final String formatString = get( params, DEFAULT_TIME_FORMAT, PARAM_TIME_FORMAT );
256        if( StringUtils.isBlank( formatString ) ) {
257            return Preferences.getDateFormat( context, TimeFormat.TIME );
258        }
259
260        return new SimpleDateFormat( formatString );
261    }
262
263    private DateFormat getDateFormat( final Context context, final Map< String, String > params ) {
264        final String formatString = get( params, DEFAULT_DATE_FORMAT, PARAM_DATE_FORMAT );
265        if( StringUtils.isBlank( formatString ) ) {
266            return Preferences.getDateFormat( context, TimeFormat.DATE );
267        }
268
269        return new SimpleDateFormat( formatString );
270    }
271    
272    private String get( final Map< String, String > params, final String defaultValue, final String paramName ) {
273        final String value = params.get( paramName );
274        return value == null ? defaultValue : value;
275    }
276    
277}