fixing html whitelist bug
[mir.git] / source / mircoders / localizer / basic / MirBasicProducerAssistantLocalizer.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30 package mircoders.localizer.basic;
31
32 import java.io.ByteArrayInputStream;
33 import java.io.IOException;
34 import java.io.StringWriter;
35 import java.util.GregorianCalendar;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Map;
40
41 import mir.config.MirPropertiesConfiguration;
42 import mir.entity.adapter.EntityAdapter;
43 import mir.entity.adapter.EntityIteratorAdapter;
44 import mir.generator.Generator;
45 import mir.generator.GeneratorExc;
46 import mir.generator.GeneratorFailure;
47 import mir.log.LoggerWrapper;
48 import mir.misc.StringUtil;
49 import mir.util.GeneratorDateTimeFunctions;
50 import mir.util.GeneratorFormatAdapters;
51 import mir.util.generator.ReflectionGeneratorFunctionsAdapter;
52 import mir.util.StringRoutines;
53 import mircoders.global.MirGlobal;
54 import mircoders.localizer.MirLocalizerExc;
55 import mircoders.localizer.MirLocalizerFailure;
56 import mircoders.localizer.MirProducerAssistantLocalizer;
57
58 import org.w3c.dom.Document;
59 import org.w3c.dom.NamedNodeMap;
60 import org.w3c.dom.Node;
61 import org.w3c.dom.NodeList;
62 import org.w3c.tidy.Configuration;
63 import org.w3c.tidy.Tidy;
64
65 public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer {
66   protected LoggerWrapper logger;
67
68   public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure  {
69     try {
70       Iterator i;
71
72       Map configMap = new HashMap();
73
74       logger = new LoggerWrapper("Localizer.ProducerAssistant");
75
76 // obsolete:
77       configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot"));
78       configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot"));
79       configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost"));
80       configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction"));
81       configMap.put("docRoot", MirGlobal.config().getString("RootUri"));
82       configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir");
83       configMap.put("now", new GeneratorFormatAdapters.DateFormatAdapter(new GregorianCalendar().getTime(), MirGlobal.config().getString("Mir.DefaultTimezone")));
84       configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host"));
85       configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host"));
86       configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host"));
87       configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path"));
88       configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version"));
89       configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding"));
90
91 // "new":
92       configMap.putAll(MirPropertiesConfiguration.instance().allSettings());
93
94       aValueSet.put("config", configMap);
95
96       aValueSet.put("utility", new Utility()); 
97
98       aValueSet.put("languages",
99         new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language"));
100
101       aValueSet.put("topics",
102         new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
103
104       Map articleTypeMap = new HashMap();
105       articleTypeMap.put("openposting", "0");
106       articleTypeMap.put("newswire", "1");
107       articleTypeMap.put("feature", "2");
108       articleTypeMap.put("topicspecial", "3");
109       articleTypeMap.put("startspecial", "4");
110
111       i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType");
112       while (i.hasNext()) {
113         EntityAdapter articleType = (EntityAdapter) i.next();
114
115         articleTypeMap.put(articleType.get("name"), articleType.get("id"));
116       }
117       aValueSet.put("articletype", articleTypeMap);
118
119       Map commentStatusMap = new HashMap();
120       i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus");
121       while (i.hasNext()) {
122         EntityAdapter commentStatus = (EntityAdapter) i.next();
123
124         commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id"));
125       }
126       aValueSet.put("commentstatus", commentStatusMap);
127       aValueSet.put("languageCodeToId", new getLanguageIdFunction());
128     }
129     catch (Throwable t) {
130       logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage());
131
132       throw new MirLocalizerFailure(t);
133     }
134
135   }
136   
137   public static class getLanguageIdFunction implements Generator.Function {
138     private Map languageCodeToId;
139     private String otherLanguageId;
140     private LoggerWrapper logger = new LoggerWrapper("Localizer.Earth.getLanguageIdFunction");
141
142     public getLanguageIdFunction() throws MirLocalizerFailure {
143       try {
144         otherLanguageId = "";
145         languageCodeToId = new HashMap();
146
147         Iterator i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language");
148         while (i.hasNext()) {
149           EntityAdapter language = (EntityAdapter) i.next();
150           if (language.get("code").equals("ot"))
151             otherLanguageId = (String) language.get("id");
152
153           languageCodeToId.put(language.get("code"), language.get("id"));
154         }
155       }
156       catch (Throwable t) {
157         logger.error(t.toString());
158
159         throw new MirLocalizerFailure(t);
160       }
161     }
162
163     public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
164       try {
165         if (aParameters.size() != 1)
166           throw new GeneratorExc("getLanguageIdFunction: 1 parameter expected: language-code");
167
168         String result = (String) languageCodeToId.get(aParameters.get(0));
169         if (result == null)
170           result = otherLanguageId;
171
172         return result;
173       }
174       catch (GeneratorExc e) {
175         throw e;
176       }
177       catch (Throwable t) {
178         throw new GeneratorFailure("getLanguageIdFunction: " + t.getMessage(), t);
179       }
180     }
181   }
182
183
184   public String filterNonHTMLText(String aText) {
185
186     logger.debug("about to filter non HTML Text of length " + aText.length());
187     try {
188       String result =
189           StringUtil.createHTML(
190           StringUtil.removeHTMLTags(aText),
191           MirGlobal.config().getString("Producer.ImageRoot"),
192           MirGlobal.config().getString("Producer.MailLinkName"),
193           MirGlobal.config().getString("Producer.ExtLinkName"),
194           MirGlobal.config().getString("Producer.IntLinkName")
195           );
196       logger.debug("done filtering non-HTML text ");
197       return result;
198     }
199     catch (Throwable t) {
200       logger.error("error while filtering non-HTML text: " + t.toString());
201
202       throw new RuntimeException(t.toString());
203     }
204   }
205   public String filterHTMLText(String aText) {
206     try {
207       StringWriter out = new StringWriter();
208       Tidy tidy = new Tidy();
209       ByteArrayInputStream in = new ByteArrayInputStream(aText.getBytes("UTF8"));
210       tidy.setMakeClean(true);
211       tidy.setCharEncoding(Configuration.UTF8);
212       tidy.setErrout(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
213       print(tidy.parseDOM(in, null), out);
214       
215       return out.toString();
216     }
217     catch (IOException e) {
218       return e.getMessage();
219     }
220   }
221
222   private boolean checkAttr(String attrName) {
223     if (attrName.equals("onLoad") || attrName.equals("onClick") || attrName.equals("onFocus") || attrName.equals("onBlur") || attrName.equals("onMouseOver") || attrName.equals("onMouseOut") || attrName.equals("style") || attrName.equals("STYLE") || attrName.equals("height") || attrName.equals("width") || attrName.equals("HEIGHT") || attrName.equals("WIDTH"))
224       return false;
225                 return true;
226
227   }
228
229   private boolean checkNode(String nodeName) {
230     List languages =  StringRoutines.splitString(MirGlobal.config().getString("Localizer.HTML.Whitelist"), ";");
231     
232     Iterator i = languages.iterator();
233     while (i.hasNext()) {
234       if (nodeName.equals(i.next()))
235         return true;
236     }
237     return false;
238   }
239
240   private void print(Node node, StringWriter out) throws IOException {
241     if (node == null) {
242       return;
243     }
244     int type = node.getNodeType();
245     boolean canOutput = checkNode(node.getNodeName());
246
247     switch (type) {
248
249       case Node.DOCUMENT_NODE:
250
251         print(((Document) node).getDocumentElement(), out);
252         out.flush();
253         break;
254
255       case Node.ELEMENT_NODE:
256         if (canOutput) {
257           out.write('<');
258
259           out.write(node.getNodeName());
260           NamedNodeMap attrs = node.getAttributes();
261
262           for (int i = 0; i < attrs.getLength(); i++) {
263             String attrName = attrs.item(i).getNodeName();
264             if (checkAttr(attrName)) {
265               out.write(' ');
266               out.write(attrs.item(i).getNodeName());
267               out.write("=\"");
268
269               out.write(attrs.item(i).getNodeValue());
270               out.write('"');
271             }
272           }
273
274           if (node.getChildNodes()==null || node.getChildNodes().getLength()==0) {
275             out.write("/");
276           }
277           out.write('>');
278         }
279         NodeList children = node.getChildNodes();
280         if (children != null) {
281           int len = children.getLength();
282           for (int i = 0; i < len; i++) {
283             print(children.item(i), out);
284           }
285         }
286         break;
287
288       case Node.TEXT_NODE:
289         out.write(node.getNodeValue());
290         break;
291
292     }
293
294     if (type == Node.ELEMENT_NODE && canOutput && node.getChildNodes()!=null && node.getChildNodes().getLength()>0) {
295       out.write("</");
296       out.write(node.getNodeName());
297       out.write('>');
298     }
299
300     out.flush();
301   }
302
303   public static class Utility extends ReflectionGeneratorFunctionsAdapter {
304     public Utility () {
305       super(new MirBasicUtilityFunctions());
306     }
307
308     public Object getDatetime() {
309       return new GeneratorDateTimeFunctions.DateTimeFunctions(
310         MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"));
311     }
312
313     public Object getCompressWhitespace() {
314       return new freemarker.template.utility.CompressWhitespace();
315     }
316   }
317 }