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.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.api.core.Context;
024import org.apache.wiki.api.core.ContextEnum;
025import org.apache.wiki.api.core.Page;
026import org.apache.wiki.api.exceptions.PluginException;
027import org.apache.wiki.api.plugin.Plugin;
028import org.apache.wiki.pages.PageManager;
029import org.apache.wiki.preferences.Preferences;
030import org.apache.wiki.references.ReferenceManager;
031import org.apache.wiki.util.TextUtil;
032
033import java.text.MessageFormat;
034import java.util.Collection;
035import java.util.Locale;
036import java.util.Map;
037import java.util.ResourceBundle;
038import java.util.stream.Collectors;
039
040/**
041 *  Displays the pages referring to the current page.
042 *
043 *  Parameters:
044 *  <ul>
045 *  <li><b>max</b> - How many items to show.</li>
046 *  <li><b>extras</b> - How to announce extras.</li>
047 *  <li><b>page</b> - Which page to get the table of contents from.</li>
048 *  </ul>
049 *
050 *  From AbstractReferralPlugin:
051 *  <ul>
052 *  <li><b>separator</b> - How to separate generated links; default is a wikitext line break, producing a vertical list.</li>
053 *  <li><b>maxwidth</b> - maximum width, in chars, of generated links.</li>
054 *  </ul>
055 */
056public class ReferringPagesPlugin extends AbstractReferralPlugin {
057
058    private static final Logger LOG = LogManager.getLogger( ReferringPagesPlugin.class );
059
060    /** Parameter name for setting the maximum items to show.  Value is <tt>{@value}</tt>. */
061    public static final String PARAM_MAX      = "max";
062
063    /** Parameter name for setting the text to show when the maximum items is overruled. Value is <tt>{@value}</tt>. */
064    public static final String PARAM_EXTRAS   = "extras";
065
066    /** Parameter name for choosing the page.  Value is <tt>{@value}</tt>. */
067    public static final String PARAM_PAGE     = "page";
068
069    @Override
070    public String getDisplayName(Locale locale) {
071        final ResourceBundle rb = ResourceBundle.getBundle(PluginManager.PLUGIN_I18N_RESOURCE, locale);
072        return rb.getString(this.getClass().getSimpleName());
073    }
074    
075    @Override
076    public String getSnipExample() {
077        return "ReferringPagesPlugin page='{pagename}' separator=',' include='regexp' exclude='regexp'";
078    }
079    
080    /**
081     *  {@inheritDoc}
082     */
083    @Override
084    public String execute( final Context context, final Map< String, String > params ) throws PluginException {
085        final ReferenceManager refmgr = context.getEngine().getManager( ReferenceManager.class );
086        String pageName = params.get( PARAM_PAGE );
087        final ResourceBundle rb = Preferences.getBundle( context, Plugin.CORE_PLUGINS_RESOURCEBUNDLE );
088
089        StringBuilder result = new StringBuilder( 256 );
090
091        if( pageName == null ) {
092            pageName = context.getPage().getName();
093        }
094
095        final Page page = context.getEngine().getManager( PageManager.class ).getPage( pageName );
096        if( page != null ) {
097            Collection< String > links  = refmgr.findReferrers( page.getName() );
098            String wikitext;
099
100            super.initialize( context, params );
101
102            final int items = TextUtil.parseIntParameter( params.get( PARAM_MAX ), ALL_ITEMS );
103
104            String extras = TextUtil.replaceEntities( params.get( PARAM_EXTRAS ) );
105            if( extras == null ) {
106                extras = rb.getString( "referringpagesplugin.more" );
107            }
108
109            LOG.debug( "Fetching referring pages for {} with a max of {}", page.getName(), items );
110
111            if( links != null && !links.isEmpty()) {
112                links = filterAndSortCollection( links.stream().filter( name -> mayView( context, name ) ).collect( Collectors.toList() ) );
113                wikitext = wikitizeCollection( links, m_separator, items );
114
115                result.append( applyColumnsStyle( makeHTML( context, wikitext ) ) );
116
117                if( items < links.size() && items > 0 ) {
118                    final Object[] args = { "" + ( links.size() - items ) };
119                    extras = MessageFormat.format( extras, args );
120
121                    result.append( "<br />" )
122                          .append( "<a class='morelink' href='" )
123                          .append( context.getURL( ContextEnum.PAGE_INFO.getRequestContext(), page.getName() ) )
124                          .append( "' " )
125                          .append( ">" )
126                          .append( extras )
127                          .append( "</a><br />" );
128                }
129            }
130
131            // If nothing was left after filtering or during search
132            if( links == null || links.isEmpty()) {
133                wikitext = rb.getString( "referringpagesplugin.nobody" );
134                result.append( makeHTML( context, wikitext ) );
135            } else  if( m_show.equals( PARAM_SHOW_VALUE_COUNT ) ) {
136                result = new StringBuilder();
137                result.append( links.size() );
138                if( m_lastModified ) {
139                    result.append( " (" ).append( m_dateFormat.format( m_dateLastModified ) ).append( ")" );
140                }
141            }
142
143            return result.toString();
144        }
145
146        return "";
147    }
148
149}