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.parser;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.oro.text.regex.MatchResult;
024import org.apache.oro.text.regex.PatternMatcher;
025import org.apache.oro.text.regex.Perl5Matcher;
026import org.apache.wiki.InternalWikiException;
027import org.apache.wiki.api.core.Context;
028import org.apache.wiki.api.core.Engine;
029import org.apache.wiki.api.exceptions.PluginException;
030import org.apache.wiki.api.plugin.ParserStagePlugin;
031import org.apache.wiki.api.plugin.Plugin;
032import org.apache.wiki.api.plugin.PluginElement;
033import org.apache.wiki.plugin.PluginManager;
034import org.apache.wiki.preferences.Preferences;
035import org.apache.wiki.util.TextUtil;
036import org.apache.wiki.variables.VariableManager;
037import org.jdom2.Text;
038
039import java.io.IOException;
040import java.text.MessageFormat;
041import java.util.HashMap;
042import java.util.Map;
043import java.util.NoSuchElementException;
044import java.util.ResourceBundle;
045
046
047/**
048 * Stores the contents of a plugin in a WikiDocument DOM tree.
049 * <p/>
050 * If the Context.VAR_WYSIWYG_EDITOR_MODE is set to Boolean.TRUE in the context, then the plugin is rendered as WikiMarkup.
051 * This allows an HTML editor to work without rendering the plugin each time as well.
052 * <p/>
053 * If Context.VAR_EXECUTE_PLUGINS is set to Boolean.FALSE, then the plugin is not executed.
054 *
055 * @since 2.4
056 */
057public class PluginContent extends Text implements PluginElement {
058
059    private static final String BLANK = "";
060    private static final String CMDLINE = "_cmdline";
061    private static final String ELEMENT_BR = "<br/>";
062    private static final String EMITTABLE_PLUGINS = "Image|FormOpen|FormClose|FormInput|FormTextarea|FormSelect";
063    private static final String LINEBREAK = "\n";
064    private static final String PLUGIN_START = "[{";
065    private static final String PLUGIN_END = "}]";
066    private static final String SPACE = " ";
067
068    private static final long serialVersionUID = 1L;
069    private static final Logger LOG = LogManager.getLogger(PluginContent.class);
070
071    private final String m_pluginName;
072    private final Map< String, String > m_params;
073
074    /**
075     * Creates a new DOM element with the given plugin name and a map of parameters.
076     *
077     * @param pluginName The FQN of a plugin.
078     * @param parameters A Map of parameters.
079     */
080    public PluginContent( final String pluginName, final Map< String, String > parameters) {
081        m_pluginName = pluginName;
082        m_params = parameters;
083    }
084
085    /**{@inheritDoc}*/
086    @Override
087    public String getPluginName() {
088        return m_pluginName;
089    }
090
091    /**{@inheritDoc}*/
092    @Override
093    public String getParameter( final String name) {
094        return m_params.get( name );
095    }
096
097    /**{@inheritDoc}*/
098    @Override
099    public Map< String, String > getParameters() {
100        return m_params;
101    }
102
103    /**{@inheritDoc}*/
104    @Override
105    public String getValue() {
106        return getText();
107    }
108
109    /**{@inheritDoc}*/
110    @Override
111    public String getText() {
112        final WikiDocument doc = ( WikiDocument )getDocument();
113        if( doc == null ) {
114            //
115            // This element has not yet been attached anywhere, so we simply assume there is no rendering and return the plugin name.
116            // This is required e.g. when the paragraphify() checks whether the element is empty or not.  We can't of course know
117            // whether the rendering would result in an empty string or not, but let us assume it does not.
118            //
119            return getPluginName();
120        }
121
122        final Context context = doc.getContext();
123        if( context == null ) {
124            LOG.info( "WikiContext garbage-collected, cannot proceed" );
125            return getPluginName();
126        }
127
128        return invoke( context );
129    }
130
131    /**{@inheritDoc}*/
132    @Override
133    public String invoke( final Context context ) {
134        String result;
135        final Boolean wysiwygVariable = context.getVariable( Context.VAR_WYSIWYG_EDITOR_MODE );
136        boolean wysiwygEditorMode = false;
137        if( wysiwygVariable != null ) {
138            wysiwygEditorMode = wysiwygVariable;
139        }
140
141        try {
142            //
143            //  Determine whether we should emit the actual code for this plugin or
144            //  whether we should execute it.  For some plugins we always execute it,
145            //  since they can be edited visually.
146            //
147            // FIXME: The plugin name matching should not be done here, but in a per-editor resource
148            if( wysiwygEditorMode && !m_pluginName.matches( EMITTABLE_PLUGINS ) ) {
149                result = PLUGIN_START + m_pluginName + SPACE;
150
151                // escape the raw command line first: this text node is emitted with output escaping
152                // disabled, so unescaped markup would reach the wysiwyg editor (and its <textarea>)
153                // as live HTML.  Then convert newlines to <br> in case the plugin has a body.
154                final String cmdLine = TextUtil.escapeHTMLEntities( m_params.get( CMDLINE ) ).replaceAll( LINEBREAK, ELEMENT_BR );
155                result = result + cmdLine + PLUGIN_END;
156            } else {
157                final Boolean b = context.getVariable( Context.VAR_EXECUTE_PLUGINS );
158                if (b != null && !b ) {
159                    return BLANK;
160                }
161
162                final Engine engine = context.getEngine();
163                final Map< String, String > parsedParams = new HashMap<>();
164
165                //  Parse any variable instances from the string
166                for( final Map.Entry< String, String > e : m_params.entrySet() ) {
167                    String val = e.getValue();
168                    val = engine.getManager( VariableManager.class).expandVariables( context, val );
169                    parsedParams.put( e.getKey(), val );
170                }
171                final PluginManager pm = engine.getManager( PluginManager.class );
172                result = pm.execute( context, m_pluginName, parsedParams );
173            }
174        } catch( final Exception e ) {
175            if( wysiwygEditorMode ) {
176                result = "";
177            } else {
178                // LOG.info("Failed to execute plugin",e);
179                final ResourceBundle rb = Preferences.getBundle( context, Plugin.CORE_PLUGINS_RESOURCEBUNDLE );
180                result = MarkupParser.makeError( MessageFormat.format( rb.getString( "plugin.error.insertionfailed" ), 
181                                                                       context.getRealPage().getWiki(), 
182                                                                       context.getRealPage().getName(), 
183                                                                       e.getMessage() ) ).getText();
184            }
185        }
186
187        return result;
188    }
189
190    /**{@inheritDoc}*/
191    @Override
192    public void executeParse( final Context context ) throws PluginException {
193        final PluginManager pm = context.getEngine().getManager( PluginManager.class );
194        if( pm.pluginsEnabled() ) {
195            final ResourceBundle rb = Preferences.getBundle( context, Plugin.CORE_PLUGINS_RESOURCEBUNDLE);
196            final Map< String, String > params = getParameters();
197            final Plugin plugin = pm.newWikiPlugin( getPluginName(), rb );
198            try {
199                if( plugin instanceof ParserStagePlugin ) {
200                    ( ( ParserStagePlugin )plugin ).executeParser(this, context, params );
201                }
202            } catch( final ClassCastException e ) {
203                throw new PluginException( MessageFormat.format( rb.getString("plugin.error.notawikiplugin"), getPluginName() ), e );
204            }
205        }
206    }
207
208    /**
209     * Parses a plugin invocation and returns a DOM element.
210     *
211     * @param context     The WikiContext
212     * @param commandline The line to parse
213     * @param pos         The position in the stream parsing.
214     * @return A DOM element
215     * @throws PluginException If plugin invocation is faulty
216     * @since 2.10.0
217     */
218    public static PluginContent parsePluginLine( final Context context, final String commandline, final int pos ) throws PluginException {
219        final PatternMatcher matcher = new Perl5Matcher();
220
221        try {
222            final PluginManager pm = context.getEngine().getManager( PluginManager.class );
223            if( matcher.contains( commandline, pm.getPluginPattern() ) ) {
224                final MatchResult res = matcher.getMatch();
225                final String plugin = res.group( 2 );
226                final String args = commandline.substring( res.endOffset( 0 ),
227                                                           commandline.length() - ( commandline.charAt( commandline.length() - 1 ) == '}' ? 1 : 0 ) );
228                final Map< String, String > arglist = pm.parseArgs( args );
229
230                // set wikitext bounds of plugin as '_bounds' parameter, e.g., [345,396]
231                if( pos != -1 ) {
232                    final int end = pos + commandline.length() + 2;
233                    final String bounds = pos + "|" + end;
234                    arglist.put( PluginManager.PARAM_BOUNDS, bounds );
235                }
236
237                return new PluginContent( plugin, arglist );
238            }
239        } catch( final ClassCastException e ) {
240            LOG.error( "Invalid type offered in parsing plugin arguments.", e );
241            throw new InternalWikiException( "Oops, someone offered !String!", e );
242        } catch( final NoSuchElementException e ) {
243            final String msg = "Missing parameter in plugin definition: " + commandline;
244            LOG.warn( msg, e );
245            throw new PluginException( msg );
246        } catch( final IOException e ) {
247            final String msg = "Zyrf.  Problems with parsing arguments: " + commandline;
248            LOG.warn( msg, e );
249            throw new PluginException( msg );
250        }
251
252        return null;
253    }
254
255}