another small fix
[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 gnu.regexp.RE;
42
43 import mir.config.MirPropertiesConfiguration;
44 import mir.entity.adapter.EntityAdapter;
45 import mir.entity.adapter.EntityIteratorAdapter;
46 import mir.generator.Generator;
47 import mir.generator.GeneratorExc;
48 import mir.generator.GeneratorFailure;
49 import mir.log.LoggerWrapper;
50 import mir.misc.StringUtil;
51 import mir.util.GeneratorDateTimeFunctions;
52 import mir.util.GeneratorFormatAdapters;
53 import mir.util.generator.ReflectionGeneratorFunctionsAdapter;
54 import mir.util.StringRoutines;
55 import mircoders.global.MirGlobal;
56 import mircoders.localizer.MirLocalizerExc;
57 import mircoders.localizer.MirLocalizerFailure;
58 import mircoders.localizer.MirProducerAssistantLocalizer;
59
60 import org.w3c.dom.Document;
61 import org.w3c.dom.NamedNodeMap;
62 import org.w3c.dom.Node;
63 import org.w3c.dom.NodeList;
64 import org.w3c.tidy.Configuration;
65 import org.w3c.tidy.Tidy;
66
67 public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer {
68   protected LoggerWrapper logger;
69
70   private RE regularExpressionLT;
71   private RE regularExpressionGT;
72
73   public MirBasicProducerAssistantLocalizer() throws MirLocalizerFailure {
74       try{
75           regularExpressionLT = new RE("<");
76           regularExpressionGT = new RE(">");
77       }
78       catch (Throwable t) {
79           throw new MirLocalizerFailure(t);
80       }
81   }
82
83   public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure  {
84     try {
85       Iterator i;
86
87       Map configMap = new HashMap();
88
89       logger = new LoggerWrapper("Localizer.ProducerAssistant");
90
91 // obsolete:
92       configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot"));
93       configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot"));
94       configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost"));
95       configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction"));
96       configMap.put("docRoot", MirGlobal.config().getString("RootUri"));
97       configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir");
98       configMap.put("now", new GeneratorFormatAdapters.DateFormatAdapter(new GregorianCalendar().getTime(), MirGlobal.config().getString("Mir.DefaultTimezone")));
99       configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host"));
100       configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host"));
101       configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host"));
102       configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path"));
103       configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version"));
104       configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding"));
105
106 // "new":
107       configMap.putAll(MirPropertiesConfiguration.instance().allSettings());
108
109       aValueSet.put("config", configMap);
110
111       aValueSet.put("utility", new Utility()); 
112
113       aValueSet.put("languages",
114         new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language"));
115
116       aValueSet.put("topics",
117         new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
118
119       Map articleTypeMap = new HashMap();
120       articleTypeMap.put("openposting", "0");
121       articleTypeMap.put("newswire", "1");
122       articleTypeMap.put("feature", "2");
123       articleTypeMap.put("topicspecial", "3");
124       articleTypeMap.put("startspecial", "4");
125
126       i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType");
127       while (i.hasNext()) {
128         EntityAdapter articleType = (EntityAdapter) i.next();
129
130         articleTypeMap.put(articleType.get("name"), articleType.get("id"));
131       }
132       aValueSet.put("articletype", articleTypeMap);
133
134       Map commentStatusMap = new HashMap();
135       i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus");
136       while (i.hasNext()) {
137         EntityAdapter commentStatus = (EntityAdapter) i.next();
138
139         commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id"));
140       }
141       aValueSet.put("commentstatus", commentStatusMap);
142       aValueSet.put("languageCodeToId", new getLanguageIdFunction());
143     }
144     catch (Throwable t) {
145       logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage());
146
147       throw new MirLocalizerFailure(t);
148     }
149
150   }
151   
152   public static class getLanguageIdFunction implements Generator.Function {
153     private Map languageCodeToId;
154     private String otherLanguageId;
155     private LoggerWrapper logger = new LoggerWrapper("Localizer.Earth.getLanguageIdFunction");
156
157     public getLanguageIdFunction() throws MirLocalizerFailure {
158       try {
159         otherLanguageId = "";
160         languageCodeToId = new HashMap();
161
162         Iterator i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language");
163         while (i.hasNext()) {
164           EntityAdapter language = (EntityAdapter) i.next();
165           if (language.get("code").equals("ot"))
166             otherLanguageId = (String) language.get("id");
167
168           languageCodeToId.put(language.get("code"), language.get("id"));
169         }
170       }
171       catch (Throwable t) {
172         logger.error(t.toString());
173
174         throw new MirLocalizerFailure(t);
175       }
176     }
177
178     public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
179       try {
180         if (aParameters.size() != 1)
181           throw new GeneratorExc("getLanguageIdFunction: 1 parameter expected: language-code");
182
183         String result = (String) languageCodeToId.get(aParameters.get(0));
184         if (result == null)
185           result = otherLanguageId;
186
187         return result;
188       }
189       catch (GeneratorExc e) {
190         throw e;
191       }
192       catch (Throwable t) {
193         throw new GeneratorFailure("getLanguageIdFunction: " + t.getMessage(), t);
194       }
195     }
196   }
197
198
199   public String filterNonHTMLText(String aText) {
200
201     logger.debug("about to filter non HTML Text of length " + aText.length());
202     try {
203       String result =
204           StringUtil.createHTML(
205           StringUtil.removeHTMLTags(aText),
206           MirGlobal.config().getString("Producer.ImageRoot"),
207           MirGlobal.config().getString("Producer.MailLinkName"),
208           MirGlobal.config().getString("Producer.ExtLinkName"),
209           MirGlobal.config().getString("Producer.IntLinkName")
210           );
211       logger.debug("done filtering non-HTML text ");
212       return result;
213     }
214     catch (Throwable t) {
215       logger.error("error while filtering non-HTML text: " + t.toString());
216
217       throw new RuntimeException(t.toString());
218     }
219   }
220   public String filterHTMLText(String aText) {
221     try {
222       StringWriter out = new StringWriter();
223       Tidy tidy = new Tidy();
224       ByteArrayInputStream in = new ByteArrayInputStream(aText.getBytes("UTF8"));
225       tidy.setMakeClean(true);
226       tidy.setCharEncoding(Configuration.UTF8);
227       tidy.setErrout(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
228       print(tidy.parseDOM(in, null), out);
229       
230       return out.toString();
231     }
232     catch (IOException e) {
233       return e.getMessage();
234     }
235   }
236
237   private String[] badAttributes = {"onload","onclick","onfocus","onblur","onmouseover","onmouseout","style","height","width"};
238   
239   private boolean isBadAttr(String attrName){
240       for (int i=0;i<badAttributes.length;i++){
241           if (badAttributes[i].toLowerCase().equals(attrName.toLowerCase()))
242               return true;
243       }
244       return false;
245   }  
246
247   private boolean checkAttr(String attrName) {
248     if (isBadAttr(attrName)){
249         return false;
250     }
251     return true;
252
253   }
254
255   private boolean checkAttrValue(String attrValue) {
256     if (attrValue.toLowerCase().startsWith("javascript:")){
257         return false;
258     }
259     return true;
260
261   }
262
263
264   private boolean checkNode(String nodeName) {
265     List languages =  StringRoutines.splitString(MirGlobal.config().getString("Localizer.HTML.Whitelist"), ";");
266     
267     Iterator i = languages.iterator();
268     while (i.hasNext()) {
269       if (nodeName.equals(i.next()))
270         return true;
271     }
272     return false;
273   }
274
275   private void print(Node node, StringWriter out) throws IOException {
276     if (node == null) {
277       return;
278     }
279     int type = node.getNodeType();
280     boolean canOutput = checkNode(node.getNodeName());
281
282     switch (type) {
283
284       case Node.DOCUMENT_NODE:
285
286         print(((Document) node).getDocumentElement(), out);
287         out.flush();
288         break;
289
290       case Node.ELEMENT_NODE:
291         if (canOutput) {
292           out.write('<');
293
294           out.write(node.getNodeName());
295           NamedNodeMap attrs = node.getAttributes();
296
297           for (int i = 0; i < attrs.getLength(); i++) {
298             String attrName = attrs.item(i).getNodeName();
299             String attrValue = attrs.item(i).getNodeValue();
300             if (checkAttr(attrName) && checkAttrValue(attrValue)) {
301               out.write(' ');
302               out.write(attrs.item(i).getNodeName());
303               out.write("=\"");
304               
305               out.write(attrs.item(i).getNodeValue());
306               out.write('"');
307             }
308           }
309
310           if (node.getChildNodes()==null || node.getChildNodes().getLength()==0) {
311             out.write("/");
312           }
313           out.write('>');
314         }
315         NodeList children = node.getChildNodes();
316         if (children != null) {
317           int len = children.getLength();
318           for (int i = 0; i < len; i++) {
319             print(children.item(i), out);
320           }
321         }
322         break;
323
324       case Node.TEXT_NODE:
325         String value=node.getNodeValue();
326         try{
327           value=regularExpressionLT.substituteAll(value, "&lt;");
328           value=regularExpressionGT.substituteAll(value, "&gt;");
329         }
330         catch (Throwable t){
331           value="";
332         }
333         out.write(value);
334
335         break;
336
337     }
338
339     if (type == Node.ELEMENT_NODE && canOutput && node.getChildNodes()!=null && node.getChildNodes().getLength()>0) {
340       out.write("</");
341       out.write(node.getNodeName());
342       out.write('>');
343     }
344
345     out.flush();
346   }
347
348   public static class Utility extends ReflectionGeneratorFunctionsAdapter {
349     public Utility () {
350       super(new MirBasicUtilityFunctions());
351     }
352
353     public Object getDatetime() {
354       return new GeneratorDateTimeFunctions.DateTimeFunctions(
355         MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"));
356     }
357
358     public Object getCompressWhitespace() {
359       return new freemarker.template.utility.CompressWhitespace();
360     }
361   }
362 }