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.Pattern;
024import org.apache.oro.text.regex.Perl5Matcher;
025import org.apache.wiki.api.core.Context;
026import org.apache.wiki.api.exceptions.ProviderException;
027
028import java.util.Arrays;
029import java.util.Comparator;
030import java.util.List;
031
032
033/**
034 * Link parsing operations.
035 *
036 * @since 2.10.3
037 */
038public class LinkParsingOperations {
039
040    private static final Logger LOG = LogManager.getLogger( LinkParsingOperations.class );
041    private final Context wikiContext;
042
043    /**
044     *  This list contains all IANA registered URI protocol types as of September 2004 + a few well-known extra types.
045     *
046     *  JSPWiki recognises all of them as external links.
047     *
048     *  This array is sorted during class load, so you can just dump here whatever you want in whatever order you want.
049     */
050    static final String[] EXTERNAL_LINKS = {
051        "http:", "ftp:", "https:", "mailto:",
052        "news:", "file:", "rtsp:", "mms:", "ldap:",
053        "gopher:", "nntp:", "telnet:", "wais:",
054        "prospero:", "z39.50s", "z39.50r", "vemmi:",
055        "imap:", "nfs:", "acap:", "tip:", "pop:",
056        "dav:", "opaquelocktoken:", "sip:", "sips:",
057        "tel:", "fax:", "modem:", "soap.beep:", "soap.beeps",
058        "xmlrpc.beep", "xmlrpc.beeps", "urn:", "go:",
059        "h323:", "ipp:", "tftp:", "mupdate:", "pres:",
060        "im:", "mtqp", "smb:"
061    };
062
063    static {
064        Arrays.sort( EXTERNAL_LINKS );
065    }
066
067    /** A base64 encoded raster image. Other types, SVG among them, can carry script and are not accepted. */
068    private static final java.util.regex.Pattern DATA_IMAGE = java.util.regex.Pattern.compile(
069            "data:image/(?:png|gif|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}", java.util.regex.Pattern.CASE_INSENSITIVE );
070
071    /**
072     * Tells if the link is a {@code data:} URL holding a PNG, GIF, JPEG or WebP image, such as the ones the WYSIWYG editor creates
073     * when an image is pasted. Those can be shown inline, as the browser only decodes them as an image.
074     *
075     * @param link the link to check
076     * @return {@code true} if the link is a base64 {@code data:} URL of a raster image
077     * @since 3.0.1
078     */
079    public static boolean isDataImage( final String link ) {
080        return link != null && DATA_IMAGE.matcher( link ).matches();
081    }
082
083    public LinkParsingOperations( final Context wikiContext ) {
084        this.wikiContext = wikiContext;
085    }
086
087    /**
088     *  Returns true, if the link in question is an access rule.
089     *
090     * @param link The link text
091     * @return {@code true}, if this represents an access rule.
092     */
093    public boolean isAccessRule( final String link ) {
094        return link.startsWith("{ALLOW") || link.startsWith("{DENY");
095    }
096
097    /**
098     *  Returns true if the link is really command to insert a plugin.
099     *  <P>
100     *  Currently we just check if the link starts with "{INSERT", or just plain "{" but not "{$".
101     *
102     *  @param link Link text, i.e. the contents of text between [].
103     *  @return True, if this link seems to be a command to insert a plugin here.
104     */
105    public boolean isPluginLink( final String link ) {
106        return link.startsWith( "{INSERT" ) ||
107               ( link.startsWith( "{" ) && !link.startsWith( "{$" ) );
108    }
109
110    /**
111     * Returns true if the link is a metadata link.
112     *
113     * @param link The link text
114     * @return {@code true}, if this represents a metadata link.
115     */
116    public boolean isMetadata( final String link ) {
117        return link.startsWith( "{SET" );
118    }
119
120    /**
121     * Returns true if the link is really command to insert a variable.
122     * <P>
123     * Currently we just check if the link starts with "{$".
124     *
125     * @param link The link text
126     * @return {@code true}, if this represents a variable link.
127     */
128    public boolean isVariableLink( final String link ) {
129        return link.startsWith( "{$" );
130    }
131
132    /**
133     * Returns true, if this Link represents an InterWiki link (of the form wiki:page).
134     *
135     * @return {@code true}, if this Link represents an InterWiki link, {@code false} otherwise.
136     */
137    public boolean isInterWikiLink( final String page ) {
138        return interWikiLinkAt( page ) != -1;
139    }
140
141    /**
142     * Returns true, if this Link represents an InterWiki link (of the form wiki:page).
143     *
144     * @return {@code true}, if this Link represents an InterWiki link, {@code false} otherwise.
145     */
146    public int interWikiLinkAt( final String page ) {
147        return page.indexOf( ':' );
148    }
149
150    /**
151     * Figures out if a link is an off-site link.  This recognizes the most common protocols by checking how it starts.
152     *
153     * @param page The link to check.
154     * @return true, if this is a link outside of this wiki.
155     */
156    public boolean isExternalLink( final String page ) {
157        final int idx = Arrays.binarySearch( EXTERNAL_LINKS, page, new StartingComparator() );
158
159        // We need to check here once again; otherwise we might get a match for something like "h".
160        return idx >= 0 && page.startsWith( EXTERNAL_LINKS[ idx ] );
161    }
162
163    /**
164     *  Matches the given link to the list of image name patterns to determine whether it should be treated as an inline image or not.
165     */
166    public boolean isImageLink( String link, final boolean isImageInlining, final List< Pattern > inlineImagePatterns ) {
167        if( isImageInlining ) {
168            link = link.toLowerCase();
169            for( final Pattern p : inlineImagePatterns ) {
170                if( new Perl5Matcher().matches( link, p ) ) {
171                    return true;
172                }
173            }
174        }
175
176        return false;
177    }
178
179    /**
180     * Returns {@code true}, if the link name exists; otherwise it returns {@code false}.
181     *
182     * @param page link name
183     * @return {@code true}, if the link name exists; otherwise it returns {@code false}.
184     */
185    public boolean linkExists( final String page ) {
186        if( page == null || page.isEmpty() ) {
187            return false;
188        }
189        try {
190            return wikiContext.getEngine().getFinalPageName( page ) != null;
191        } catch( final ProviderException e ) {
192            LOG.warn( "TranslatorReader got a faulty page name [" + page + "]!", e );
193            return false;
194        }
195    }
196
197    /**
198     * Returns link name, if it exists; otherwise it returns {@code null}.
199     *
200     * @param page link name
201     * @return link name, if it exists; otherwise it returns {@code null}.
202     */
203    public String linkIfExists( final String page ) {
204        if( page == null || page.isEmpty() ) {
205            return null;
206        }
207        try {
208            return wikiContext.getEngine().getFinalPageName( page );
209        } catch( final ProviderException e ) {
210            LOG.warn( "TranslatorReader got a faulty page name [" + page + "]!", e );
211            return null;
212        }
213    }
214
215    /**
216     * Compares two Strings, and if one starts with the other, then returns 0. Otherwise just like the normal Comparator for strings.
217     */
218    private static class StartingComparator implements Comparator< String > {
219
220        /**
221         * {@inheritDoc}
222         *
223         * @see Comparator#compare(Object, Object)
224         */
225        @Override
226        public int compare( final String s1, final String s2 ) {
227            if( s1.length() > s2.length() ) {
228                if( s1.startsWith( s2 ) && s2.length() > 1 ) {
229                    return 0;
230                }
231            } else if( s2.startsWith( s1 ) && s1.length() > 1 ) {
232                return 0;
233            }
234
235            return s1.compareTo( s2 );
236        }
237
238    }
239
240}