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 */
019
020package org.apache.wiki.plugin;
021
022import org.apache.commons.lang3.StringUtils;
023import org.apache.wiki.api.core.Context;
024import org.apache.wiki.api.core.Page;
025import org.apache.wiki.api.exceptions.PluginException;
026import org.apache.wiki.api.plugin.Plugin;
027import org.apache.wiki.api.providers.WikiProvider;
028import org.apache.wiki.auth.AuthorizationManager;
029import org.apache.wiki.auth.permissions.PermissionFactory;
030import org.apache.wiki.pages.PageManager;
031import org.apache.wiki.render.RenderingManager;
032import org.apache.wiki.util.HttpUtil;
033import org.apache.wiki.util.TextUtil;
034import org.apache.wiki.variables.VariableManager;
035
036import java.security.Principal;
037import java.util.Locale;
038import java.util.Map;
039import java.util.ResourceBundle;
040import java.util.regex.Pattern;
041import java.util.regex.PatternSyntaxException;
042import org.apache.wiki.i18n.InternationalizationManager;
043import org.apache.wiki.util.TimeLimitedRegex;
044
045/**
046 *  The IfPlugin allows parts of a WikiPage to be executed conditionally, and is intended as a flexible way
047 *  of customizing a page depending on certain conditions. Do not use it as a security mechanism to conditionally
048 *  hide content from users (use page ACLs for that).
049 *  
050 *  You can also use shorthand "If" to run it.
051 *  
052 *  Parameters:
053 *  <ul>
054 *    <li><b>group</b> - A "|" -separated list of group names.</li>
055 *    <li><b>user</b>  - A "|" -separated list of user names.</li>
056 *    <li><b>ip</b>    - A "|" -separated list of ip addresses.</li>
057 *    <li><b>var</b>   - A wiki variable</li>
058 *    <li><b>page</b>  - A page name</li>
059 *    <li><b>contains</b> - A Perl5 regexp pattern</li>
060 *    <li><b>is</b>    - A Perl5 regexp pattern</li>
061 *    <li><b>exists</b> - "true" or "false".</li>
062 *  </ul>
063 *
064 *  <p>If any of them match, the body of the plugin is executed.  You can
065 *  negate the content by prefixing it with a "!".  For example, to greet
066 *  all admins, put the following in your LeftMenu:</p>
067 *  <pre>
068 *  [{If group='Admin'
069 *
070 *  Hello, Admin, and your mighty powers!}]
071 *  </pre>
072 *
073 *  <p>In order to send a message to everybody except Jack use</p>
074 *  <pre>
075 *  [{If user='!Jack'
076 *
077 *  %%warning
078 *  Jack's surprise birthday party at eleven!
079 *  %%}]
080 *  </pre>
081 *
082 *  <p>Note that you can't use "!Jack|!Jill", because for Jack, !Jill matches;
083 *  and for Jill, !Jack matches.  These are not regular expressions (though
084 *  they might become so in the future).<p>
085 *
086 *  <p>To check for page content, use</p>
087 *  <pre>
088 *  [{If page='TestPage' contains='xyzzy'
089 *
090 *  Page contains the text "xyzzy"}]
091 *  </pre>
092 *
093 *  <p>The difference between "contains" and "is" is that "is" is always an exact match,
094 *  whereas "contains" just checks if a pattern is available.</p>
095 *
096 *  <p>To check for page existence, use</p>
097 *  <pre>
098 *  [{If page='TestPage' exists='true'
099 *
100 *  Page "TestPage" exists.}]
101 *  </pre>
102 *  <p>With the same mechanism, it's also possible to test for the existence
103 *  of a variable - just use "var" instead of "page".</p>
104 *  
105 *  <p>Another caveat is that the plugin body content is not counted
106 *  towards ReferenceManager links.  So any links do not appear on any reference
107 *  lists.  Depending on your position, this may be a good or a bad
108 *  thing.</p>
109 *
110 *  <h3>Calling Externally</h3>
111 *
112 *  <p>The functional, decision-making part of this plugin may be called from
113 *  other code (e.g., other plugins) since it is available as a static method
114 *  {@link #ifInclude(Context,Map)}. Note that the plugin body may contain
115 *  references to other plugins.</p>
116 *
117 *  @since 2.6
118 */
119public class IfPlugin implements Plugin {
120
121    /** The parameter name for setting the group to check.  Value is <tt>{@value}</tt>. */
122    public static final String PARAM_GROUP    = "group";
123
124    /** The parameter name for setting the user id to check.  Value is <tt>{@value}</tt>. */
125    public static final String PARAM_USER     = "user";
126    
127    /** The parameter name for setting the ip address to check.  Value is <tt>{@value}</tt>. */
128    public static final String PARAM_IP       = "ip";
129    
130    /** The parameter name for setting the page name to check.  Value is <tt>{@value}</tt>. */
131    public static final String PARAM_PAGE     = "page";
132    
133    /** The parameter name for setting the contents of the page to check.  Value is <tt>{@value}</tt>. */
134    public static final String PARAM_CONTAINS = "contains";
135    
136    /** The parameter name for setting the variable name to check.  Value is <tt>{@value}</tt>. */
137    public static final String PARAM_VAR      = "var";
138    
139    /** The parameter name for setting the exact content to check.  Value is <tt>{@value}</tt>. */
140    public static final String PARAM_IS       = "is";
141    
142    /** The parameter name for checking whether a page/var exists.  Value is <tt>{@value}</tt>. */
143    public static final String PARAM_EXISTS   = "exists";
144
145    @Override
146    public String getDisplayName(Locale locale) {
147        final ResourceBundle rb = ResourceBundle.getBundle(PluginManager.PLUGIN_I18N_RESOURCE, locale);
148        return rb.getString(this.getClass().getSimpleName());
149    }
150    
151    @Override
152    public String getSnipExample() {
153        return "If name='{value}' page='pagename' exists='true' contains='regexp'\n\nbody\n";
154    }
155    /**
156     *  {@inheritDoc}
157     */
158    @Override 
159    public String execute( final Context context, final Map< String, String > params ) throws PluginException {
160        return ifInclude( context,params )
161                ? context.getEngine().getManager( RenderingManager.class ).textToHTML( context, params.get( DefaultPluginManager.PARAM_BODY ) )
162                : "" ;
163    }
164
165
166    /**
167     *  Returns a boolean result based on processing the WikiContext and
168     *  parameter Map as according to the rules stated in the IfPlugin
169     *  documentation. 
170     *  As a static method this may be called by other classes.
171     *
172     * @param context   The current WikiContext.
173     * @param params    The parameter Map which contains key-value pairs.
174     * @throws PluginException If something goes wrong
175     * @return True, if the condition holds.
176     */
177    public static boolean ifInclude( final Context context, final Map< String, String > params ) throws PluginException {
178        final String group    = params.get( PARAM_GROUP );
179        final String user     = params.get( PARAM_USER );
180        final String ip       = params.get( PARAM_IP );
181        final String page     = params.get( PARAM_PAGE );
182        final String contains = params.get( PARAM_CONTAINS );
183        final String var      = params.get( PARAM_VAR );
184        final String is       = params.get( PARAM_IS );
185        final String exists   = params.get( PARAM_EXISTS );
186
187        boolean include = checkGroup( context, group );
188        include |= checkUser(context, user);
189        include |= checkIP(context, ip);
190
191        if( page != null ) {
192            // Only read the target page's content if the requesting session is allowed to view it;
193            // otherwise behave exactly as if the content did not match, so ACL-protected content
194            // cannot be probed through the contains/is parameters.
195            String content = null;
196            final Page testedPage = context.getEngine().getManager( PageManager.class ).getPage( page );
197            if( testedPage != null && context.getEngine().getManager( AuthorizationManager.class )
198                    .checkPermission( context.getWikiSession(), PermissionFactory.getPagePermission( testedPage, "view" ) ) ) {
199                content = context.getEngine().getManager( PageManager.class ).getPureText(page, WikiProvider.LATEST_VERSION).trim();
200            }
201            include |= checkContains(content,contains);
202            include |= checkIs(content,is);
203            include |= checkExists(context,page,exists);
204        }
205
206        if( var != null ) {
207            final String content = context.getEngine().getManager( VariableManager.class ).getVariable(context, var);
208            include |= checkContains(content,contains);
209            include |= checkIs(content,is);
210            include |= checkVarExists(content,exists);
211        }
212
213        return include;
214    }
215
216    private static boolean checkExists( final Context context, final String page, final String exists ) {
217        if( exists == null ) {
218            return false;
219        }
220        return !context.getEngine().getManager( PageManager.class ).wikiPageExists( page ) ^ TextUtil.isPositive(exists);
221    }
222
223    private static boolean checkVarExists( final String varContent, final String exists ) {
224        if( exists == null ) {
225            return false;
226        }
227        return varContent == null ^ TextUtil.isPositive( exists );
228    }
229
230    private static boolean checkGroup( final Context context, final String group ) {
231        if( group == null ) {
232            return false;
233        }
234        final String[] groupList = StringUtils.split(group,'|');
235        boolean include = false;
236
237        for( final String grp : groupList ) {
238            String gname = grp;
239            boolean invert = false;
240            if( grp.startsWith( "!" ) ) {
241                if( grp.length() > 1 ) {
242                    gname = grp.substring( 1 );
243                }
244                invert = true;
245            }
246
247            final Principal g = context.getEngine().getManager( AuthorizationManager.class ).resolvePrincipal( gname );
248
249            include |= context.getEngine().getManager( AuthorizationManager.class ).isUserInRole( context.getWikiSession(), g ) ^ invert;
250        }
251        return include;
252    }
253
254    private static boolean checkUser( final Context context, final String user ) {
255        if( user == null || context.getCurrentUser() == null ) {
256            return false;
257        }
258
259        final String[] list = StringUtils.split(user,'|');
260        boolean include = false;
261
262        for( final String usr : list ) {
263            String userToCheck = usr;
264            boolean invert = false;
265            if( usr.startsWith( "!" ) ) {
266                invert = true;
267                // strip !
268                if( user.length() > 1 ) {
269                    userToCheck = usr.substring( 1 );
270                }
271            }
272
273            include |= userToCheck.equals( context.getCurrentUser().getName() ) ^ invert;
274        }
275        return include;
276    }
277
278    // TODO: Add subnetwork matching, e.g. 10.0.0.0/8
279    private static boolean checkIP( final Context context, final String ipaddr ) {
280        if( ipaddr == null || context.getHttpRequest() == null ) {
281            return false;
282        }
283
284        final String[] list = StringUtils.split(ipaddr,'|');
285        boolean include = false;
286
287        for( final String ip : list ) {
288            String ipaddrToCheck = ip;
289            boolean invert = false;
290            if( ip.startsWith( "!" ) ) {
291                invert = true;
292                // strip !
293                if( ip.length() > 1 ) {
294                    ipaddrToCheck = ip.substring( 1 );
295                }
296            }
297
298            include |= HttpUtil.ipIsInRange( context.getHttpRequest(), ipaddrToCheck ) ^ invert;
299        }
300        return include;
301    }
302
303    private static boolean doMatch( final String content, final String pattern ) throws PluginException {
304     
305
306        try {
307              // DOTALL gives '.' the same match-newlines behaviour as the previous Perl5Compiler.SINGLELINE_MASK.
308            // The match is time-boxed: pattern and page content are both author-controlled, so an unbounded
309            // backtracking match is a render-time denial of service (see TimeLimitedRegex).
310            final Pattern matchp = Pattern.compile( pattern, Pattern.DOTALL );
311            return TimeLimitedRegex.matches( content, matchp );
312            //final Pattern matchp = compiler.compile( pattern, Perl5Compiler.SINGLELINE_MASK );
313            //return matcher.matches( content, matchp );
314        } catch( final PatternSyntaxException e ) {
315            throw new PluginException( "Faulty pattern " + pattern );
316        }
317
318    }
319
320    private static boolean checkContains( final String pagecontent, final String matchPattern ) throws PluginException {
321        if( pagecontent == null || matchPattern == null ) {
322            return false;
323        }
324
325        return doMatch( pagecontent, ".*"+matchPattern+".*" );
326    }
327
328    private static boolean checkIs( final String content, final String matchPattern ) throws PluginException {
329        if( content == null || matchPattern == null ) {
330            return false;
331        }
332        return doMatch( content, "^" + matchPattern + "$");
333    }
334
335}