001/** 002 * 003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. 004 * 005 * This library is free software; you can redistribute it and/or 006 * modify it under the terms of the GNU Lesser General Public 007 * License as published by the Free Software Foundation; either 008 * version 2.1 of the License, or (at your option) any later version. 009 * 010 * This library is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013 * Lesser General Public License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public 016 * License along with this library. If not, see <http://www.gnu.org/licenses/>. 017 * 018 **/ 019/** 020 * Implements the CFML Function urlencodedformat 021 */ 022package lucee.runtime.functions.other; 023 024import java.io.UnsupportedEncodingException; 025 026import lucee.commons.lang.ExceptionUtil; 027import lucee.commons.lang.StringUtil; 028import lucee.commons.lang.URLEncoder; 029import lucee.runtime.PageContext; 030import lucee.runtime.exp.PageException; 031import lucee.runtime.ext.function.Function; 032import lucee.runtime.net.http.ReqRspUtil; 033import lucee.runtime.op.Caster; 034 035public final class URLEncodedFormat implements Function { 036 037 private static final long serialVersionUID = 5640029138134769481L; 038 039 public static String call(PageContext pc , String str) throws PageException { 040 return call(pc,str, "UTF-8",true); 041 } 042 043 044 public static String call(PageContext pc , String str, String encoding) throws PageException { 045 return call(pc,str, encoding,true); 046 } 047 048 public static String call(PageContext pc , String str, String encoding,boolean force) throws PageException { 049 return invoke(str, encoding, force); 050 } 051 052 public static String invoke(String str, String encoding,boolean force) throws PageException { 053 if(!force && !ReqRspUtil.needEncoding(str,false)) 054 return str; 055 056 try { 057 String enc=lucee.commons.net.URLEncoder.encode(str, encoding); 058 return StringUtil.replace(StringUtil.replace(StringUtil.replace(StringUtil.replace(StringUtil.replace(enc, "+", "%20", false), "*", "%2A", false), "-", "%2D", false), ".", "%2E", false), "_", "%5F", false);// TODO do better 059 //return enc; 060 } 061 catch (Throwable t) { 062 ExceptionUtil.rethrowIfNecessary(t); 063 try { 064 return URLEncoder.encode(str, encoding); 065 } 066 catch (UnsupportedEncodingException e) { 067 throw Caster.toPageException(e); 068 } 069 } 070 } 071 072}