1 package ys.wikiparser;
2 import fr.paris.lutece.portal.service.util.AppPathService;
3 import fr.paris.lutece.portal.service.util.AppPropertiesService;
4 import fr.paris.lutece.portal.service.util.AppLogService;
5 import fr.paris.lutece.util.html.HtmlTemplate;
6 import ys.wikiparser.XSSSanitizer;
7 import java.util.Map;
8 import java.util.regex.Matcher;
9 import java.util.regex.Pattern;
10 import java.io.File;
11 import org.apache.commons.io.FileUtils;
12 import java.nio.charset.StandardCharsets;
13 public class MarkdownCustomInputs
14 {
15
16 public static final String PROPERTY_CUSTOM_TEMPLATE_PATH = "wiki.custom.template.path";
17 public static final String TEMPLATE_SUFFIX = ".html";
18 private static final String PROPERTY_PATH_TEMPLATE = "path.templates";
19
20 public static final String VAR_OPEN = "${";
21 public static final String VAR_CLOSE = "}";
22
23
24
25
26
27
28 public static Map<String, String> extractParams( String inputText)
29 {
30 Map<String, String> paramMap = new java.util.HashMap<>( );
31
32 String regex = "(\\w+)=\\{\\{([^}]*)\\}\\}";
33
34
35 Pattern pattern = Pattern.compile( regex );
36
37
38 Matcher matcher = pattern.matcher( inputText );
39
40
41
42
43 while ( matcher.find( ) )
44 {
45
46 String param = matcher.group( 1 );
47 String arg = matcher.group( 2 );
48 if(arg == null){
49 arg = "";
50 }
51 paramMap.put( param.toString(), arg.toString() );
52 }
53 return paramMap;
54 }
55
56
57
58
59
60
61 public static String fillTemplate (String template, Map<String, String> model){
62 HtmlTemplate htmlTemplate = new HtmlTemplate( template );
63 for ( String key : model.keySet( ) )
64 {
65 htmlTemplate.substitute( VAR_OPEN + key + VAR_CLOSE, model.get( key ));
66 }
67 String sanitizedHtml = XSSSanitizer.sanitize( htmlTemplate.getHtml( ) );
68 return sanitizedHtml;
69 }
70
71
72
73
74
75
76
77 public static String renderCustomInHtml( String inputText, String customInputName )
78 {
79 String html = "";
80 try
81 {
82 Map<String, String> model = extractParams( inputText );
83 String templatePath = AppPathService.getPath( PROPERTY_PATH_TEMPLATE ) + AppPropertiesService.getProperty( PROPERTY_CUSTOM_TEMPLATE_PATH ) + File.separator + customInputName + TEMPLATE_SUFFIX;
84 File file = new File( templatePath );
85 html = FileUtils.readFileToString( file, StandardCharsets.UTF_8 );
86 html = fillTemplate( html, model );
87 }
88 catch( Exception e){
89 String errorMessage = "Issue for custom input: " + customInputName;
90 AppLogService.error( errorMessage );
91 AppLogService.error(e.getMessage());
92 html = "<div style='color:red;font-weight:bold'>"+ errorMessage + "</div>";
93 }
94
95 return html;
96 }
97 }