001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.wiki.engines.mediawiki.matchers;
016    
017    import com.liferay.portal.kernel.util.CallbackMatcher;
018    import com.liferay.portal.kernel.util.HttpUtil;
019    import com.liferay.portal.kernel.util.StringBundler;
020    import com.liferay.portal.kernel.util.StringPool;
021    import com.liferay.portal.kernel.util.StringUtil;
022    
023    import java.util.regex.MatchResult;
024    
025    /**
026     * @author Jonathan Potter
027     * @author Brian Wing Shun Chan
028     */
029    public class ImageURLMatcher extends CallbackMatcher {
030    
031            public ImageURLMatcher(String attachmentURLPrefix) {
032                    _attachmentURLPrefix = attachmentURLPrefix;
033    
034                    setRegex(_REGEX);
035            }
036    
037            public String replaceMatches(CharSequence charSequence) {
038                    return replaceMatches(charSequence, _callBack);
039            }
040    
041            private static final String _REGEX =
042                    "<a href=\"[^\"]*?Special:Upload[^\"]*?topic=Image:([^\"]*?)\".*?</a>";
043    
044            private String _attachmentURLPrefix;
045    
046            private Callback _callBack = new Callback() {
047    
048                    @Override
049                    public String foundMatch(MatchResult matchResult) {
050                            String title = StringUtil.replace(
051                                    matchResult.group(1), "%5F", StringPool.UNDERLINE);
052    
053                            String url = _attachmentURLPrefix + HttpUtil.encodeURL(title);
054    
055                            StringBundler sb = new StringBundler(5);
056    
057                            sb.append("<img alt=\"");
058                            sb.append(title);
059                            sb.append("\" class=\"wikiimg\" src=\"");
060                            sb.append(url);
061                            sb.append("\" />");
062    
063                            return sb.toString();
064                    }
065    
066            };
067    
068    }