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.ui; 020 021import org.apache.commons.lang3.StringUtils; 022import org.apache.logging.log4j.LogManager; 023import org.apache.logging.log4j.Logger; 024import org.apache.wiki.InternalWikiException; 025import org.apache.wiki.api.core.Context; 026import org.apache.wiki.api.core.Engine; 027import org.apache.wiki.modules.BaseModuleManager; 028import org.apache.wiki.modules.WikiModuleInfo; 029import org.apache.wiki.preferences.Preferences; 030import org.apache.wiki.preferences.Preferences.TimeFormat; 031 032import jakarta.servlet.ServletContext; 033import jakarta.servlet.http.HttpServletRequest; 034import jakarta.servlet.jsp.PageContext; 035import java.io.IOException; 036import java.io.InputStream; 037import java.text.SimpleDateFormat; 038import java.util.ArrayList; 039import java.util.Collection; 040import java.util.Collections; 041import java.util.Date; 042import java.util.Enumeration; 043import java.util.LinkedHashMap; 044import java.util.Map; 045import java.util.Properties; 046import java.util.Set; 047import java.util.TimeZone; 048import java.util.TreeSet; 049 050 051/** 052 * This class takes care of managing JSPWiki templates. This class also provides the ResourceRequest mechanism. 053 * 054 * @since 2.1.62 055 */ 056public class DefaultTemplateManager extends BaseModuleManager implements TemplateManager { 057 058 private static final Logger LOG = LogManager.getLogger( DefaultTemplateManager.class ); 059 060 private static String santitize(String template) { 061 if (template==null) return null; 062 String filename = template.replace("..", "_"); 063 filename = filename.replace("/", "_"); 064 filename = filename.replace("\\", "_"); 065 066 //remove any non-filename-safe characters 067 filename = filename.replaceAll("[/:*?\"<>|\\p{Cntrl}]", "_"); 068 if (!template.equals(filename)) { 069 LOG.warn("request for template '" + template + "' was sanitized to '" + filename + "' however they don't match. Potential malicious intent blocked"); 070 } 071 return filename; 072 } 073 074 /** 075 * Creates a new TemplateManager. There is typically one manager per engine. 076 * 077 * @param engine The owning engine. 078 * @param properties The property list used to initialize this. 079 */ 080 public DefaultTemplateManager( final Engine engine, final Properties properties ) { 081 super( engine ); 082 } 083 084 /** {@inheritDoc} */ 085 @Override 086 // FIXME: Does not work yet 087 public boolean templateExists( final String templateName ) { 088 final ServletContext context = m_engine.getServletContext(); 089 try( final InputStream in = context.getResourceAsStream( getPath( templateName ) + "ViewTemplate.jsp" ) ) { 090 if( in != null ) { 091 return true; 092 } 093 } catch( final IOException e ) { 094 LOG.error( e.getMessage(), e ); 095 } 096 return false; 097 } 098 099 /** 100 * Tries to locate a given resource from the template directory. If the given resource is not found under the current name, returns the 101 * path to the corresponding one in the default template. 102 * 103 * @param sContext The servlet context 104 * @param name The name of the resource 105 * @return The name of the resource which was found. 106 */ 107 private static String findResource( final ServletContext sContext, final String name ) { 108 String resourceName = name; 109 try( final InputStream is = sContext.getResourceAsStream( resourceName ) ) { 110 if( is == null ) { 111 final String defname = makeFullJSPName( DEFAULT_TEMPLATE, removeTemplatePart( resourceName ) ); 112 try( final InputStream iis = sContext.getResourceAsStream( defname ) ) { 113 resourceName = iis != null ? defname : null; 114 } 115 } 116 } catch( final IOException e ) { 117 LOG.error( "unable to open " + name + " as resource stream", e ); 118 } 119 return resourceName; 120 } 121 122 /** 123 * Attempts to find a resource from the given template, and if it's not found 124 * attempts to locate it from the default template. 125 * @param sContext servlet context used to search for the resource 126 * @param template template used to search for the resource 127 * @param name resource name 128 * @return the Resource for the given template and name. 129 */ 130 private static String findResource( final ServletContext sContext, final String template, final String name ) { 131 if( name.charAt(0) == '/' ) { 132 // This is already a full path 133 return findResource( sContext, name ); 134 } 135 final String fullname = makeFullJSPName( template, name ); 136 return findResource( sContext, fullname ); 137 } 138 139 /** {@inheritDoc} */ 140 @Override 141 public String findJSP( final PageContext pageContext, final String name ) { 142 final ServletContext sContext = pageContext.getServletContext(); 143 return findResource( sContext, name ); 144 } 145 146 /** 147 * Removes the template part of a name. 148 */ 149 private static String removeTemplatePart( String name ) { 150 int idx = 0; 151 if( name.startsWith( "/" ) ) { 152 idx = 1; 153 } 154 155 idx = name.indexOf('/', idx); 156 if( idx != -1 ) { 157 idx = name.indexOf('/', idx+1); // Find second "/" 158 if( idx != -1 ) { 159 name = name.substring( idx+1 ); 160 } 161 } 162 163 LOG.debug( "Final name = {}", name ); 164 return name; 165 } 166 167 /** 168 * Returns the full name (/templates/foo/bar) for name=bar, template=foo. 169 * 170 * @param template The name of the template. 171 * @param name The name of the resource. 172 * @return The full name for a template. 173 */ 174 private static String makeFullJSPName( final String template, final String name ) { 175 return "/" + DIRECTORY + "/" + santitize(template) + "/" + name; 176 } 177 178 /** {@inheritDoc} */ 179 @Override 180 public String findJSP( final PageContext pageContext, final String template, final String name ) { 181 if( name == null || template == null ) { 182 LOG.fatal("findJSP() was asked to find a null template or name (" + template + "," + name + ")." + " JSP page '" + 183 ( ( HttpServletRequest )pageContext.getRequest() ).getRequestURI() + "'" ); 184 throw new InternalWikiException( "Illegal arguments to findJSP(); please check logs." ); 185 } 186 187 return findResource( pageContext.getServletContext(), template, name ); 188 } 189 190 /** {@inheritDoc} */ 191 @Override 192 public String findResource( final Context ctx, final String template, final String name ) { 193 if( m_engine.getServletContext() != null ) { 194 return findResource( m_engine.getServletContext(), template, name ); 195 } 196 197 return getPath( template ) + "/" + name; 198 } 199 200 /** 201 * Returns an absolute path to a given template. 202 */ 203 private static String getPath( final String template ) { 204 return "/" + DIRECTORY + "/" + template + "/"; 205 } 206 207 /** {@inheritDoc} */ 208 @Override 209 public Set< String > listSkins( final PageContext pageContext, final String template ) { 210 final String place = makeFullJSPName( template, SKIN_DIRECTORY ); 211 final ServletContext sContext = pageContext.getServletContext(); 212 final Set< String > skinSet = sContext.getResourcePaths( place ); 213 final Set< String > resultSet = new TreeSet<>(); 214 215 LOG.debug( "Listings skins from {}", place ); 216 if( skinSet != null ) { 217 final String[] skins = skinSet.toArray( new String[]{} ); 218 for( final String skin : skins ) { 219 final String[] s = StringUtils.split( skin, "/" ); 220 if( s.length > 2 && skin.endsWith( "/" ) ) { 221 final String skinName = s[ s.length - 1 ]; 222 resultSet.add( skinName ); 223 LOG.debug( "...adding skin '{}'", skinName ); 224 } 225 } 226 } 227 228 return resultSet; 229 } 230 231 /** {@inheritDoc} */ 232 @Override 233 public Map< String, String > listTimeFormats( final PageContext pageContext ) { 234 final Context context = Context.findContext( pageContext ); 235 final Properties props = m_engine.getWikiProperties(); 236 final ArrayList< String > tfArr = new ArrayList<>(40); 237 final LinkedHashMap< String, String > resultMap = new LinkedHashMap<>(); 238 239 /* filter timeformat properties */ 240 for( final Enumeration< ? > e = props.propertyNames(); e.hasMoreElements(); ) { 241 final String name = ( String )e.nextElement(); 242 if( name.startsWith( TIMEFORMATPROPERTIES ) ) { 243 tfArr.add( name ); 244 } 245 } 246 247 /* fetch actual formats */ 248 if(tfArr.isEmpty()) {/* no props found - make sure some default formats are avail */ 249 tfArr.add( "dd-MMM-yy" ); 250 tfArr.add( "d-MMM-yyyy" ); 251 tfArr.add( "EEE, dd-MMM-yyyy, zzzz" ); 252 } else { 253 Collections.sort( tfArr ); 254 255 tfArr.replaceAll(props::getProperty); 256 } 257 258 final String prefTimeZone = Preferences.getPreference( context, "TimeZone" ); 259 final TimeZone tz = TimeZone.getTimeZone( prefTimeZone ); 260 261 final Date d = new Date(); // current date 262 try { 263 // dummy format pattern 264 final SimpleDateFormat fmt = Preferences.getDateFormat( context, TimeFormat.DATETIME ); 265 fmt.setTimeZone( tz ); 266 267 for( final String s : tfArr ) { 268 try { 269 fmt.applyPattern( s ); 270 resultMap.put( s, fmt.format( d ) ); 271 } catch( final IllegalArgumentException e ) { 272 LOG.debug(e.getMessage(), e); 273 } // skip parameter 274 } 275 } catch( final IllegalArgumentException e ) { 276 LOG.debug(e.getMessage(), e); 277 } // skip parameter 278 279 return resultMap; 280 } 281 282 /** {@inheritDoc} */ 283 @Override 284 public Collection< WikiModuleInfo > modules() { 285 return new ArrayList<>(); 286 } 287 288 /** {@inheritDoc} */ 289 @Override 290 public WikiModuleInfo getModuleInfo( final String moduleName ) { 291 return null; 292 } 293 294}