001/*
002 *  Copyright 2019 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.newsletter.testsending;
017
018import java.util.regex.Matcher;
019import java.util.regex.Pattern;
020
021import org.apache.commons.lang3.StringUtils;
022
023import org.ametys.cms.transformation.xslt.ResolveURIComponent;
024import org.ametys.core.util.URIUtils;
025
026
027/**
028 * This class parses and resolve links using ResolveLinkComponent
029 */
030public final class HTMLExpertLinkResolver
031{
032    private static final Pattern __PARSER = Pattern.compile("\\$\\{type:([^#]+)#url:([^#]+)#download:(true|false)\\}");
033    
034    private HTMLExpertLinkResolver()
035    {
036        // Utility
037    }
038    
039    /**
040     * Parse a html string and resolve link found
041     * @param htmlexpert The htmlexpert string 
042     * @param idDataHolderContent The id of the content holding the data. Can be null to keep the uri as is
043     * @return The string with links resolved
044     */
045    public static String parseAndResolve(String htmlexpert, String idDataHolderContent)
046    {
047        String s = URIUtils.decode(htmlexpert);
048        
049        Matcher m = __PARSER.matcher(s);
050        while (m.find())
051        {
052            String type = m.group(1);
053            String uri = m.group(2);
054            boolean download = "true".equals(m.group(3));
055            
056            if ("local".equals(type) && StringUtils.isNotEmpty(idDataHolderContent))
057            {
058                uri = idDataHolderContent + "@" + StringUtils.substringAfter(uri, "@");
059                type = NewsletterLocalURIResolver.NEWSLETTER_LOCAL_DATA_TYPE;
060            }
061            
062            s = s.substring(0, m.start()) + ResolveURIComponent.resolve(type, uri, download) + s.substring(m.end());
063            
064            m.reset(s);
065        }
066        
067        return s;
068    }
069}