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.Engine;
026import org.apache.wiki.api.core.Page;
027import org.apache.wiki.api.exceptions.PluginException;
028import org.apache.wiki.api.plugin.Plugin;
029import org.apache.wiki.pages.PageManager;
030import org.apache.wiki.references.ReferenceManager;
031import org.apache.wiki.util.TextUtil;
032
033import java.util.ArrayList;
034import java.util.Collection;
035import java.util.HashSet;
036import java.util.Map;
037import java.util.regex.Pattern;
038import java.util.regex.PatternSyntaxException;
039import org.apache.wiki.util.TimeLimitedRegex;
040
041
042/**
043 *  Displays the pages referring to the current page.
044 *
045 *  <p>Parameters</p>
046 *  <ul>
047 *    <li><b>name</b> - Name of the root page. Default name of calling page
048 *    <li><b>type</b> - local|externalattachment
049 *    <li><b>depth</b> - How many levels of pages to be parsed.
050 *    <li><b>include</b> - Include only these pages. (eg. include='UC.*|BP.*' )
051 *    <li><b>exclude</b> - Exclude with this pattern. (eg. exclude='LeftMenu' )
052 *    <li><b>format</b> -  full|compact, FULL now expands all levels correctly
053 *  </ul>
054 *
055 */
056public class ReferredPagesPlugin implements Plugin {
057
058    private static final Logger LOG = LogManager.getLogger( ReferredPagesPlugin.class );
059    private Engine m_engine;
060    private int m_depth;
061    private final HashSet< String > m_exists  = new HashSet<>();
062    private final StringBuffer m_result  = new StringBuffer( 1024 );
063    private Pattern m_includePattern;
064    private Pattern m_excludePattern;
065    private int items;
066    private boolean m_formatCompact = true;
067    private boolean m_formatSort;
068
069    /** The parameter name for the root page to start from.  Value is <tt>{@value}</tt>. */
070    public static final String PARAM_ROOT = "page";
071
072    /** The parameter name for the depth.  Value is <tt>{@value}</tt>. */
073    public static final String PARAM_DEPTH = "depth";
074
075    /** The parameter name for the type of the references.  Value is <tt>{@value}</tt>. */
076    public static final String PARAM_TYPE = "type";
077
078    /** The parameter name for the included pages.  Value is <tt>{@value}</tt>. */
079    public static final String PARAM_INCLUDE = "include";
080
081    /** The parameter name for the excluded pages.  Value is <tt>{@value}</tt>. */
082    public static final String PARAM_EXCLUDE = "exclude";
083
084    /** The parameter name for the format.  Value is <tt>{@value}</tt>. */
085    public static final String PARAM_FORMAT = "format";
086
087    /** Parameter name for setting the number of columns that will be displayed by the plugin.  Value is <tt>{@value}</tt>. Available since 2.11.0. */
088    public static final String PARAM_COLUMNS = "columns";
089
090    /** The minimum depth. Value is <tt>{@value}</tt>. */
091    public static final int MIN_DEPTH = 1;
092
093    /** The maximum depth. Value is <tt>{@value}</tt>. */
094    public static final int MAX_DEPTH = 8;
095
096    /**
097     *  {@inheritDoc}
098     */
099    @Override
100    public String execute( final Context context, final Map< String, String > params ) throws PluginException {
101        m_engine = context.getEngine();
102        final Page page = context.getPage();
103        if( page == null ) {
104            return "";
105        }
106
107        // parse parameters
108        String rootname = params.get( PARAM_ROOT );
109        if( rootname == null ) {
110            rootname = page.getName() ;
111        }
112        // the links of a page that the viewer may not view are not shown either
113        if( !AbstractReferralPlugin.mayView( context, rootname ) ) {
114            return "";
115        }
116
117        String format = params.get( PARAM_FORMAT );
118        if( format == null) {
119            format = "";
120        }
121        if( format.contains( "full" ) ) {
122            m_formatCompact = false ;
123        }
124        if( format.contains( "sort" ) ) {
125            m_formatSort = true  ;
126        }
127
128        m_depth = TextUtil.parseIntParameter( params.get( PARAM_DEPTH ), MIN_DEPTH );
129        if( m_depth > MAX_DEPTH ) {
130            m_depth = MAX_DEPTH;
131        }
132
133        String includePattern = params.get(PARAM_INCLUDE);
134        if( includePattern == null ) {
135            includePattern = ".*";
136        }
137
138        String excludePattern = params.get(PARAM_EXCLUDE);
139        if( excludePattern == null ) {
140            excludePattern = "^$";
141        }
142
143        final String columns = params.get( PARAM_COLUMNS );
144        if( columns != null ) {
145            items = TextUtil.parseIntParameter( columns, 0 );
146        }
147
148        LOG.debug( "Fetching referred pages for "+ rootname +
149                   " with a depth of "+ m_depth +
150                   " with include pattern of "+ includePattern +
151                   " with exclude pattern of "+ excludePattern +
152                   " with " + columns + " items" );
153
154        //
155        // do the actual work
156        //
157        final String href  = context.getViewURL( rootname );
158        final String title = "ReferredPagesPlugin: depth[" + m_depth +
159                             "] include[" + includePattern + "] exclude[" + excludePattern +
160                             "] format[" + ( m_formatCompact ? "compact" : "full" ) +
161                             ( m_formatSort ? " sort" : "" ) + "]";
162
163        if( items > 1 ) {
164            m_result.append( "<div class=\"ReferredPagesPlugin\" style=\"" )
165                    .append( "columns:" ).append( columns ).append( ";" )
166                    .append( "moz-columns:" ).append( columns ).append( ";" )
167                    .append( "webkit-columns:" ).append( columns ).append( ";" )
168                    .append( "\">\n" );
169        } else {
170            m_result.append( "<div class=\"ReferredPagesPlugin\">\n" );
171        }
172        m_result.append( "<a class=\"wikipage\" href=\"" )
173                .append( href ).append( "\" title=\"" )
174                .append( TextUtil.replaceEntities( title ) )
175                .append( "\">" )
176                .append( TextUtil.replaceEntities( rootname ) )
177                .append( "</a>\n" );
178        m_exists.add( rootname );
179
180        // pre compile all needed patterns
181        // glob compiler :  * is 0..n instance of any char  -- more convenient as input
182        // perl5 compiler : .* is 0..n instances of any char -- more powerful
183        //PatternCompiler g_compiler = new GlobCompiler();
184
185        try {
186             m_includePattern = Pattern.compile( includePattern );
187            m_excludePattern = Pattern.compile( excludePattern );
188           // m_includePattern = compiler.compile( includePattern );
189           // m_excludePattern = compiler.compile( excludePattern );
190        } catch( final PatternSyntaxException e ) {
191            if( m_includePattern == null ) {
192                throw new PluginException( "Illegal include pattern detected." );
193            } else if( m_excludePattern == null ) {
194                throw new PluginException( "Illegal exclude pattern detected." );
195            } else {
196                throw new PluginException( "Illegal internal pattern detected." );
197            }
198        }
199
200        // go get all referred links
201        getReferredPages(context,rootname, 0);
202
203        // close and finish
204        m_result.append ("</div>\n" ) ;
205
206        return m_result.toString() ;
207    }
208
209    /**
210     * Retrieves a list of all referred pages. Is called recursively depending on the depth parameter.
211     */
212    private void getReferredPages( final Context context, final String pagename, int depth ) {
213        if( depth >= m_depth ) {
214            return;  // end of recursion
215        }
216        if( pagename == null ) {
217            return;
218        }
219        if( !m_engine.getManager( PageManager.class ).wikiPageExists(pagename) ) {
220            return;
221        }
222
223        final ReferenceManager mgr = m_engine.getManager( ReferenceManager.class );
224        final Collection< String > allPages = mgr.findRefersTo( pagename );
225        handleLinks( context, allPages, ++depth, pagename );
226    }
227
228    private void handleLinks( final Context context, final Collection<String> links, final int depth, final String pagename ) {
229        boolean isUL = false;
230        final HashSet< String > localLinkSet = new HashSet<>();  // needed to skip multiple links to the same page
231        localLinkSet.add( pagename );
232
233        final ArrayList< String > allLinks = new ArrayList<>();
234
235        if( links != null )
236            allLinks.addAll( links );
237
238        if( m_formatSort ) context.getEngine().getManager( PageManager.class ).getPageSorter().sort( allLinks );
239
240        for( final String link : allLinks ) {
241            if( localLinkSet.contains( link ) ) {
242                continue; // skip multiple links to the same page
243            }
244            localLinkSet.add( link );
245
246            if( !m_engine.getManager( PageManager.class ).wikiPageExists( link ) ) {
247                continue; // hide links to non-existing pages
248            }
249            if( !AbstractReferralPlugin.mayView( context, link ) ) {
250                continue; // hide the pages that the viewer may not view
251            }
252            // author-controlled patterns: time-box each match so a pathological
253            // regexp can't pin the rendering thread (see TimeLimitedRegex)
254            if (TimeLimitedRegex.matches(link, m_excludePattern)) {
255                continue;
256            }
257            if (!TimeLimitedRegex.matches(link, m_includePattern)) {
258                continue;
259            }
260
261            if( m_exists.contains( link ) ) {
262                if( !m_formatCompact ) {
263                    if( !isUL ) {
264                        isUL = true;
265                        m_result.append("<ul>\n");
266                    }
267
268                    //See https://www.w3.org/wiki/HTML_lists  for proper nesting of UL and LI
269                    m_result.append( "<li> " ).append( TextUtil.replaceEntities( link ) ).append( "\n" );
270                    getReferredPages( context, link, depth );  // added recursive call - on general request
271                    m_result.append( "\n</li>\n" );
272                }
273            } else {
274                if( !isUL ) {
275                    isUL = true;
276                    m_result.append("<ul>\n");
277                }
278
279                final String href = context.getURL( ContextEnum.PAGE_VIEW.getRequestContext(), link );
280                m_result.append( "<li><a class=\"wikipage\" href=\"" ).append( href ).append( "\">" ).append( TextUtil.replaceEntities( link ) ).append( "</a>\n" );
281                m_exists.add( link );
282                getReferredPages( context, link, depth );
283                m_result.append( "\n</li>\n" );
284            }
285        }
286
287        if( isUL ) {
288            m_result.append("</ul>\n");
289        }
290    }
291
292}