- experimental opensessions
authorzapata <zapata>
Wed, 16 Apr 2003 03:26:44 +0000 (03:26 +0000)
committerzapata <zapata>
Wed, 16 Apr 2003 03:26:44 +0000 (03:26 +0000)
- experimental media in comments support
- first attempts of replacing cos
- support for Beans by the freemarker generator

71 files changed:
etc/bundles/producer_en.properties
etc/open/donecomment.template [new file with mode: 0755]
etc/open/dupecomment.template [new file with mode: 0755]
etc/open/editcomment.template [new file with mode: 0755]
etc/producer/article.template
lib/commons-beanutils-1.6.1.jar [new file with mode: 0755]
lib/commons-fileupload-1.0-beta-1.jar [new file with mode: 0755]
lib/commons-logging-1.0.3.jar [new file with mode: 0755]
source/OpenMir.java
source/default.properties
source/mir/entity/adapter/EntityAdapterExc.java
source/mir/generator/FreemarkerGenerator.java
source/mir/generator/GeneratorLibraryRepository.java
source/mir/module/AbstractModule.java
source/mir/producer/RSSProducerNode.java
source/mir/producer/SimpleProducerVerb.java
source/mir/producer/reader/ProducerConfigReader.java
source/mir/servlet/ServletModule.java
source/mir/session/CommonsUploadedFileAdapter.java [new file with mode: 0755]
source/mir/session/HTTPAdapters.java [new file with mode: 0755]
source/mir/session/Request.java [new file with mode: 0755]
source/mir/session/Response.java [new file with mode: 0755]
source/mir/session/Session.java [new file with mode: 0755]
source/mir/session/SessionExc.java [new file with mode: 0755]
source/mir/session/SessionFailure.java [new file with mode: 0755]
source/mir/session/SessionHandler.java [new file with mode: 0755]
source/mir/session/SimpleResponse.java [new file with mode: 0755]
source/mir/session/UploadedFile.java [new file with mode: 0755]
source/mir/storage/Database.java
source/mir/storage/store/StoreContainer.java
source/mir/util/FileFunctions.java
source/mir/util/GeneratorIntegerFunctions.java
source/mir/util/HTTPParsedRequest.java [new file with mode: 0755]
source/mir/util/HTTPRequestParser.java
source/mir/util/InternetFunctions.java
source/mir/util/JDBCStringRoutines.java
source/mir/util/PropertiesManipulator.java
source/mir/util/SQLQueryBuilder.java
source/mir/util/StringRoutines.java
source/mir/util/URLBuilder.java
source/mir/util/UtilExc.java [new file with mode: 0755]
source/mir/util/UtilFailure.java [new file with mode: 0755]
source/mircoders/entity/EntityMedia.java
source/mircoders/global/Abuse.java
source/mircoders/localizer/MirLocalizer.java
source/mircoders/localizer/MirOpenPostingLocalizer.java
source/mircoders/localizer/basic/MirBasicCommentPostingSessionHandler.java [new file with mode: 0755]
source/mircoders/localizer/basic/MirBasicLocalizer.java
source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java
source/mircoders/media/MediaUploadProcessor.java [new file with mode: 0755]
source/mircoders/media/UnsupportedMediaFormatExc.java
source/mircoders/module/ModuleContent.java
source/mircoders/module/ModuleMediaType.java [new file with mode: 0755]
source/mircoders/module/ModuleUploadedMedia.java
source/mircoders/servlet/ServletHelper.java
source/mircoders/servlet/ServletModuleAbuse.java
source/mircoders/servlet/ServletModuleOpenIndy.java
source/tool/BundleTool.java
templates/admin/FUNCTIONS.template
templates/admin/abuse.filters.template
templates/admin/abuse.template
templates/admin/articletypelist.template
templates/admin/audio.template
templates/admin/comment.template
templates/admin/content.template
templates/admin/image.template
templates/admin/media.template
templates/admin/mediafolder.template
templates/admin/message.template
templates/admin/topic.template
templates/admin/video.template

index 737e5dc..aae675f 100755 (executable)
@@ -40,6 +40,7 @@ article.homepage.prefix = Homepage:
 article.addcomment = Make a quick comment on this article
 article.send_as_email = Email this article to someone 
 article.get_as_pdf = Download this article in pdf format 
+article.add_to_pdf = Add this article to your pdf newsletter selection
 
 newswirearchive.title = Newswire archive
 featurearchive.title = Feature archive
diff --git a/etc/open/donecomment.template b/etc/open/donecomment.template
new file mode 100755 (executable)
index 0000000..bf9d1ed
--- /dev/null
@@ -0,0 +1,37 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+       <title>${lang("commentdone.htmltitle")}</title>
+</head>
+
+<body bgcolor="White" text="Black" link="#006600" vlink="#009900" alink="Red">
+
+<table width="100%" border="0" cellspacing="0" cellpadding="10">
+       <tr>
+               <td valign="top" align="center" bgcolor="#663399">
+                       <font color="White"><b>${lang("commentdone.thanks")}</b></font
+               </td>
+       </tr>
+       <tr>
+               <td bgcolor="#cccccc" align="center">
+
+                               <br>
+                ${lang("commentdone.wait")}
+                               <br>
+                ${lang("commentdone.criteria")}
+                               <br>
+                               <em>${lang("commentdone.stay_calm")}</em><br>
+                               <br>
+
+               </td>
+       </tr>
+       <tr>
+               <td valign="top" align="center" bgcolor="#663399">
+                       <a href="javascript:history.go(-2)"><font color="White"><b>&gt;&gt; ${lang("commentdone.back")}</b></font></a>
+               </td>
+       </tr>
+</table>
+
+</body>
+</html>
diff --git a/etc/open/dupecomment.template b/etc/open/dupecomment.template
new file mode 100755 (executable)
index 0000000..2e9ce66
--- /dev/null
@@ -0,0 +1,37 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+       <title>${lang("commentdupe.htmltitle")}</title>
+</head>
+
+<body bgcolor="White" text="Black" link="white" vlink="#009900" alink="Red">
+
+<table width="100%" border="0" cellspacing="0" cellpadding="10">
+       <tr>
+               <td valign="top" align="center" bgcolor="#663399">
+                       <font color="White"><b>
+                               ${lang("commentdupe.title")}
+                       </b></font
+               </td>
+       </tr>
+       <tr>
+               <td bgcolor="003300" width=70%>
+                       <font color="White">
+                               <br>
+                    ${lang("commentdupe.explanation")}
+                               <br>
+                               <center><em>${lang("commentdupe.no_panic")}</em></center><br>
+                               <br>
+                       </font>
+               </td>
+       </tr>
+       <tr>
+               <td valign="top" align="center" bgcolor="#663399">
+                       <a href="javascript:history.go(-2)"><font color="White"><b>&gt;&gt; ${lang("commentdupe.back")}</b></font></a>
+               </td>
+       </tr>
+</table>
+
+</body>
+</html>
diff --git a/etc/open/editcomment.template b/etc/open/editcomment.template
new file mode 100755 (executable)
index 0000000..5414017
--- /dev/null
@@ -0,0 +1,234 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\r
+<html>\r
+  <head>\r
+    <title>${lang("comment.htmltitle")}</title> \r
+  </head>\r
+  \r
+  <body marginwidth="0" marginheight="0" leftmargin="0" topmargin="0" bgcolor="#dddddd">\r
+    <form enctype="multipart/form-data" action="${actionURL}&do=opensession" method="post">\r
+      <input type="hidden" name="do" value="processcomment">\r
+      <input type="hidden" name="to_media" value="${to_media}">\r
+    \r
+      <table cellspacing="0" cellpadding="0" width="100%">\r
+        <tr>\r
+          <td colspan="3"><span>&nbsp;</span></td>\r
+        </tr>
+        <if errors>\r
+        <tr>\r
+          <td colspan="3">
+            Your input had the following errors:<br><br>
+            <list errors as e>
+              <font color="red">
+              <if e.field>
+                ${lang("comment."+e.field)}:
+              </if>
+              ${lang(e.message)} <br>
+              </font>
+            </list>
+          </td>\r
+        </tr>
+        </if>\r
+        <if password>\r
+          <tr>\r
+            <td align="right">&nbsp;</td>\r
+            <td>\r
+              ${lang("comment.note")}\r
+                     <br>${data.passwd}<br>\r
+               <br>\r
+            </td>\r
+            <td>&nbsp;</td>\r
+          </tr>\r
+          <tr>\r
+            <td></td>\r
+            <td  valign="top">\r
+                  ${lang("comment.password")}: <input type="text" name="passwd" size="10">\r
+            </td>\r
+            <td>&nbsp;</td>\r
+          </tr>\r
+        </if>\r
+        <tr>\r
+          <td width="20%" bgcolor="#cc0033">\r
+          </td>\r
+          <td width="60%" bgcolor="#cc0033">\r
+            <span id="title"><b>${lang("comment.formtitle")}</b></span>\r
+          </td>\r
+          <td width="20%">&nbsp;</td>\r
+        </tr>\r
+        <tr>\r
+          <td colspan="3"><span>&nbsp;</span></td>\r
+        </tr>\r
+\r
+        <tr>\r
+          <td align="right" valign="top">&nbsp;</td>\r
+          <td valign="top" bgcolor="#cc9999" cellpadding="8" >\r
+            <b><font color="#cc0033">R E Q U I R E D</font> information</b>\r
+          </td>\r
+          <td>&nbsp;</td>\r
+        </tr>\r
+        <tr>\r
+          <td colspan="3"><span>&nbsp;</span></td>\r
+        </tr>\r
+        <tr>\r
+          <td align="right">\r
+            ${lang("comment.title")}:\r
+          </td>\r
+          <td>\r
+            <input type="text" name="title"  maxlength="45" value="${utility.encodeHTML(title)}">\r
+          </td>\r
+          <td></td>\r
+        </tr>\r
+        <tr>\r
+          <td align="right" valign="top">\r
+            ${lang("comment.text")}:\r
+          </td>\r
+          <td> \r
+            <textarea name="description" rows="10" wrap="virtual">${utility.encodeHTML(description)}</textarea>\r
+          </td>\r
+          <td></td>\r
+        </tr>\r
+        <tr>\r
+          <td align="right">\r
+            ${lang("comment.name")}:<br><br>\r
+          </td>\r
+          <td>\r
+            <input type="text" name="creator"  maxlength="45" value="${utility.encodeHTML(creator)}">\r
+            <br><br>\r
+          </td>\r
+          <td></td>\r
+        </tr>\r
+        \r
+        <tr>\r
+          <td align="right" valign="top">&nbsp;</td>\r
+          <td valign="top" bgcolor="#cc9999">\r
+            <b>Additional information</b>\r
+          </td>\r
+          <td>&nbsp;</td>\r
+        </tr>\r
+        <tr>\r
+          <td colspan="3"><span>&nbsp;</span></td>\r
+        </tr>\r
+        <tr>\r
+          <td align="right">\r
+            ${lang("comment.language")}:<br><br>\r
+          </td>\r
+          <td>      \r
+            <select name="to_language"  size="1">\r
+              <list languages as l>\r
+                <option value="${l.id}" <if to_language==l.id>selected="1"</if>>${l.name}</option>\r
+              </list>\r
+            </select>\r
+            <br><br>\r
+          </td>\r
+          <td>&nbsp;</td>\r
+        </tr>\r
+        \r
+        <tr>\r
+          <td align="right" valign="top">&nbsp;</td>\r
+          <td valign="top" bgcolor="#cc9999">\r
+            <b>Contact information</b>\r
+          </td>\r
+          <td>&nbsp;</td>\r
+        </tr>\r
+        <tr>\r
+          <td colspan="3"><span>&nbsp;</span></td>\r
+        </tr>\r
+        <tr>\r
+          <td align="right">&nbsp;</td>\r
+          <td>\r
+             ${lang("comment.contact.info")}\r
+          </td>\r
+          <td>&nbsp;</td>\r
+        </tr>\r
+        <tr>\r
+          <td align="right">\r
+            ${lang("comment.email")}:\r
+          </td>\r
+          <td>\r
+            <input type="text" name="email" maxlength="80" value="">\r
+          </td>\r
+          <td>&nbsp;</td>\r
+        </tr>\r
+        <tr>\r
+          <td align="right">\r
+            ${lang("comment.url")}:\r
+          </td>\r
+          <td>\r
+            <input type="text" name="main_url" maxlength="160" value="http://">\r
+          </td>\r
+          <td>&nbsp;</td>\r
+        </tr>\r
+        <tr>\r
+          <td align="right">\r
+            ${lang("comment.address")}:\r
+          </td>\r
+          <td>\r
+            <input type="text" name="address" maxlength="160" value="">\r
+          </td>\r
+          <td>&nbsp;</td>\r
+        </tr>\r
+        <tr>\r
+          <td align="right">\r
+            ${lang("comment.phone")}<br><br>\r
+          </td>\r
+          <td>\r
+            <input type="text" name="phone" maxlength="20" value=""><br><br>\r
+          </td>\r
+          <td>&nbsp;</td>\r
+        </tr>\r
+        \r
+       <tr>
+               <td>
+               ${lang("posting.media.title")} 1:
+               </td>
+               <td colspan="2">
+                       <input type="text" name="media_title1" size="40" maxlength="80" value=""><br>
+               </td>
+       </tr>
+       <tr>
+               <td>${lang("posting.media.media")} 1</td>
+               <td colspan="2">
+                       <INPUT TYPE="file" NAME="media1">
+               </td>
+       </tr>
+       <tr>
+               <td>
+               ${lang("posting.media.title")} 2:
+               </td>
+               <td colspan="2">
+                       <input type="text" name="media_title2" size="40" maxlength="80" value=""><br>
+               </td>
+       </tr>
+       <tr>
+               <td>${lang("posting.media.media")} 2</td>
+               <td colspan="2">
+                       <INPUT TYPE="file" NAME="media2">
+               </td>
+       </tr>
+       <tr>
+               <td>
+               ${lang("posting.media.title")} 3:
+               </td>
+               <td colspan="2">
+                       <input type="text" name="media_title3" size="40" maxlength="80" value=""><br>
+               </td>
+       </tr>
+       <tr>
+               <td>${lang("posting.media.media")} 3</td>
+               <td colspan="2">
+                       <INPUT TYPE="file" NAME="media3">
+               </td>
+       </tr>
+        <tr>\r
+          <td align="right">&nbsp;</td>\r
+          <td  bgcolor="#cc0033">\r
+            <input id="button" type="submit" value="${lang("comment.submit")}">\r
+          </td>\r
+          <td bgcolor="#cc0033">&nbsp;</td>\r
+        </tr>\r
+        <tr>\r
+          <td colspan="3">&nbsp;<br><br></td>\r
+        </tr>\r
+      </table>\r
+    </form>\r
+  </body>\r
+</html>\r
index 83f90d8..77aaf97 100755 (executable)
                                        </td></tr></table>
 <br>
                                        <table border="0" cellpadding="2" cellspacing="0" width="100%"><tr><td bgcolor="#669999">
-            &nbsp;<a href="${config["Producer.OpenAction"]}?do=addcomment&aid=${article.id}&language=${language.code}">
+           &nbsp;<a href="${config["Producer.OpenAction"]}?do=addcomment&aid=${article.id}&language=${language.code}">
             <font color="#dddddd" size="+1"><b>${lang("article.addcomment")}&gt;&gt;</b></font></a>
                                        </td></tr></table>
                                        <if article.to_comments>
                                                                <br>
                                                                <font size="+1"><b>${utility.encodeHTML(c.title)}</b></font><br>
                                                                <i>${c.creationdate.formatted["dd.MM.yyyy HH:mm"]}</i><br>
+
+                                       <list c.to_media_audio as media>
+                                         <a href="${media["publish_server"]}${media["publish_path"]}">
+                                           ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]}
+                                         </a>
+                                       </list>
+                                       <list c.to_media_video as media>
+                                       <img src="../../../img/${media["big_icon"]}" border="0" alt="">
+                                       <a href="${media["publish_server"]}${media["publish_path"]}">
+                                       ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]}</a>
+                                       </list>
+                                       <list c.to_media_other as media>
+                                       <img src="../../../img/${media["big_icon"]}" border="0" alt="">
+                                       <a href="${media["publish_server"]}${media["publish_path"]}">
+                                       ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]}</a>
+                                       </list>
+                                       
+                                       <list c.to_media_images as image>
+                                       <img src="${image["publish_server"]}${image["publish_path"]}"
+                                       border="0" width="${image["img_width"]}"
+                                       height="${image["img_height"]}" alt="${image["title"]}">
+                                       <br><i>${image["title"]}</i>
+                                       </list>
+
+
                                                                ${c.description_parsed}
                                                                <if c.email || c.main_url || c.address || c.phone || c.creator>
                                                                        <i>
diff --git a/lib/commons-beanutils-1.6.1.jar b/lib/commons-beanutils-1.6.1.jar
new file mode 100755 (executable)
index 0000000..795655a
Binary files /dev/null and b/lib/commons-beanutils-1.6.1.jar differ
diff --git a/lib/commons-fileupload-1.0-beta-1.jar b/lib/commons-fileupload-1.0-beta-1.jar
new file mode 100755 (executable)
index 0000000..ab99356
Binary files /dev/null and b/lib/commons-fileupload-1.0-beta-1.jar differ
diff --git a/lib/commons-logging-1.0.3.jar b/lib/commons-logging-1.0.3.jar
new file mode 100755 (executable)
index 0000000..b99c937
Binary files /dev/null and b/lib/commons-logging-1.0.3.jar differ
index f8cc73e..791e345 100755 (executable)
@@ -47,7 +47,7 @@ import mircoders.servlet.ServletModuleOpenIndy;
  *  OpenMir.java - main servlet for open posting and comment feature to articles
  *
  *  @author RK 1999-2001, the mir-coders group
- *  @version $Id: OpenMir.java,v 1.31 2003/04/09 02:06:06 zapata Exp $
+ *  @version $Id: OpenMir.java,v 1.32 2003/04/16 03:26:44 zapata Exp $
  *
  */
 
@@ -63,6 +63,7 @@ public class OpenMir extends AbstractServlet {
     long startTime = System.currentTimeMillis();
     long sessionConnectTime=0;
 
+
     HttpSession session = aRequest.getSession();
 
     checkLanguage(session, aRequest);
@@ -70,8 +71,7 @@ public class OpenMir extends AbstractServlet {
     //make sure client browsers don't cache anything
     setNoCaching(aResponse);
 
-    aResponse.setContentType("text/html");
-    //aResponse.setContentType("text/html; charset="+MirPropertiesConfiguration.instance().getString("Mir.DefaultHTMLCharset"));
+    aResponse.setContentType("text/html; charset="+configuration.getString("Mir.DefaultHTMLCharset"));
 
     try {
       ServletModuleDispatch.dispatch(ServletModuleOpenIndy.getInstance(), aRequest, aResponse);
@@ -115,9 +115,6 @@ public class OpenMir extends AbstractServlet {
     String acceptLanguage = aRequest.getLocale().getLanguage();
     String defaultLanguage = MirGlobal.config().getString("Mir.Login.DefaultLanguage", "en");
 
-    logger.debug(" requestlanguage = " + requestLanguage + ", sessionLanugage = " + sessionLanguage +
-                 ", acceptLanguage = " + acceptLanguage + ", defaultLanguage = " + defaultLanguage);
-
     String language = requestLanguage;
 
     if (language==null)
index 356f6bb..531c749 100755 (executable)
@@ -113,7 +113,7 @@ Mir.Localizer.Producer.AllNewProducers= media.new;articles.changed;startpage.run
 
 #note that you can't make pdf's without making fo's
 #this is actually now set in producers.xml
-#but these summarize what is said in there for the benefit of OpenMir 
+#but these summarize what is said in there for the benefit of OpenMir
 GenerateFO=yes
 GeneratePDF=yes
 
@@ -201,7 +201,7 @@ Producer.Image.MaxIconSize = 120
 Producer.Image.MinDescalePercentage=10
 
 # descaling will only occur if at least the following number of pixels needs
-#  to be removed from either the width or the height: 
+#  to be removed from either the width or the height:
 Producer.Image.MinDescaleReduction=10
 
 
@@ -231,7 +231,7 @@ Producer.Icon.BigVideo=video_big.gif
 Producer.Icon.BigText=text_big.gif
 
 #the style sheet used to turn html into xsl:fo
-Producer.HTML2FOStyleSheet=/some/dir/mir/etc/producer/html2fo.xsl 
+Producer.HTML2FOStyleSheet=/some/dir/mir/etc/producer/html2fo.xsl
 
 # the following lines are used to construct PDFs on the fly from one or more articles
 # for the moment, if you want to change anything else about your pdfs, you 
@@ -310,10 +310,14 @@ Mir.DefaultHTMLCharset=UTF-8
 
 
 
+Localizer.OpenSession.comment.EditTemplate = editcomment.template
+Localizer.OpenSession.comment.DupeTemplate = donecomment.template
+Localizer.OpenSession.comment.DoneTemplate = dupecomment.template
+
+
 #
 # config used for OpenIndy
 
-OpenMir.TemplateDir=etc/open/
 ServletModule.OpenIndy.CommentTemplate=comment.template
 ServletModule.OpenIndy.CommentDoneTemplate=comment_done.template
 ServletModule.OpenIndy.CommentDupeTemplate=comment_dupe.template
index b3a7681..9d21d57 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.entity.adapter;
 
 import multex.Exc;
index d4fda8c..ea0c69d 100755 (executable)
@@ -38,10 +38,9 @@ import java.util.List;
 import java.util.Map;
 import java.util.Vector;
 
-import mir.util.RewindableIterator;
-import mir.util.*;
-
 import org.apache.struts.util.MessageResources;
+import org.apache.commons.beanutils.PropertyUtils;
+
 
 import freemarker.template.FileTemplateCache;
 import freemarker.template.SimpleScalar;
@@ -54,6 +53,10 @@ import freemarker.template.TemplateModelException;
 import freemarker.template.TemplateModelRoot;
 import freemarker.template.TemplateScalarModel;
 
+import mir.util.RewindableIterator;
+import mir.util.*;
+
+
 public class FreemarkerGenerator implements Generator {
   private Template template;
 
@@ -92,6 +95,10 @@ public class FreemarkerGenerator implements Generator {
     return new FunctionAdapter(aFunction);
   }
 
+  private static TemplateHashModel makeBeanAdapter(Object anObject)  {
+    return new BeanAdapter(anObject);
+  }
+
   public static TemplateModel makeAdapter(Object anObject) throws TemplateModelException {
     if (anObject == null)
       return null;
@@ -117,12 +124,13 @@ public class FreemarkerGenerator implements Generator {
     else if (anObject instanceof List)
       return makeIteratorAdapter(((List) anObject).iterator());
     else
-      throw new TemplateModelException("Unadaptable class: " + anObject.getClass().getName());
+      return makeBeanAdapter(anObject);
+//      throw new TemplateModelException("Unadaptable class: " + anObject.getClass().getName());
   }
 
   private static class MapAdapter implements TemplateModelRoot {
-    Map map;
-    Map valuesCache;
+    private Map map;
+    private Map valuesCache;
 
     private MapAdapter(Map aMap) {
       map = aMap;
@@ -165,9 +173,9 @@ public class FreemarkerGenerator implements Generator {
   }
 
   private static class IteratorAdapter implements TemplateListModel {
-    Iterator iterator;
-    List valuesCache;
-    int position;
+    private Iterator iterator;
+    private List valuesCache;
+    private int position;
 
     private IteratorAdapter(Iterator anIterator) {
       iterator = anIterator;
@@ -290,7 +298,7 @@ public class FreemarkerGenerator implements Generator {
   }
 
   private static class FunctionAdapter implements TemplateMethodModel {
-    Generator.GeneratorFunction function;
+    private Generator.GeneratorFunction function;
 
     public FunctionAdapter(Generator.GeneratorFunction aFunction) {
       function = aFunction;
@@ -311,6 +319,35 @@ public class FreemarkerGenerator implements Generator {
 
   }
 
+  private static class BeanAdapter implements TemplateHashModel {
+    private Object object;
+
+    public BeanAdapter(Object anObject) {
+      object = anObject;
+    }
+
+    public void put(String aKey, TemplateModel aModel)  throws TemplateModelException  {
+      throw new TemplateModelException("FreemarkerGenerator$BeanAdapter.put not supported");
+    }
+
+    public void remove(String aKey) throws TemplateModelException  {
+      throw new TemplateModelException("FreemarkerGenerator$BeanAdapter.remove not supported");
+    }
+
+    public boolean isEmpty() {
+      return false;
+    }
+
+    public TemplateModel get(String aKey) throws TemplateModelException {
+      try {
+        return makeAdapter(PropertyUtils.getSimpleProperty(object, aKey));
+      }
+      catch (Throwable t) {
+        throw new TemplateModelException(t.getMessage());
+      }
+    }
+  }
+
   public static class FreemarkerGeneratorLibrary implements GeneratorLibrary {
     private FileTemplateCache templateCache;
 
index 06dde95..639c9c1 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.generator;
 
 import java.util.HashMap;
index 25a2282..3687748 100755 (executable)
@@ -179,6 +179,26 @@ public class AbstractModule {
   }
 
   /**
+   * This function creates an Entity without yet storing it in the database
+   *
+   * @param theValues
+   * @return
+   * @throws ModuleExc
+   * @throws ModuleFailure
+   */
+  public Entity createNew() throws ModuleExc, ModuleFailure {
+    try {
+      Entity result = (Entity)theStorage.getEntityClass().newInstance();
+      result.setStorage(theStorage);
+
+      return result;
+    }
+    catch (Throwable e) {
+      throw new ModuleFailure(e);
+    }
+  }
+
+  /**
    * Standardfunktion, um einen Datensatz via StorageObject zu aktualisieren
    * @param theValues Hash mit Spalte/Wert-Paaren
    * @return Id des eingef?gten Objekts
index d3ee397..6db8088 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.producer;
 
 import java.util.Map;
index 57c39cc..66d2f90 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.producer;
 
 public class SimpleProducerVerb implements ProducerFactory.ProducerVerb {
index 1eabcc2..f71c5b1 100755 (executable)
@@ -277,8 +277,7 @@ public class ProducerConfigReader {
         return new ProducerNodeSectionHandler();
       }
       else
-        throw new XMLReader.XMLReaderExc("Only 'verb' tags allowed here, '" +
-                                         aTag + "' encountered.");
+        throw new XMLReader.XMLReaderExc("Only 'verb' tags allowed here, '" + aTag + "' encountered.");
     }
 
     public void endElement(XMLReader.SectionHandler aHandler) {
index f114804..6dc534c 100755 (executable)
@@ -475,8 +475,6 @@ public abstract class ServletModule {
       for (int i = 0; i < theFieldList.size(); i++) {\r
         aField = (String) theFieldList.get(i);\r
 \r
-        logger.debug("field " + aField + " = " + parser.getParameter(aField));\r
-\r
         aValue = parser.getParameter(aField);\r
         if (aValue != null)\r
           withValues.put(aField, aValue);\r
diff --git a/source/mir/session/CommonsUploadedFileAdapter.java b/source/mir/session/CommonsUploadedFileAdapter.java
new file mode 100755 (executable)
index 0000000..42b2d91
--- /dev/null
@@ -0,0 +1,27 @@
+package mir.session;\r
+\r
+import org.apache.commons.fileupload.*;\r
+import java.io.*;\r
+\r
+public class CommonsUploadedFileAdapter implements UploadedFile {\r
+  private FileItem fileItem;\r
+  private Object container;\r
+\r
+  public CommonsUploadedFileAdapter(Object aContainer, FileItem aFileItem) {\r
+    container = aContainer;\r
+    fileItem = aFileItem;\r
+  }\r
+\r
+  public InputStream getInputStream() throws SessionExc, SessionFailure{\r
+    try {\r
+      return fileItem.getInputStream();\r
+    }\r
+    catch (Throwable t) {\r
+      throw new SessionFailure(t);\r
+    }\r
+  };\r
+\r
+  public String getContentType() {\r
+    return fileItem.getContentType();\r
+  };\r
+}
\ No newline at end of file
diff --git a/source/mir/session/HTTPAdapters.java b/source/mir/session/HTTPAdapters.java
new file mode 100755 (executable)
index 0000000..b8d4181
--- /dev/null
@@ -0,0 +1,91 @@
+package mir.session;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+import java.util.Vector;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpSession;\r
+\r
+import org.apache.commons.fileupload.FileItem;\r
+\r
+import mir.util.HTTPParsedRequest;\r
+\r
+public class HTTPAdapters {\r
+  public static class HTTPRequestAdapter implements Request {\r
+    private HttpServletRequest request;\r
+\r
+    public HTTPRequestAdapter(HttpServletRequest aRequest) {\r
+      request = aRequest;\r
+    }\r
+\r
+    public String getParameter(String aName) {\r
+      return request.getParameter(aName);\r
+    };\r
+\r
+    public List getUploadedFiles() {\r
+      return new Vector();\r
+    };\r
+\r
+    public List getParameters(String aName) {\r
+      return Arrays.asList(request.getParameterValues(aName));\r
+    };\r
+\r
+    public HttpServletRequest getRequest() {\r
+      return request;\r
+    }\r
+  }\r
+\r
+  public static class HTTPParsedRequestAdapter implements Request {\r
+    private HTTPParsedRequest request;\r
+\r
+    public HTTPParsedRequestAdapter(HTTPParsedRequest aRequest) {\r
+      request = aRequest;\r
+    }\r
+\r
+    public String getParameter(String aName) {\r
+      return request.getParameter(aName);\r
+    };\r
+\r
+    public List getParameters(String aName) {\r
+      return request.getParameterList(aName);\r
+    };\r
+\r
+    public List getUploadedFiles() {\r
+      List result = new Vector();\r
+      List files = request.getFiles();\r
+\r
+      for (int i=0; i<files.size(); i++) {\r
+        result.add(new CommonsUploadedFileAdapter(request, (FileItem) files.get(i)));\r
+      }\r
+\r
+      return result;\r
+    };\r
+\r
+    public HttpServletRequest getRequest() {\r
+      return request.getRequest();\r
+    }\r
+  }\r
+\r
+  public static class HTTPSessionAdapter implements Session {\r
+    private HttpSession session;\r
+\r
+    public HTTPSessionAdapter(HttpSession aSession) {\r
+      session = aSession;\r
+    }\r
+    public Object getAttribute(String aName) {\r
+      return session.getAttribute(aName);\r
+    }\r
+\r
+    public void deleteAttribute(String aName) {\r
+      session.removeAttribute(aName);\r
+    }\r
+\r
+    public void setAttribute(String aName, Object aNewValue) {\r
+      session.setAttribute(aName, aNewValue);\r
+    }\r
+\r
+    public void terminate() {\r
+      session.invalidate();\r
+    }\r
+  }\r
+}
\ No newline at end of file
diff --git a/source/mir/session/Request.java b/source/mir/session/Request.java
new file mode 100755 (executable)
index 0000000..bc7fb2d
--- /dev/null
@@ -0,0 +1,9 @@
+package mir.session;
+
+import java.util.*;
+
+public interface Request {
+  public String getParameter(String aName);
+  public List getUploadedFiles();
+  public List getParameters(String aName);
+}
\ No newline at end of file
diff --git a/source/mir/session/Response.java b/source/mir/session/Response.java
new file mode 100755 (executable)
index 0000000..334139e
--- /dev/null
@@ -0,0 +1,8 @@
+package mir.session;
+
+import java.util.Map;
+
+public interface Response {
+  public void setResponseValue(String aName, Object aValue);
+  public void setResponseGenerator(String aGenerator);
+}
diff --git a/source/mir/session/Session.java b/source/mir/session/Session.java
new file mode 100755 (executable)
index 0000000..facd8ff
--- /dev/null
@@ -0,0 +1,8 @@
+package mir.session;
+
+public interface Session {
+  public Object getAttribute(String aName);
+  public void setAttribute(String aName, Object aNewValue);
+  public void deleteAttribute(String aName);
+  public void terminate();
+}
diff --git a/source/mir/session/SessionExc.java b/source/mir/session/SessionExc.java
new file mode 100755 (executable)
index 0000000..3c31684
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
+package mir.session;
+
+import multex.Exc;
+
+public class SessionExc extends Exc {
+  public SessionExc(String aMessage) {
+    super(aMessage);
+  }
+}
diff --git a/source/mir/session/SessionFailure.java b/source/mir/session/SessionFailure.java
new file mode 100755 (executable)
index 0000000..e1c1cea
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
+package mir.session;
+
+import multex.Failure;
+
+public class SessionFailure extends Failure {
+
+  public SessionFailure(String msg,Throwable cause) {
+    super(msg,cause);
+  }
+
+  public SessionFailure(Throwable aCause) {
+    this (aCause.getMessage(), aCause);
+  }
+}
diff --git a/source/mir/session/SessionHandler.java b/source/mir/session/SessionHandler.java
new file mode 100755 (executable)
index 0000000..87b3801
--- /dev/null
@@ -0,0 +1,5 @@
+package mir.session;
+
+public interface SessionHandler {
+  public void processRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure;
+}
diff --git a/source/mir/session/SimpleResponse.java b/source/mir/session/SimpleResponse.java
new file mode 100755 (executable)
index 0000000..3dcadf5
--- /dev/null
@@ -0,0 +1,32 @@
+package mir.session;\r
+\r
+import java.util.*;\r
+\r
+public class SimpleResponse implements Response {\r
+  private String generator;\r
+  private Map values;\r
+\r
+  public SimpleResponse() {\r
+    values = new HashMap();\r
+  }\r
+\r
+  public SimpleResponse(Map aMap) {\r
+    values = aMap;\r
+  }\r
+\r
+  public void setResponseValue(String aName, Object aValue) {\r
+    values.put(aName, aValue);\r
+  }\r
+\r
+  public Map getResponseValues() {\r
+    return values;\r
+  }\r
+\r
+  public void setResponseGenerator(String aGenerator) {\r
+    generator = aGenerator;\r
+  }\r
+\r
+  public String getResponseGenerator() {\r
+    return generator;\r
+  }\r
+}
\ No newline at end of file
diff --git a/source/mir/session/UploadedFile.java b/source/mir/session/UploadedFile.java
new file mode 100755 (executable)
index 0000000..ae6f454
--- /dev/null
@@ -0,0 +1,8 @@
+package mir.session;
+
+import java.io.InputStream;
+
+public interface UploadedFile {
+  InputStream getInputStream() throws SessionExc, SessionFailure;
+  String getContentType();
+}
\ No newline at end of file
index 16b88e5..2774c11 100755 (executable)
@@ -77,7 +77,7 @@ import freemarker.template.SimpleList;
  * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
  * Datenbank erfolgt.
  *
- * @version $Id: Database.java,v 1.37 2003/04/09 02:06:07 zapata Exp $
+ * @version $Id: Database.java,v 1.38 2003/04/16 03:26:45 zapata Exp $
  * @author rk
  *
  */
@@ -831,7 +831,7 @@ public class Database implements StorageObject {
                                         .append(") values (").append(v).append(")");
       String sql = sqlBuf.toString();
 
-      //theLog.printInfo("INSERT: " + sql);
+      logger.debug("INSERT: " + sql);
       con = getPooledCon();
       con.setAutoCommit(false);
       pstmt = con.prepareStatement(sql);
index 567d965..bcc4c8a 100755 (executable)
@@ -109,7 +109,7 @@ public class StoreContainer {
     if (sid != null && sid.hasReference()) {
       if (has(sid)) {
         moveToHead(sid);
-        logger.error("OBJECTStore: tried to add sid " + sid.toString() + " that was already in store.");
+        logger.debug("OBJECTStore: tried to add sid " + sid.toString() + " that was already in store.");
       }
       else {
         container.addFirst(sid);
index 20d20e5..77cdc1b 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.util;
 
 import java.io.File;
index af9d653..19d3b04 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.util;
 
 import java.util.List;
diff --git a/source/mir/util/HTTPParsedRequest.java b/source/mir/util/HTTPParsedRequest.java
new file mode 100755 (executable)
index 0000000..e49ba1b
--- /dev/null
@@ -0,0 +1,159 @@
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mir.util;\r
+\r
+import java.util.Arrays;\r
+import java.util.Enumeration;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+import javax.servlet.http.HttpServletRequest;\r
+\r
+import org.apache.commons.fileupload.FileItem;\r
+import org.apache.commons.fileupload.FileUpload;\r
+import mir.log.LoggerWrapper;\r
+\r
+public class HTTPParsedRequest {\r
+  static final String MULTIPART_FORMDATA_CONTENTTYPE = "multipart/form-data";\r
+\r
+  private HttpServletRequest request;\r
+  private String encoding;\r
+  private int maxUploadSize;\r
+  private String tempDir;\r
+\r
+  private Map stringValues;\r
+  private Map listValues;\r
+  private List files;\r
+\r
+  private LoggerWrapper logger;\r
+\r
+  public HTTPParsedRequest(HttpServletRequest aRequest, String anEncoding, int aMaxUploadSize, String aTempDir) throws UtilExc, UtilFailure {\r
+    logger = new LoggerWrapper("Utility,HTTPParsedRequest");\r
+\r
+    request = aRequest;\r
+    encoding = anEncoding;\r
+    maxUploadSize = aMaxUploadSize;\r
+    tempDir = aTempDir;\r
+\r
+    stringValues = new HashMap();\r
+    listValues = new HashMap();\r
+    files = new Vector();\r
+\r
+    parseRequest(aRequest);\r
+  }\r
+\r
+  public HTTPParsedRequest(HttpServletRequest aRequest, int aMaxUploadSize, String aTempDir) throws UtilExc, UtilFailure {\r
+    this(aRequest, aRequest.getCharacterEncoding(), aMaxUploadSize, aTempDir);\r
+  }\r
+\r
+  public HttpServletRequest getRequest() {\r
+    return request;\r
+  }\r
+\r
+  public String getParameter(String aName) {\r
+    return (String) stringValues.get(aName);\r
+  }\r
+\r
+  public List getFiles() {\r
+    return files;\r
+  }\r
+\r
+  public List getParameterList(String aName) {\r
+    return (List) listValues.get(aName);\r
+  }\r
+\r
+  protected void parseRequest(HttpServletRequest aRequest) throws UtilExc, UtilFailure {\r
+\r
+    try {\r
+      String contentType = aRequest.getContentType();\r
+      List parts = StringRoutines.splitString(contentType, ";");\r
+\r
+      Enumeration e = aRequest.getParameterNames();\r
+\r
+      while (e.hasMoreElements()) {\r
+        String name = (String) e.nextElement();\r
+\r
+        stringValues.put(name, aRequest.getParameter(name));\r
+        List listValue = new Vector(Arrays.asList(aRequest.getParameterValues(name)));\r
+        listValues.put(name, listValue);\r
+      }\r
+\r
+      if (parts.size()>0 && ((String) parts.get(0)).trim().toLowerCase().equals(MULTIPART_FORMDATA_CONTENTTYPE)) {\r
+        parseMultipartRequest();\r
+      }\r
+    }\r
+    catch (Throwable t) {\r
+      t.printStackTrace();\r
+\r
+      throw new UtilFailure(t);\r
+    }\r
+  }\r
+\r
+  protected void parseMultipartRequest() throws UtilExc, UtilFailure {\r
+    try {\r
+      FileUpload upload = new FileUpload();\r
+\r
+      upload.setSizeMax(maxUploadSize);\r
+      upload.setSizeThreshold(4096);\r
+      upload.setRepositoryPath(tempDir);\r
+\r
+      List items = upload.parseRequest(request);\r
+\r
+      Iterator i = items.iterator();\r
+      while (i.hasNext()) {\r
+        FileItem item = (FileItem) i.next();\r
+\r
+        if (item.isFormField()) {\r
+          if (!stringValues.containsKey(item.getName())) {\r
+            stringValues.put(item.getFieldName(), item.getString());\r
+          }\r
+\r
+          List listValue = (List) listValues.get(item.getFieldName());\r
+          if (listValue == null) {\r
+            listValue = new Vector();\r
+            listValues.put(item.getFieldName(), listValue);\r
+          }\r
+          listValue.add(item.getString());\r
+        }\r
+        else {\r
+          if (item.getSize()>0)\r
+            files.add(item);\r
+        }\r
+      }\r
+    }\r
+    catch (Throwable t) {\r
+      throw new UtilFailure(t);\r
+    }\r
+  }\r
+}\r
index 20bfd91..043dc7c 100755 (executable)
@@ -1,58 +1,89 @@
-package mir.util;
-
-import javax.servlet.http.HttpServletRequest;
-
-public class HTTPRequestParser {
-  private HttpServletRequest request;
-  private String encoding;
-
-  public HTTPRequestParser(HttpServletRequest aRequest) {
-    this(aRequest, aRequest.getCharacterEncoding());
-  }
-
-  public HTTPRequestParser(HttpServletRequest aRequest, String anEncoding) {
-    request = aRequest;
-    encoding = anEncoding;
-  }
-
-  public boolean hasParameter(String aName) {
-    return request.getParameter(aName)!=null;
-  }
-
-  public String getParameterWithDefault(String aName, String aDefault) {
-    if (hasParameter(aName))
-      return getParameter(aName);
-    else
-      return aDefault;
-  }
-
-  public String getParameter(String aName) {
-    try {
-      String result = request.getParameter(aName);
-      String requestEncoding = request.getCharacterEncoding();
-      if (requestEncoding==null)
-        requestEncoding = "ISO-8859-1";
-
-      if (result != null && encoding!=null && !encoding.equals(requestEncoding)) {
-        result = new String(result.getBytes(requestEncoding), encoding);
-      }
-
-      return result;
-    }
-    catch (Throwable t) {
-      throw new RuntimeException("HTTPRequestParser.getParameter: " + t.getMessage());
-    }
-  }
-
-  public int getIntegerWithDefault(String aName, int aDefault) {
-    int result = aDefault;
-    String value = getParameter(aName);
-
-    try {
-      result = Integer.parseInt(value);
-    }
-    catch (Throwable t) {
-    }
-    return result;
-  }
-}
\ No newline at end of file
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mir.util;\r
+\r
+import javax.servlet.http.HttpServletRequest;\r
+\r
+public class HTTPRequestParser {\r
+  private HttpServletRequest request;\r
+  private String encoding;\r
+\r
+  public HTTPRequestParser(HttpServletRequest aRequest) {\r
+    this(aRequest, aRequest.getCharacterEncoding());\r
+  }\r
+\r
+  public HTTPRequestParser(HttpServletRequest aRequest, String anEncoding) {\r
+    request = aRequest;\r
+    encoding = anEncoding;\r
+  }\r
+\r
+  public boolean hasParameter(String aName) {\r
+    return request.getParameter(aName)!=null;\r
+  }\r
+\r
+  public String getParameterWithDefault(String aName, String aDefault) {\r
+    if (hasParameter(aName))\r
+      return getParameter(aName);\r
+    else\r
+      return aDefault;\r
+  }\r
+\r
+  public String getParameter(String aName) {\r
+    try {\r
+      String result = request.getParameter(aName);\r
+      String requestEncoding = request.getCharacterEncoding();\r
+      if (requestEncoding==null)\r
+        requestEncoding = "ISO-8859-1";\r
+\r
+      if (result != null && encoding!=null && !encoding.equals(requestEncoding)) {\r
+        result = new String(result.getBytes(requestEncoding), encoding);\r
+      }\r
+\r
+      return result;\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException("HTTPRequestParser.getParameter: " + t.getMessage());\r
+    }\r
+  }\r
+\r
+  public int getIntegerWithDefault(String aName, int aDefault) {\r
+    int result = aDefault;\r
+    String value = getParameter(aName);\r
+\r
+    try {\r
+      result = Integer.parseInt(value);\r
+    }\r
+    catch (Throwable t) {\r
+    }\r
+    return result;\r
+  }\r
+}\r
index 5193daa..171e8f8 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.util;
 
 import java.util.List;
index 0e273f2..a039d10 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.util;
 
 /**
index a60a8ca..194f31b 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.util;
 
 import java.io.InputStream;
index eef1844..dcf3a2a 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.util;
 
 public class SQLQueryBuilder {
index 4c58d6a..579e921 100755 (executable)
-/*
- * Copyright (C) 2001, 2002  The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with the com.oreilly.servlet library, any library
- * licensed under the Apache Software License, The Sun (tm) Java Advanced
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of
- * the above that use the same license as the above), and distribute linked
- * combinations including the two.  You must obey the GNU General Public
- * License in all respects for all of the code used other than the above
- * mentioned libraries.  If you modify this file, you may extend this exception
- * to your version of the file, but you are not obligated to do so.  If you do
- * not wish to do so, delete this exception statement from your version.
- */
-
-package mir.util;
-
-import gnu.regexp.RE;
-import gnu.regexp.REException;
-
-import java.util.List;
-import java.util.Vector;
-
-public class StringRoutines {
-
-  private StringRoutines() {
-  }
-
-  static int indexOfCharacters(String aString, char[] aCharacters, int aFrom) {
-    int i;
-    int result=-1;
-    int position;
-
-    for (i=0; i<aCharacters.length ; i++) {
-      position = aString.indexOf(aCharacters[i], aFrom);
-
-      if (position != -1 && ( result == -1 || position < result )) {
-        result = position;
-      }
-    }
-
-    return result;
-  }
-
-  static String replaceStringCharacters(String aText, char[] aCharactersToReplace, String[] aStringsToSubstitute) {
-    if (aText==null)
-      return null;
-
-    int position, nextPosition;
-    int i;
-    StringBuffer result = new StringBuffer();
-
-    position=0;
-    do {
-      nextPosition = StringRoutines.indexOfCharacters(aText, aCharactersToReplace, position);
-
-      if (nextPosition<0)
-        nextPosition = aText.length();
-
-      result.append(aText.substring(position, nextPosition));
-
-      if (nextPosition<aText.length())
-        for (i=0; i<aCharactersToReplace.length; i++) {
-          if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {
-            result.append(aStringsToSubstitute[i]);
-            break;
-          }
-        }
-      position=nextPosition+1;
-    }
-    while (nextPosition<aText.length()) ;
-
-    return result.toString();
-  }
-
-
-  public static String interpretAsString(Object aValue) throws Exception {
-    if (aValue instanceof String)
-      return (String) aValue;
-
-    if (aValue instanceof Integer)
-      return ((Integer) aValue).toString();
-
-    if (aValue == null)
-      return "";
-
-    throw new Exception("String expected, "+aValue+" found");
-  }
-
-  public static int interpretAsInteger(Object aValue) throws Exception {
-    if (aValue instanceof Integer)
-      return ((Integer) aValue).intValue();
-
-    if (aValue instanceof String)
-      try {
-        return Integer.parseInt((String) aValue);
-      }
-      catch (Throwable t) {
-        throw new Exception("Integer expected, "+aValue+" found");
-      }
-
-    throw new Exception("Integer expected, "+aValue+" found");
-  }
-
-  /**
-   *
-   * @param aSource
-   * @param aSearchExpression
-   * @param aReplacement
-   * @return
-   * @throws Exception
-   */
-  public static String performRegularExpressionReplacement(String aSource,
-      String aSearchExpression, String aReplacement) throws Exception {
-
-    RE regularExpression;
-
-    regularExpression = new RE(aSearchExpression);
-
-    return regularExpression.substituteAll(aSource, aReplacement);
-  }
-
-  /**
-   *
-   * @param aSource
-   * @param aSearchExpression
-   * @return
-   * @throws REException
-   */
-  public static boolean performRegularExpressionSearch(String aSource,
-      String aSearchExpression) throws REException {
-    RE regularExpression;
-
-    regularExpression = new RE(aSearchExpression);
-
-    return regularExpression.isMatch(aSource);
-  }
-
-  /**
-   * Separates a string based on a separator:
-   *     <code>seperateString("a:b:c", ":");</code> will lead to
-   *     a List with 3 Strings: <code>"a"</code>, <code>"b"</code> and <code>"c"</code>
-   *
-   * @param aString     The string to split
-   * @param aSeparator
-   * @return
-   */
-
-  public static List splitString(String aString, String aSeparator) {
-    List result= new Vector();
-    int previousPosition = 0;
-    int position;
-    int endOfNamePosition;
-
-    while ((position = aString.indexOf(aSeparator, previousPosition))>=0) {
-      result.add(aString.substring(previousPosition, position));
-      previousPosition = position + aSeparator.length();
-    }
-
-    result.add(aString.substring(previousPosition, aString.length()));
-
-    return result;
-  }
-
-  /**
-   * Separates a String into at most 2 parts based on a separator:
-   * <ul>
-   *   <li>
-   *     <code>seperateString("a:b:c", ":");</code> will lead to
-   *     a List with 2 Strings: <code>"a"</code> and <code>"b:c"</code>
-   *   <li>
-   *     <code>seperateString("abc", ":");</code> will lead to
-   *     a List with a single String: <code>"abc"</code>
-   * </ul>
-   *
-   *
-   * @param aString
-   * @param aSeparator
-   * @return
-   */
-  public static List separateString(String aString, String aSeparator) {
-    List result= new Vector();
-    int previousPosition = 0;
-    int position;
-    int endOfNamePosition;
-
-    if((position = aString.indexOf(aSeparator, previousPosition))>=0) {
-      result.add(aString.substring(previousPosition, position));
-      previousPosition = position + aSeparator.length();
-    }
-
-    result.add(aString.substring(previousPosition, aString.length()));
-
-    return result;
-  }
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mir.util;\r
+\r
+import gnu.regexp.RE;\r
+import gnu.regexp.REException;\r
+\r
+import java.util.List;\r
+import java.util.Vector;\r
+\r
+public class StringRoutines {\r
+\r
+  private StringRoutines() {\r
+  }\r
+\r
+  static int indexOfCharacters(String aString, char[] aCharacters, int aFrom) {\r
+    int i;\r
+    int result=-1;\r
+    int position;\r
+\r
+    for (i=0; i<aCharacters.length ; i++) {\r
+      position = aString.indexOf(aCharacters[i], aFrom);\r
+\r
+      if (position != -1 && ( result == -1 || position < result )) {\r
+        result = position;\r
+      }\r
+    }\r
+\r
+    return result;\r
+  }\r
+\r
+  static String replaceStringCharacters(String aText, char[] aCharactersToReplace, String[] aStringsToSubstitute) {\r
+    if (aText==null)\r
+      return null;\r
+\r
+    int position, nextPosition;\r
+    int i;\r
+    StringBuffer result = new StringBuffer();\r
+\r
+    position=0;\r
+    do {\r
+      nextPosition = StringRoutines.indexOfCharacters(aText, aCharactersToReplace, position);\r
+\r
+      if (nextPosition<0)\r
+        nextPosition = aText.length();\r
+\r
+      result.append(aText.substring(position, nextPosition));\r
+\r
+      if (nextPosition<aText.length())\r
+        for (i=0; i<aCharactersToReplace.length; i++) {\r
+          if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {\r
+            result.append(aStringsToSubstitute[i]);\r
+            break;\r
+          }\r
+        }\r
+      position=nextPosition+1;\r
+    }\r
+    while (nextPosition<aText.length()) ;\r
+\r
+    return result.toString();\r
+  }\r
+\r
+\r
+  public static String interpretAsString(Object aValue) throws Exception {\r
+    if (aValue instanceof String)\r
+      return (String) aValue;\r
+\r
+    if (aValue instanceof Integer)\r
+      return ((Integer) aValue).toString();\r
+\r
+    if (aValue == null)\r
+      return "";\r
+\r
+    throw new Exception("String expected, "+aValue+" found");\r
+  }\r
+\r
+  public static int interpretAsInteger(Object aValue) throws Exception {\r
+    if (aValue instanceof Integer)\r
+      return ((Integer) aValue).intValue();\r
+\r
+    if (aValue instanceof String)\r
+      try {\r
+        return Integer.parseInt((String) aValue);\r
+      }\r
+      catch (Throwable t) {\r
+        throw new Exception("Integer expected, "+aValue+" found");\r
+      }\r
+\r
+    throw new Exception("Integer expected, "+aValue+" found");\r
+  }\r
+\r
+  /**\r
+   *\r
+   * @param aSource\r
+   * @param aSearchExpression\r
+   * @param aReplacement\r
+   * @return\r
+   * @throws Exception\r
+   */\r
+  public static String performRegularExpressionReplacement(String aSource,\r
+      String aSearchExpression, String aReplacement) throws Exception {\r
+\r
+    RE regularExpression;\r
+\r
+    regularExpression = new RE(aSearchExpression);\r
+\r
+    return regularExpression.substituteAll(aSource, aReplacement);\r
+  }\r
+\r
+  /**\r
+   *\r
+   * @param aSource\r
+   * @param aSearchExpression\r
+   * @return\r
+   * @throws REException\r
+   */\r
+  public static boolean performRegularExpressionSearch(String aSource,\r
+      String aSearchExpression) throws REException {\r
+    RE regularExpression;\r
+\r
+    regularExpression = new RE(aSearchExpression);\r
+\r
+    return regularExpression.isMatch(aSource);\r
+  }\r
+\r
+  /**\r
+   * Separates a string based on a separator:\r
+   *     <code>seperateString("a:b:c", ":");</code> will lead to\r
+   *     a List with 3 Strings: <code>"a"</code>, <code>"b"</code> and <code>"c"</code>\r
+   *\r
+   * @param aString     The string to split\r
+   * @param aSeparator\r
+   * @return\r
+   */\r
+\r
+  public static List splitString(String aString, String aSeparator) {\r
+    List result= new Vector();\r
+    int previousPosition = 0;\r
+    int position;\r
+    int endOfNamePosition;\r
+\r
+    if (aString!=null) {\r
+      while ( (position = aString.indexOf(aSeparator, previousPosition)) >= 0) {\r
+        result.add(aString.substring(previousPosition, position));\r
+        previousPosition = position + aSeparator.length();\r
+      }\r
+      result.add(aString.substring(previousPosition, aString.length()));\r
+    }\r
+\r
+    return result;\r
+  }\r
+\r
+  /**\r
+   * Separates a String into at most 2 parts based on a separator:\r
+   * <ul>\r
+   *   <li>\r
+   *     <code>seperateString("a:b:c", ":");</code> will lead to\r
+   *     a List with 2 Strings: <code>"a"</code> and <code>"b:c"</code>\r
+   *   <li>\r
+   *     <code>seperateString("abc", ":");</code> will lead to\r
+   *     a List with a single String: <code>"abc"</code>\r
+   * </ul>\r
+   *\r
+   *\r
+   * @param aString\r
+   * @param aSeparator\r
+   * @return\r
+   */\r
+  public static List separateString(String aString, String aSeparator) {\r
+    List result= new Vector();\r
+    int previousPosition = 0;\r
+    int position;\r
+    int endOfNamePosition;\r
+\r
+    if((position = aString.indexOf(aSeparator, previousPosition))>=0) {\r
+      result.add(aString.substring(previousPosition, position));\r
+      previousPosition = position + aSeparator.length();\r
+    }\r
+\r
+    result.add(aString.substring(previousPosition, aString.length()));\r
+\r
+    return result;\r
+  }\r
 }
\ No newline at end of file
index f64fb90..c36cdf9 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mir.util;
 
 import java.util.HashMap;
diff --git a/source/mir/util/UtilExc.java b/source/mir/util/UtilExc.java
new file mode 100755 (executable)
index 0000000..7810eff
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
+package mir.util;
+
+import multex.Exc;
+
+public class UtilExc extends Exc {
+  public UtilExc(String aMessage) {
+    super(aMessage);
+  }
+}
diff --git a/source/mir/util/UtilFailure.java b/source/mir/util/UtilFailure.java
new file mode 100755 (executable)
index 0000000..9990296
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
+package mir.util;
+
+import multex.Failure;
+
+public class UtilFailure extends Failure {
+
+  public UtilFailure(String aMessage, Throwable aCause) {
+    super (aMessage, aCause);
+  }
+
+  public UtilFailure(Throwable aCause) {
+    this (aCause.getMessage(), aCause);
+  }
+}
index cf8f801..0784743 100755 (executable)
@@ -1,75 +1,77 @@
-/*
- * Copyright (C) 2001, 2002  The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with the com.oreilly.servlet library, any library
- * licensed under the Apache Software License, The Sun (tm) Java Advanced
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of
- * the above that use the same license as the above), and distribute linked
- * combinations including the two.  You must obey the GNU General Public
- * License in all respects for all of the code used other than the above
- * mentioned libraries.  If you modify this file, you may extend this exception
- * to your version of the file, but you are not obligated to do so.  If you do
- * not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.entity;
-
-import mir.entity.Entity;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectExc;
-import mir.storage.StorageObjectFailure;
-import mircoders.storage.DatabaseMedia;
-/**
- * Diese Klasse enth?lt die Daten eines MetaObjekts
- *
- * @author RK
- * @version 29.6.1999
- */
-
-
-public class EntityMedia extends Entity
-{
-
-  public EntityMedia(){
-    super();
-  }
-
-  public EntityMedia(StorageObject theStorage)
-  {
-    this();
-    setStorage(theStorage);
-  }
-
-       /**
-        * fetches the MediaType entry assiciated w/ this media
-        *
-        * @return mir.entity.Entity
-        */
-       public Entity getMediaType() throws StorageObjectFailure {
-    try {
-       return ((DatabaseMedia)theStorageObject).getMediaType(this);
-    } catch (StorageObjectFailure e) {
-      throw new StorageObjectFailure("getMediaType(): ",e);
-    } catch (StorageObjectExc e) {
-      throw new StorageObjectFailure("getMediaType(): ",e);
-    }
-
-       }
-}
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.entity;\r
+\r
+import mir.entity.Entity;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectExc;\r
+import mir.storage.StorageObjectFailure;\r
+import mircoders.storage.DatabaseMedia;\r
+/**\r
+ * Diese Klasse enth?lt die Daten eines MetaObjekts\r
+ *\r
+ * @author RK\r
+ * @version 29.6.1999\r
+ */\r
+\r
+\r
+public class EntityMedia extends Entity\r
+{\r
+\r
+  public EntityMedia(){\r
+    super();\r
+  }\r
+\r
+  public EntityMedia(StorageObject theStorage)\r
+  {\r
+    this();\r
+    setStorage(theStorage);\r
+  }\r
+\r
+  /**\r
+   * fetches the MediaType entry assiciated w/ this media\r
+   *\r
+   * @return mir.entity.Entity\r
+   */\r
+  public Entity getMediaType() throws StorageObjectFailure {\r
+    try {\r
+      return ( (DatabaseMedia) theStorageObject).getMediaType(this);\r
+    }\r
+    catch (StorageObjectFailure e) {\r
+      throw new StorageObjectFailure("getMediaType(): ", e);\r
+    }\r
+    catch (StorageObjectExc e) {\r
+      throw new StorageObjectFailure("getMediaType(): ", e);\r
+    }\r
+\r
+  }\r
+}\r
index 0d2e630..b3e1855 100755 (executable)
-package mircoders.global;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Vector;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.collections.ExtendedProperties;
-
-import gnu.regexp.RE;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.util.DateToMapAdapter;
-import mir.util.InternetFunctions;
-import mir.util.StringRoutines;
-import mircoders.entity.EntityComment;
-import mircoders.entity.EntityContent;
-import mircoders.localizer.MirAdminInterfaceLocalizer;
-
-
-public class Abuse {
-  private List filters;
-  private int maxIdentifier;
-  private LoggerWrapper logger;
-  private int logSize;
-  private boolean logEnabled;
-  private boolean openPostingDisabled;
-  private boolean openPostingPassword;
-  private boolean cookieOnBlock;
-  private String articleBlockAction;
-  private String commentBlockAction;
-  private List log;
-  private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");
-
-
-  private static final String IP_FILTER_TYPE="ip";
-  private static final String REGEXP_FILTER_TYPE="regexp";
-  private static String cookieName=MirGlobal.config().getString("Abuse.CookieName");
-  private static int cookieMaxAge = 60*60*MirGlobal.config().getInt("Abuse.CookieMaxAge");
-
-  public Abuse() {
-    logger = new LoggerWrapper("Global.Abuse");
-    filters = new Vector();
-    maxIdentifier = 0;
-    log = new Vector();
-
-    logSize = 100;
-    logEnabled = false;
-    articleBlockAction = "";
-    commentBlockAction = "";
-    openPostingPassword = false;
-    openPostingDisabled = false;
-    cookieOnBlock = false;
-
-    load();
-  }
-
-  public boolean checkIpFilter(String anIpAddress) {
-    synchronized (filters) {
-      Iterator i = filters.iterator();
-
-      while (i.hasNext()) {
-        Filter filter = (Filter) i.next();
-
-        try {
-          if ( (filter.getType().equals(IP_FILTER_TYPE)) &&
-              InternetFunctions.isIpAddressInNetwork(anIpAddress, filter.getExpression())) {
-            logger.debug("ip match on " + filter.getExpression());
-            return true;
-          }
-        }
-        catch (Throwable t) {
-          logger.warn("error while checking ip address " + anIpAddress + " over network " + filter.expression + ": " + t.getMessage());
-        }
-      }
-
-      return false;
-    }
-  }
-
-  private boolean checkRegExpFilter(Entity anEntity) {
-    synchronized (filters) {
-      Iterator i = filters.iterator();
-
-      while (i.hasNext()) {
-        Filter filter = (Filter) i.next();
-
-        if (filter.getType().equals(REGEXP_FILTER_TYPE)) {
-          try {
-            RE regularExpression = new RE(filter.getExpression());
-
-            Iterator j = anEntity.getFields().iterator();
-            while (j.hasNext()) {
-              String field = anEntity.getValue( (String) j.next());
-
-              if (field != null && regularExpression.isMatch(field.toLowerCase())) {
-                logger.debug("regexp match on " + filter.getExpression());
-                return true;
-              }
-            }
-          }
-          catch (Throwable t) {
-            logger.warn("error while checking entity with regexp " + filter.getExpression() + ": " + t.getMessage());
-          }
-        }
-      }
-
-      return false;
-    }
-  }
-
-  private void setCookie(HttpServletResponse aResponse) {
-    Random random = new Random();
-
-    Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));
-    cookie.setMaxAge(cookieMaxAge);
-    cookie.setPath("/");
-    aResponse.addCookie(cookie);
-  }
-
-  private boolean checkCookie(List aCookies) {
-    if (getCookieOnBlock()) {
-      Iterator i = aCookies.iterator();
-
-      while (i.hasNext()) {
-        Cookie cookie = (Cookie) i.next();
-
-        if (cookie.getName().equals(cookieName)) {
-          logger.debug("cookie match");
-          return true;
-        }
-      }
-    }
-
-    return false;
-  }
-
-  public void checkComment(EntityComment aComment, HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    try {
-      long time = System.currentTimeMillis();
-
-      MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);
-
-      if (checkCookie(Arrays.asList(aRequest.getCookies())) || checkIpFilter(aRequest.getRemoteAddr()) || checkRegExpFilter(aComment)) {
-        operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));
-        setCookie(aResponse);
-      }
-
-      logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms");
-
-    }
-    catch (Throwable t) {
-      logger.error("Abuse.checkComment: " + t.toString());
-    }
-  }
-
-  public void checkArticle(EntityContent anArticle, HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    try {
-      long time = System.currentTimeMillis();
-
-      MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);
-
-      if (checkCookie(Arrays.asList(aRequest.getCookies())) || checkIpFilter(aRequest.getRemoteAddr()) || checkRegExpFilter(anArticle)) {
-        operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));
-        setCookie(aResponse);
-      }
-
-      logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");
-    }
-    catch (Throwable t) {
-      logger.error("Abuse.checkArticle: " + t.toString());
-    }
-  }
-
-  public boolean getLogEnabled() {
-    return logEnabled;
-  }
-
-  public void setLogEnabled(boolean anEnabled) {
-    logEnabled = anEnabled;
-    truncateLog();
-  }
-
-  public int getLogSize() {
-    return logSize;
-  }
-
-  public void setLogSize(int aSize) {
-    logSize = aSize;
-    truncateLog();
-  }
-
-  public boolean getOpenPostingDisabled() {
-    return openPostingDisabled;
-  }
-
-  public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {
-    openPostingDisabled = anOpenPostingDisabled;
-  }
-
-  public boolean getOpenPostingPassword() {
-    return openPostingPassword;
-  }
-
-  public void setOpenPostingPassword(boolean anOpenPostingPassword) {
-    openPostingPassword = anOpenPostingPassword;
-  }
-
-  public boolean getCookieOnBlock() {
-    return cookieOnBlock;
-  }
-
-  public void setCookieOnBlock(boolean aCookieOnBlock) {
-    cookieOnBlock = aCookieOnBlock;
-  }
-
-  public String getArticleBlockAction() {
-    return articleBlockAction;
-  }
-
-  public void setArticleBlockAction(String anAction) {
-    articleBlockAction = anAction;
-  }
-
-  public String getCommentBlockAction() {
-    return commentBlockAction;
-  }
-
-  public void setCommentBlockAction(String anAction) {
-    commentBlockAction = anAction;
-  }
-
-
-  public List getLog() {
-    synchronized(log) {
-      List result = new Vector();
-
-      Iterator i = log.iterator();
-      while (i.hasNext()) {
-        LogEntry logEntry = (LogEntry) i.next();
-        Map entry = new HashMap();
-
-        entry.put("ip", logEntry.getIpNumber());
-        entry.put("id", logEntry.getId());
-        entry.put("timestamp", new DateToMapAdapter(logEntry.getTimeStamp()));
-        if (logEntry.getIsArticle())
-          entry.put("type", "content");
-        else
-          entry.put("type", "comment");
-        entry.put("browser", logEntry.getBrowserString());
-
-        result.add(entry);
-      }
-
-      return result;
-    }
-  }
-
-  public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {
-    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));
-  }
-
-  public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {
-    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));
-  }
-
-  public void load() {
-    try {
-      ExtendedProperties configuration = new ExtendedProperties();
-
-      try {
-        configuration = new ExtendedProperties(configFile);
-      }
-      catch (FileNotFoundException e) {
-      }
-
-      getFilterConfig(filters, "abuse.filter", configuration);
-
-      setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));
-      setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));
-      setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));
-      setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));
-      setLogSize(configuration.getInt("abuse.logSize", 10));
-      setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));
-      setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));
-    }
-    catch (Throwable t) {
-      throw new RuntimeException(t.toString());
-    }
-  }
-  public void save() {
-    try {
-      ExtendedProperties configuration = new ExtendedProperties();
-
-      setFilterConfig(filters, "abuse.filter", configuration);
-
-      configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0");
-      configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0");
-      configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0");
-      configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0");
-      configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));
-      configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());
-      configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());
-
-      configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");
-    }
-    catch (Throwable t) {
-      throw new RuntimeException(t.toString());
-    }
-  }
-
-  public List getFilterTypes() {
-    List result = new Vector();
-
-    Map entry = new HashMap();
-    entry.put("resource", "abuse.filtertype.ip");
-    entry.put("id", IP_FILTER_TYPE);
-    result.add(entry);
-
-    entry = new HashMap();
-    entry.put("resource", "abuse.filtertype.regexp");
-    entry.put("id", REGEXP_FILTER_TYPE);
-    result.add(entry);
-
-    return result;
-  }
-
-  public List getArticleActions() {
-    try {
-      List result = new Vector();
-
-      Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
-      while (i.hasNext()) {
-        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
-            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
-
-        Map action = new HashMap();
-        action.put("resource", "content.operation."+operation.getName());
-        action.put("identifier", operation.getName());
-
-        result.add(action);
-      }
-
-      return result;
-    }
-    catch (Throwable t) {
-      throw new RuntimeException("can't get article actions");
-    }
-  }
-
-  public List getCommentActions() {
-    try {
-      List result = new Vector();
-
-      Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
-      while (i.hasNext()) {
-        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
-            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
-
-        Map action = new HashMap();
-        action.put("resource", "comment.operation."+operation.getName());
-        action.put("identifier", operation.getName());
-
-        result.add(action);
-      }
-
-      return result;
-    }
-    catch (Throwable t) {
-      throw new RuntimeException("can't get comment actions");
-    }
-  }
-
-  public List getFilters() {
-    return getFiltersAsMaps(filters);
-  }
-
-  public void addFilter(String aType, String anExpression) {
-    addFilter(filters, aType, anExpression);
-  }
-
-  public void setFilter(String anIdentifier, String aType, String anExpression) {
-    setFilter(filters, anIdentifier, aType, anExpression);
-  }
-
-  public void deleteFilter(String anIdentifier) {
-    deleteFilter(filters, anIdentifier);
-  }
-
-  public void validateIpFilter(String anIdentifier, String anArticleAction, String aCommentAction) throws Exception {
-  }
-
-  private List getFiltersAsMaps(List aFilters) {
-    synchronized(aFilters) {
-      List result = new Vector();
-
-      Iterator i = aFilters.iterator();
-      while (i.hasNext()) {
-        Filter filter = (Filter) i.next();
-        Map map = new HashMap();
-
-        map.put("id", filter.getId());
-        map.put("expression", filter.getExpression());
-        map.put("type", filter.getType());
-
-        result.add(map);
-      }
-      return result;
-    }
-  }
-
-  private void addFilter(List aFilters, String aType, String anExpression) {
-    Filter filter = new Filter();
-
-    filter.setId(generateId());
-    filter.setExpression(anExpression);
-    filter.setType(aType);
-
-    synchronized (aFilters) {
-      aFilters.add(filter);
-    }
-  }
-
-  private void setFilter(List aFilters, String anIdentifier, String aType, String anExpression) {
-    synchronized (aFilters) {
-      Filter filter = findFilter(aFilters, anIdentifier);
-
-      if (filter!=null) {
-        filter.setExpression(anExpression);
-        filter.setType(aType);
-      }
-    }
-  }
-
-  private Filter findFilter(List aFilters, String anIdentifier) {
-    synchronized (aFilters) {
-      Iterator i = aFilters.iterator();
-      while (i.hasNext()) {
-        Filter filter = (Filter) i.next();
-
-        if (filter.getId().equals(anIdentifier)) {
-          return filter;
-        }
-      }
-    }
-
-    return null;
-  }
-
-  private void deleteFilter(List aFilters, String anIdentifier) {
-    synchronized (aFilters) {
-      Filter filter = findFilter(aFilters, anIdentifier);
-
-      if (filter!=null) {
-        aFilters.remove(filter);
-      }
-    }
-  }
-
-  private String generateId() {
-    synchronized(this) {
-      maxIdentifier = maxIdentifier+1;
-
-      return Integer.toString(maxIdentifier);
-    }
-  }
-
-  private static class Filter {
-    private String identifier;
-    private String expression;
-    private String type;
-
-    public Filter() {
-      expression="";
-      type="";
-      identifier="";
-    }
-
-    public String getId() {
-      return identifier;
-    }
-
-    public void setId(String anId) {
-      identifier = anId;
-    }
-
-    public String getExpression() {
-      return expression;
-    }
-
-    public void setExpression(String anExpression) {
-      expression = anExpression;
-    }
-
-    public String getType() {
-      return type;
-    }
-
-    public void setType(String aType) {
-      type = aType;
-    }
-  }
-
-  private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
-    synchronized(aFilters) {
-      Iterator i = aFilters.iterator();
-
-      while (i.hasNext()) {
-        Filter filter = (Filter) i.next();
-
-        aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression());
-      }
-    }
-  }
-
-  private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
-    synchronized(aFilters) {
-      aFilters.clear();
-
-      Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).iterator();
-
-      while (i.hasNext()) {
-        String filter = (String) i.next();
-        List parts = StringRoutines.separateString(filter, ":");
-
-        if (parts.size()==2) {
-          addFilter( (String) parts.get(0), (String) parts.get(1));
-        }
-      }
-    }
-  }
-
-  private static class LogEntry {
-    private String ipNumber;
-    private String browserString;
-    private String id;
-    private Date timeStamp;
-    private boolean isArticle;
-
-    public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
-      ipNumber = anIpNumber;
-      browserString = aBrowserString;
-      id = anId;
-      isArticle = anIsArticle;
-      timeStamp=aTimeStamp;
-    }
-
-    public String getIpNumber() {
-      return ipNumber;
-    }
-
-    public String getBrowserString() {
-      return browserString;
-    }
-
-    public String getId() {
-      return id;
-    }
-
-    public Date getTimeStamp() {
-      return timeStamp;
-    }
-
-    public boolean getIsArticle() {
-      return isArticle;
-    }
-  }
-
-  private void truncateLog() {
-    synchronized(log) {
-      if (!logEnabled)
-        log.clear();
-      else {
-        while (log.size()>0 && log.size()>logSize) {
-          log.remove(0);
-        }
-      }
-    }
-  };
-
-  private void appendLog(LogEntry anEntry) {
-    synchronized (log) {
-      if (logEnabled) {
-        log.add(anEntry);
-        truncateLog();
-      }
-    }
-  }
-
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.global;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
+import java.util.Arrays;\r
+import java.util.Date;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Random;\r
+import java.util.Vector;\r
+import javax.servlet.http.Cookie;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import org.apache.commons.collections.ExtendedProperties;\r
+\r
+import gnu.regexp.RE;\r
+\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.util.DateToMapAdapter;\r
+import mir.util.InternetFunctions;\r
+import mir.util.StringRoutines;\r
+import mir.session.*;\r
+import mircoders.entity.EntityComment;\r
+import mircoders.entity.EntityContent;\r
+import mircoders.localizer.MirAdminInterfaceLocalizer;\r
+\r
+\r
+public class Abuse {\r
+  private List filters;\r
+  private int maxIdentifier;\r
+  private LoggerWrapper logger;\r
+  private int logSize;\r
+  private boolean logEnabled;\r
+  private boolean openPostingDisabled;\r
+  private boolean openPostingPassword;\r
+  private boolean cookieOnBlock;\r
+  private String articleBlockAction;\r
+  private String commentBlockAction;\r
+  private List log;\r
+  private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");\r
+\r
+\r
+  private static final String IP_FILTER_TYPE="ip";\r
+  private static final String REGEXP_FILTER_TYPE="regexp";\r
+  private static String cookieName=MirGlobal.config().getString("Abuse.CookieName");\r
+  private static int cookieMaxAge = 60*60*MirGlobal.config().getInt("Abuse.CookieMaxAge");\r
+\r
+  public Abuse() {\r
+    logger = new LoggerWrapper("Global.Abuse");\r
+    filters = new Vector();\r
+    maxIdentifier = 0;\r
+    log = new Vector();\r
+\r
+    logSize = 100;\r
+    logEnabled = false;\r
+    articleBlockAction = "";\r
+    commentBlockAction = "";\r
+    openPostingPassword = false;\r
+    openPostingDisabled = false;\r
+    cookieOnBlock = false;\r
+\r
+    load();\r
+  }\r
+\r
+  public boolean checkIpFilter(String anIpAddress) {\r
+    synchronized (filters) {\r
+      Iterator i = filters.iterator();\r
+\r
+      while (i.hasNext()) {\r
+        Filter filter = (Filter) i.next();\r
+\r
+        try {\r
+          if ( (filter.getType().equals(IP_FILTER_TYPE)) &&\r
+              InternetFunctions.isIpAddressInNetwork(anIpAddress, filter.getExpression())) {\r
+            logger.debug("ip match on " + filter.getExpression());\r
+            return true;\r
+          }\r
+        }\r
+        catch (Throwable t) {\r
+          logger.warn("error while checking ip address " + anIpAddress + " over network " + filter.expression + ": " + t.getMessage());\r
+        }\r
+      }\r
+\r
+      return false;\r
+    }\r
+  }\r
+\r
+  private boolean checkRegExpFilter(Entity anEntity) {\r
+    synchronized (filters) {\r
+      Iterator i = filters.iterator();\r
+\r
+      while (i.hasNext()) {\r
+        Filter filter = (Filter) i.next();\r
+\r
+        if (filter.getType().equals(REGEXP_FILTER_TYPE)) {\r
+          try {\r
+            RE regularExpression = new RE(filter.getExpression());\r
+\r
+            Iterator j = anEntity.getFields().iterator();\r
+            while (j.hasNext()) {\r
+              String field = anEntity.getValue( (String) j.next());\r
+\r
+              if (field != null && regularExpression.isMatch(field.toLowerCase())) {\r
+                logger.debug("regexp match on " + filter.getExpression());\r
+                return true;\r
+              }\r
+            }\r
+          }\r
+          catch (Throwable t) {\r
+            logger.warn("error while checking entity with regexp " + filter.getExpression() + ": " + t.getMessage());\r
+          }\r
+        }\r
+      }\r
+\r
+      return false;\r
+    }\r
+  }\r
+\r
+  private void setCookie(HttpServletResponse aResponse) {\r
+    Random random = new Random();\r
+\r
+    Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));\r
+    cookie.setMaxAge(cookieMaxAge);\r
+    cookie.setPath("/");\r
+\r
+    if (aResponse!=null)\r
+      aResponse.addCookie(cookie);\r
+  }\r
+\r
+  private boolean checkCookie(List aCookies) {\r
+    if (getCookieOnBlock()) {\r
+      Iterator i = aCookies.iterator();\r
+\r
+      while (i.hasNext()) {\r
+        Cookie cookie = (Cookie) i.next();\r
+\r
+        if (cookie.getName().equals(cookieName)) {\r
+          logger.debug("cookie match");\r
+          return true;\r
+        }\r
+      }\r
+    }\r
+\r
+    return false;\r
+  }\r
+\r
+  public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {\r
+    try {\r
+      long time = System.currentTimeMillis();\r
+      String address = "0.0.0.0";\r
+      String browser = "unknown";\r
+      Cookie[] cookies = {};\r
+\r
+      HttpServletRequest request = null;\r
+\r
+      if (aRequest instanceof HTTPAdapters.HTTPParsedRequestAdapter) {\r
+        request = ((HTTPAdapters.HTTPParsedRequestAdapter) aRequest).getRequest();\r
+      }\r
+      else if (aRequest instanceof HTTPAdapters.HTTPRequestAdapter) {\r
+        request = ((HTTPAdapters.HTTPRequestAdapter) aRequest).getRequest();\r
+      }\r
+      if (request!=null) {\r
+        browser = (String) request.getHeader("User-Agent");\r
+        address = request.getRemoteAddr();\r
+        cookies = request.getCookies();\r
+      }\r
+\r
+      logComment(address, aComment.getId(), new Date(), browser);\r
+\r
+      MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);\r
+\r
+      if (checkCookie(Arrays.asList(cookies)) || checkIpFilter(address) || checkRegExpFilter(aComment)) {\r
+        operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));\r
+        setCookie(aResponse);\r
+      }\r
+\r
+      logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms");\r
+    }\r
+    catch (Throwable t) {\r
+      logger.error("Abuse.checkComment: " + t.toString());\r
+    }\r
+  }\r
+\r
+  public void checkArticle(EntityContent anArticle, HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    try {\r
+      long time = System.currentTimeMillis();\r
+\r
+      logArticle(aRequest.getRemoteAddr(), anArticle.getId(), new Date(), (String) aRequest.getHeader("User-Agent"));\r
+\r
+      MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);\r
+\r
+      if (checkCookie(Arrays.asList(aRequest.getCookies())) || checkIpFilter(aRequest.getRemoteAddr()) || checkRegExpFilter(anArticle)) {\r
+        operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));\r
+        setCookie(aResponse);\r
+      }\r
+\r
+      logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");\r
+    }\r
+    catch (Throwable t) {\r
+      logger.error("Abuse.checkArticle: " + t.toString());\r
+    }\r
+  }\r
+\r
+  public boolean getLogEnabled() {\r
+    return logEnabled;\r
+  }\r
+\r
+  public void setLogEnabled(boolean anEnabled) {\r
+    logEnabled = anEnabled;\r
+    truncateLog();\r
+  }\r
+\r
+  public int getLogSize() {\r
+    return logSize;\r
+  }\r
+\r
+  public void setLogSize(int aSize) {\r
+    logSize = aSize;\r
+    truncateLog();\r
+  }\r
+\r
+  public boolean getOpenPostingDisabled() {\r
+    return openPostingDisabled;\r
+  }\r
+\r
+  public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {\r
+    openPostingDisabled = anOpenPostingDisabled;\r
+  }\r
+\r
+  public boolean getOpenPostingPassword() {\r
+    return openPostingPassword;\r
+  }\r
+\r
+  public void setOpenPostingPassword(boolean anOpenPostingPassword) {\r
+    openPostingPassword = anOpenPostingPassword;\r
+  }\r
+\r
+  public boolean getCookieOnBlock() {\r
+    return cookieOnBlock;\r
+  }\r
+\r
+  public void setCookieOnBlock(boolean aCookieOnBlock) {\r
+    cookieOnBlock = aCookieOnBlock;\r
+  }\r
+\r
+  public String getArticleBlockAction() {\r
+    return articleBlockAction;\r
+  }\r
+\r
+  public void setArticleBlockAction(String anAction) {\r
+    articleBlockAction = anAction;\r
+  }\r
+\r
+  public String getCommentBlockAction() {\r
+    return commentBlockAction;\r
+  }\r
+\r
+  public void setCommentBlockAction(String anAction) {\r
+    commentBlockAction = anAction;\r
+  }\r
+\r
+\r
+  public List getLog() {\r
+    synchronized(log) {\r
+      List result = new Vector();\r
+\r
+      Iterator i = log.iterator();\r
+      while (i.hasNext()) {\r
+        LogEntry logEntry = (LogEntry) i.next();\r
+        Map entry = new HashMap();\r
+\r
+        entry.put("ip", logEntry.getIpNumber());\r
+        entry.put("id", logEntry.getId());\r
+        entry.put("timestamp", new DateToMapAdapter(logEntry.getTimeStamp()));\r
+        if (logEntry.getIsArticle())\r
+          entry.put("type", "content");\r
+        else\r
+          entry.put("type", "comment");\r
+        entry.put("browser", logEntry.getBrowserString());\r
+\r
+        result.add(entry);\r
+      }\r
+\r
+      return result;\r
+    }\r
+  }\r
+\r
+  public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {\r
+    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));\r
+  }\r
+\r
+  public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {\r
+    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));\r
+  }\r
+\r
+  public void load() {\r
+    try {\r
+      ExtendedProperties configuration = new ExtendedProperties();\r
+\r
+      try {\r
+        configuration = new ExtendedProperties(configFile);\r
+      }\r
+      catch (FileNotFoundException e) {\r
+      }\r
+\r
+      getFilterConfig(filters, "abuse.filter", configuration);\r
+\r
+      setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));\r
+      setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));\r
+      setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));\r
+      setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));\r
+      setLogSize(configuration.getInt("abuse.logSize", 10));\r
+      setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));\r
+      setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException(t.toString());\r
+    }\r
+  }\r
+  public void save() {\r
+    try {\r
+      ExtendedProperties configuration = new ExtendedProperties();\r
+\r
+      setFilterConfig(filters, "abuse.filter", configuration);\r
+\r
+      configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0");\r
+      configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0");\r
+      configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0");\r
+      configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0");\r
+      configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));\r
+      configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());\r
+      configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());\r
+\r
+      configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException(t.toString());\r
+    }\r
+  }\r
+\r
+  public List getFilterTypes() {\r
+    List result = new Vector();\r
+\r
+    Map entry = new HashMap();\r
+    entry.put("resource", "ip");\r
+    entry.put("id", IP_FILTER_TYPE);\r
+    result.add(entry);\r
+\r
+    entry = new HashMap();\r
+    entry.put("resource", "regexp");\r
+    entry.put("id", REGEXP_FILTER_TYPE);\r
+    result.add(entry);\r
+\r
+    return result;\r
+  }\r
+\r
+  public List getArticleActions() {\r
+    try {\r
+      List result = new Vector();\r
+\r
+      Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();\r
+      while (i.hasNext()) {\r
+        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
+            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
+\r
+        Map action = new HashMap();\r
+        action.put("resource", operation.getName());\r
+        action.put("identifier", operation.getName());\r
+\r
+        result.add(action);\r
+      }\r
+\r
+      return result;\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException("can't get article actions");\r
+    }\r
+  }\r
+\r
+  public List getCommentActions() {\r
+    try {\r
+      List result = new Vector();\r
+\r
+      Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();\r
+      while (i.hasNext()) {\r
+        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
+            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
+\r
+        Map action = new HashMap();\r
+        action.put("resource", operation.getName());\r
+        action.put("identifier", operation.getName());\r
+\r
+        result.add(action);\r
+      }\r
+\r
+      return result;\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException("can't get comment actions");\r
+    }\r
+  }\r
+\r
+  public List getFilters() {\r
+    return getFiltersAsMaps(filters);\r
+  }\r
+\r
+  public void addFilter(String aType, String anExpression) {\r
+    addFilter(filters, aType, anExpression);\r
+  }\r
+\r
+  public void setFilter(String anIdentifier, String aType, String anExpression) {\r
+    setFilter(filters, anIdentifier, aType, anExpression);\r
+  }\r
+\r
+  public void deleteFilter(String anIdentifier) {\r
+    deleteFilter(filters, anIdentifier);\r
+  }\r
+\r
+  public void validateIpFilter(String anIdentifier, String anArticleAction, String aCommentAction) throws Exception {\r
+  }\r
+\r
+  private List getFiltersAsMaps(List aFilters) {\r
+    synchronized(aFilters) {\r
+      List result = new Vector();\r
+\r
+      Iterator i = aFilters.iterator();\r
+      while (i.hasNext()) {\r
+        Filter filter = (Filter) i.next();\r
+        Map map = new HashMap();\r
+\r
+        map.put("id", filter.getId());\r
+        map.put("expression", filter.getExpression());\r
+        map.put("type", filter.getType());\r
+\r
+        result.add(map);\r
+      }\r
+      return result;\r
+    }\r
+  }\r
+\r
+  private void addFilter(List aFilters, String aType, String anExpression) {\r
+    Filter filter = new Filter();\r
+\r
+    filter.setId(generateId());\r
+    filter.setExpression(anExpression);\r
+    filter.setType(aType);\r
+\r
+    synchronized (aFilters) {\r
+      aFilters.add(filter);\r
+    }\r
+  }\r
+\r
+  private void setFilter(List aFilters, String anIdentifier, String aType, String anExpression) {\r
+    synchronized (aFilters) {\r
+      Filter filter = findFilter(aFilters, anIdentifier);\r
+\r
+      if (filter!=null) {\r
+        filter.setExpression(anExpression);\r
+        filter.setType(aType);\r
+      }\r
+    }\r
+  }\r
+\r
+  private Filter findFilter(List aFilters, String anIdentifier) {\r
+    synchronized (aFilters) {\r
+      Iterator i = aFilters.iterator();\r
+      while (i.hasNext()) {\r
+        Filter filter = (Filter) i.next();\r
+\r
+        if (filter.getId().equals(anIdentifier)) {\r
+          return filter;\r
+        }\r
+      }\r
+    }\r
+\r
+    return null;\r
+  }\r
+\r
+  private void deleteFilter(List aFilters, String anIdentifier) {\r
+    synchronized (aFilters) {\r
+      Filter filter = findFilter(aFilters, anIdentifier);\r
+\r
+      if (filter!=null) {\r
+        aFilters.remove(filter);\r
+      }\r
+    }\r
+  }\r
+\r
+  private String generateId() {\r
+    synchronized(this) {\r
+      maxIdentifier = maxIdentifier+1;\r
+\r
+      return Integer.toString(maxIdentifier);\r
+    }\r
+  }\r
+\r
+  private static class Filter {\r
+    private String identifier;\r
+    private String expression;\r
+    private String type;\r
+\r
+    public Filter() {\r
+      expression="";\r
+      type="";\r
+      identifier="";\r
+    }\r
+\r
+    public String getId() {\r
+      return identifier;\r
+    }\r
+\r
+    public void setId(String anId) {\r
+      identifier = anId;\r
+    }\r
+\r
+    public String getExpression() {\r
+      return expression;\r
+    }\r
+\r
+    public void setExpression(String anExpression) {\r
+      expression = anExpression;\r
+    }\r
+\r
+    public String getType() {\r
+      return type;\r
+    }\r
+\r
+    public void setType(String aType) {\r
+      type = aType;\r
+    }\r
+  }\r
+\r
+  private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {\r
+    synchronized(aFilters) {\r
+      Iterator i = aFilters.iterator();\r
+\r
+      while (i.hasNext()) {\r
+        Filter filter = (Filter) i.next();\r
+\r
+        aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression());\r
+      }\r
+    }\r
+  }\r
+\r
+  private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {\r
+    synchronized(aFilters) {\r
+      aFilters.clear();\r
+\r
+      Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).iterator();\r
+\r
+      while (i.hasNext()) {\r
+        String filter = (String) i.next();\r
+        List parts = StringRoutines.separateString(filter, ":");\r
+\r
+        if (parts.size()==2) {\r
+          addFilter( (String) parts.get(0), (String) parts.get(1));\r
+        }\r
+      }\r
+    }\r
+  }\r
+\r
+  private static class LogEntry {\r
+    private String ipNumber;\r
+    private String browserString;\r
+    private String id;\r
+    private Date timeStamp;\r
+    private boolean isArticle;\r
+\r
+    public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {\r
+      ipNumber = anIpNumber;\r
+      browserString = aBrowserString;\r
+      id = anId;\r
+      isArticle = anIsArticle;\r
+      timeStamp=aTimeStamp;\r
+    }\r
+\r
+    public String getIpNumber() {\r
+      return ipNumber;\r
+    }\r
+\r
+    public String getBrowserString() {\r
+      return browserString;\r
+    }\r
+\r
+    public String getId() {\r
+      return id;\r
+    }\r
+\r
+    public Date getTimeStamp() {\r
+      return timeStamp;\r
+    }\r
+\r
+    public boolean getIsArticle() {\r
+      return isArticle;\r
+    }\r
+  }\r
+\r
+  private void truncateLog() {\r
+    synchronized(log) {\r
+      if (!logEnabled)\r
+        log.clear();\r
+      else {\r
+        while (log.size()>0 && log.size()>logSize) {\r
+          log.remove(0);\r
+        }\r
+      }\r
+    }\r
+  };\r
+\r
+  private void appendLog(LogEntry anEntry) {\r
+    synchronized (log) {\r
+      if (logEnabled) {\r
+        log.add(anEntry);\r
+        truncateLog();\r
+      }\r
+    }\r
+  }\r
+\r
 }
\ No newline at end of file
index 4d487ae..8e3cf15 100755 (executable)
@@ -38,5 +38,4 @@ public interface MirLocalizer {
   public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc;
   public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc;
   public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc;
-
 }
\ No newline at end of file
index 4960162..b323275 100755 (executable)
@@ -1,44 +1,81 @@
-/*
- * Copyright (C) 2001, 2002  The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with the com.oreilly.servlet library, any library
- * licensed under the Apache Software License, The Sun (tm) Java Advanced
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of
- * the above that use the same license as the above), and distribute linked
- * combinations including the two.  You must obey the GNU General Public
- * License in all respects for all of the code used other than the above
- * mentioned libraries.  If you modify this file, you may extend this exception
- * to your version of the file, but you are not obligated to do so.  If you do
- * not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.localizer;
-
-import javax.servlet.http.HttpServletRequest;
-
-import mircoders.entity.EntityComment;
-import mircoders.entity.EntityContent;
-
-public interface MirOpenPostingLocalizer {
-  public void afterContentPosting(EntityContent aContent);
-  public void afterCommentPosting(EntityComment aComment);
-
-  public String chooseOpenPostingLanguage(HttpServletRequest req);
-}
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.localizer;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+\r
+import mir.session.Request;\r
+import mir.session.Response;\r
+import mir.session.*;\r
+import mircoders.entity.EntityComment;\r
+import mircoders.entity.EntityContent;\r
+\r
+public interface MirOpenPostingLocalizer {\r
+\r
+  /**\r
+   * Class to encapsulate a validation error\r
+   *\r
+   * <p>Title: </p>\r
+   * <p>Description: </p>\r
+   * <p>Copyright: Copyright (c) 2003</p>\r
+   * <p>Company: </p>\r
+   * @author not attributable\r
+   * @version 1.0\r
+   */\r
+\r
+  /**\r
+   *\r
+   * @param aRequest\r
+   * @param aSession\r
+   * @return\r
+   * @throws MirLocalizerExc\r
+   * @throws MirLocalizerFailure\r
+   */\r
+  public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure;\r
+\r
+  /**\r
+   *\r
+   * @param aComment\r
+   * @throws MirLocalizerExc\r
+   * @throws MirLocalizerFailure\r
+   */\r
+  public void afterCommentPosting(EntityComment aComment) throws MirLocalizerExc, MirLocalizerFailure;\r
+\r
+  /**\r
+   *\r
+   * @param aContent\r
+   * @throws MirLocalizerExc\r
+   * @throws MirLocalizerFailure\r
+   */\r
+  public void afterContentPosting(EntityContent aContent) throws MirLocalizerExc, MirLocalizerFailure;\r
+}\r
diff --git a/source/mircoders/localizer/basic/MirBasicCommentPostingSessionHandler.java b/source/mircoders/localizer/basic/MirBasicCommentPostingSessionHandler.java
new file mode 100755 (executable)
index 0000000..bf219f8
--- /dev/null
@@ -0,0 +1,307 @@
+package mircoders.localizer.basic;\r
+\r
+import java.util.*;\r
+import mir.log.LoggerWrapper;\r
+import mir.session.*;\r
+import mir.config.*;\r
+import mir.util.*;\r
+import mir.entity.*;\r
+import mircoders.storage.*;\r
+import mircoders.global.*;\r
+import mircoders.localizer.*;\r
+import mircoders.entity.*;\r
+import mircoders.module.*;\r
+import mircoders.media.*;\r
+\r
+/**\r
+ *\r
+ * <p>Title: Experimental session handler for comment postings </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+\r
+public class MirBasicCommentPostingSessionHandler implements SessionHandler {\r
+  protected LoggerWrapper logger;\r
+  protected MirPropertiesConfiguration configuration;\r
+  protected boolean initialRequest;\r
+  protected ModuleComment commentModule;\r
+  protected DatabaseCommentToMedia commentToMedia = DatabaseCommentToMedia.getInstance();\r
+\r
+  public MirBasicCommentPostingSessionHandler() {\r
+    logger = new LoggerWrapper("Localizer.OpenPosting.Comment");\r
+    try {\r
+      configuration = MirPropertiesConfiguration.instance();\r
+    }\r
+    catch (Throwable t) {\r
+      logger.fatal("Cannont load configuration: " + t.toString());\r
+\r
+      throw new RuntimeException("Cannont load configuration: " + t.toString());\r
+    }\r
+    initialRequest= true;\r
+    commentModule= new ModuleComment(DatabaseComment.getInstance());\r
+  }\r
+\r
+  public void processRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
+    if (aSession.getAttribute("initialRequest")==null) {\r
+      initialRequest(aRequest, aSession, aResponse);\r
+      aSession.setAttribute("initialRequest", "no");\r
+    }\r
+    else {\r
+      subsequentRequest(aRequest, aSession, aResponse);\r
+    }\r
+  };\r
+\r
+  public String generateOnetimePassword() {\r
+    Random r = new Random();\r
+    int random = r.nextInt();\r
+\r
+    long l = System.currentTimeMillis();\r
+\r
+    l = (l*l*l*l)/random;\r
+    if (l<0)\r
+      l = l * -1;\r
+\r
+    String returnString = ""+l;\r
+\r
+    return returnString.substring(5);\r
+  }\r
+\r
+  public void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
+    if (MirGlobal.abuse().getOpenPostingPassword()) {\r
+      String password = (String) aSession.getAttribute("password");\r
+      if (password==null) {\r
+        password = generateOnetimePassword();\r
+        aSession.setAttribute("password", password);\r
+      }\r
+      aResponse.setResponseValue("password", password);\r
+    }\r
+    else {\r
+      aResponse.setResponseValue("password", null);\r
+      aSession.deleteAttribute("password");\r
+    }\r
+\r
+    aResponse.setResponseValue("errors", null);\r
+  };\r
+\r
+  public void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure{\r
+    Iterator i = DatabaseContent.getInstance().getFields().iterator();\r
+    while (i.hasNext()) {\r
+      aResponse.setResponseValue( (String) i.next(), null);\r
+    }\r
+\r
+    String articleId = aRequest.getParameter("to_media");\r
+\r
+    if (articleId == null)\r
+      throw new SessionExc("MirBasicCommentPostingSessionHandler.initialRequest: article id not set!");\r
+\r
+    aSession.setAttribute("to_media", articleId);\r
+\r
+    initializeResponseData(aRequest, aSession, aResponse);\r
+\r
+    try {\r
+      aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate"));\r
+    }\r
+    catch (Throwable e) {\r
+      throw new SessionFailure("Can't get configuration: " + e.getMessage(), e);\r
+    }\r
+\r
+  }\r
+\r
+  public boolean testFieldExists(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {\r
+    Object value = aRequest.getParameter(aFieldName);\r
+    if (value==null || !(value instanceof String) || ((String) value).trim().length()==0) {\r
+      logger.debug("  missing field " + aFieldName + " value = " + value);\r
+      aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));\r
+      return false;\r
+    }\r
+    else\r
+      return true;\r
+  }\r
+\r
+  public boolean testFieldIsNumeric(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {\r
+    Object value = aRequest.getParameter(aFieldName);\r
+    if (value!=null) {\r
+      try {\r
+        Integer.parseInt((String) value);\r
+        return true;\r
+      }\r
+      catch (Throwable t) {\r
+        logger.debug("  field not numeric: " + aFieldName + " value = " + value);\r
+        aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));\r
+        return false;\r
+      }\r
+    }\r
+    return true;\r
+  }\r
+\r
+\r
+  public List validate(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
+    List result = new Vector();\r
+\r
+    testFieldExists(aRequest, "title", "validationerror.missing", result);\r
+    testFieldExists(aRequest, "description", "validationerror.missing", result);\r
+    testFieldExists(aRequest, "creator", "validationerror.missing", result);\r
+\r
+    return result;\r
+  }\r
+\r
+  public void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
+    try {\r
+      Map commentFields = new HashMap();\r
+\r
+      Iterator i = DatabaseContent.getInstance().getFields().iterator();\r
+      while (i.hasNext()) {\r
+        String field = (String) i.next();\r
+        aResponse.setResponseValue(field, aRequest.getParameter(field));\r
+        if (aRequest.getParameter(field)!=null) {\r
+          commentFields.put(field, aRequest.getParameter(field));\r
+        }\r
+      }\r
+\r
+      initializeResponseData(aRequest, aSession, aResponse);\r
+\r
+      List validationErrors = validate(aRequest, aSession);\r
+\r
+      if (validationErrors != null && validationErrors.size()>0) {\r
+        returnValidationErrors(aRequest, aSession, aResponse, validationErrors);\r
+      }\r
+      else {\r
+        EntityComment comment = (EntityComment) commentModule.createNew ();\r
+        comment.setValues(commentFields);\r
+\r
+        finishComment(aRequest, aSession, comment);\r
+\r
+        String id = comment.insert();\r
+        if(id==null){\r
+          afterDuplicateCommentPosting(aRequest, aSession, aResponse, comment);\r
+          logger.info("Dupe comment rejected");\r
+          aSession.terminate();\r
+        }\r
+        else {\r
+          i = aRequest.getUploadedFiles().iterator();\r
+          while (i.hasNext()) {\r
+            UploadedFile file = (UploadedFile) i.next();\r
+            processMediaFile(aRequest, aSession, comment, file);\r
+          }\r
+\r
+          afterCommentPosting(aRequest, aSession, aResponse, comment);\r
+          MirGlobal.abuse().checkComment(comment, aRequest, null);\r
+          MirGlobal.localizer().openPostings().afterCommentPosting(comment);\r
+          logger.info("Comment posted");\r
+          aSession.terminate();\r
+        }\r
+      }\r
+    }\r
+    catch (Throwable t) {\r
+      ExceptionFunctions.traceCauseException(t).printStackTrace();\r
+\r
+      throw new SessionFailure("MirBasicCommentPostingSessionHandler.subsequentRequest: " + t.getMessage(), t);\r
+    }\r
+  }\r
+\r
+  public void initializeCommentPosting(Request aRequest, Session aSession, Response aResponse) throws SessionFailure, SessionExc {\r
+    String articleId = aRequest.getParameter("to_media");\r
+    if (articleId==null)\r
+      articleId = aRequest.getParameter("aid");\r
+\r
+    if (articleId==null)\r
+      throw new SessionExc("initializeCommentPosting: article id not set!");\r
+\r
+    aSession.setAttribute("to_media", articleId);\r
+    processCommentPosting(aRequest, aSession, aResponse);\r
+  };\r
+\r
+  public void returnValidationErrors(Request aRequest, Session aSession, Response aResponse, List aValidationErrors) throws SessionFailure, SessionExc {\r
+    aResponse.setResponseValue("errors", aValidationErrors);\r
+    aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate"));\r
+  };\r
+\r
+  public void processCommentPosting(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
+    if (MirGlobal.abuse().getOpenPostingPassword()) {\r
+      String password = generateOnetimePassword();\r
+      aSession.setAttribute("password", password);\r
+      aResponse.setResponseValue("password", password);\r
+      aResponse.setResponseValue("passwd", password);\r
+    }\r
+    else {\r
+      aResponse.setResponseValue("password", null);\r
+    }\r
+\r
+    aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate"));\r
+  };\r
+\r
+  public void processMediaFile(Request aRequest, Session aSession, EntityComment aComment, UploadedFile aFile) throws SessionExc, SessionFailure {\r
+    try {\r
+      Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile);\r
+      finishMedia(aRequest, aSession, aFile, mediaItem);\r
+      mediaItem.update();\r
+      commentToMedia.addMedia(aComment.getId(), mediaItem.getId());\r
+    }\r
+    catch (Throwable t) {\r
+      throw new SessionFailure(t);\r
+    }\r
+  }\r
+\r
+  public void finishMedia(Request aRequest, Session aSession, UploadedFile aFile, Entity aMedia) throws SessionExc, SessionFailure {\r
+  }\r
+\r
+  public void finishComment(Request aRequest, Session aSession, EntityComment aComment) throws SessionExc, SessionFailure {\r
+    if (aSession.getAttribute("to_media") == null)\r
+      throw new SessionExc("missing to_media");\r
+\r
+    aComment.setValueForProperty("is_published", "1");\r
+    aComment.setValueForProperty("to_comment_status", "1");\r
+    aComment.setValueForProperty("is_html","0");\r
+    aComment.setValueForProperty("to_media", (String) aSession.getAttribute("to_media"));\r
+  };\r
+\r
+  public void addMedia(Request aRequest, Session aSession, EntityComment aComment)  throws SessionExc, SessionFailure {\r
+  }\r
+\r
+  public void afterCommentPosting(Request aRequest, Session aSession, Response aResponse, EntityComment aComment) {\r
+    DatabaseContent.getInstance().setUnproduced("id=" + aComment.getValue("to_media"));\r
+    aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.DoneTemplate"));\r
+  };\r
+\r
+  public void afterDuplicateCommentPosting(Request aRequest, Session aSession, Response aResponse, EntityComment aComment) {\r
+    aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.DupeTemplate"));\r
+  };\r
+\r
+  public class ValidationError {\r
+    private String field;\r
+    private String message;\r
+    private List parameters;\r
+\r
+    public ValidationError(String aField, String aMessage) {\r
+      this (aField, aMessage, new String[] {});\r
+    }\r
+\r
+    public ValidationError(String aField, String aMessage, Object aParameter) {\r
+      this (aField, aMessage, new Object[] {aParameter});\r
+    }\r
+\r
+    public ValidationError(String aField, String aMessage, Object[] aParameters) {\r
+      field = aField;\r
+      message = aMessage;\r
+      parameters = Arrays.asList(aParameters);\r
+    }\r
+\r
+    public String getMessage() {\r
+      return message;\r
+    }\r
+\r
+    public String getField() {\r
+      return field;\r
+    }\r
+\r
+    public List getParameters() {\r
+      return parameters;\r
+    }\r
+  }\r
+\r
+\r
+\r
+}
\ No newline at end of file
index 3dfb79a..06823a1 100755 (executable)
@@ -47,11 +47,11 @@ public class MirBasicLocalizer implements MirLocalizer {
     return new MirBasicProducerLocalizer();
   }
 
-  public MirGeneratorLocalizer generators() {
+  public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc {
     return new MirBasicGeneratorLocalizer();
   }
 
-  public MirOpenPostingLocalizer openPostings() {
+  public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure, MirLocalizerExc {
     return new MirBasicOpenPostingLocalizer();
   }
 
@@ -59,7 +59,7 @@ public class MirBasicLocalizer implements MirLocalizer {
     return new MirBasicProducerAssistantLocalizer();
   }
 
-  public MirDataModelLocalizer dataModel() {
+  public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc {
     return new MirBasicDataModelLocalizer();
   };
 
index ad7dae9..f4b5d5c 100755 (executable)
-/*
- * Copyright (C) 2001, 2002  The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with the com.oreilly.servlet library, any library
- * licensed under the Apache Software License, The Sun (tm) Java Advanced
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of
- * the above that use the same license as the above), and distribute linked
- * combinations including the two.  You must obey the GNU General Public
- * License in all respects for all of the code used other than the above
- * mentioned libraries.  If you modify this file, you may extend this exception
- * to your version of the file, but you are not obligated to do so.  If you do
- * not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.localizer.basic;
-
-import java.util.List;
-import java.util.Locale;
-
-import javax.servlet.http.HttpServletRequest;
-
-import mir.log.LoggerWrapper;
-import mircoders.entity.EntityComment;
-import mircoders.entity.EntityContent;
-import mircoders.global.MirGlobal;
-import mircoders.global.ProducerEngine;
-import mircoders.localizer.MirOpenPostingLocalizer;
-
-public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer {
-  private List afterContentProducerTasks;
-  private List afterCommentProducerTasks;
-  protected LoggerWrapper logger;
-
-
-
-  public MirBasicOpenPostingLocalizer() {
-    logger = new LoggerWrapper("Localizer.Basic.OpenPosting");
-
-    try {
-      String contentProducers = MirGlobal.config().getString("Mir.Localizer.OpenPosting.ContentProducers");
-      String commentProducers = MirGlobal.config().getString("Mir.Localizer.OpenPosting.CommentProducers");
-
-      afterContentProducerTasks = ProducerEngine.ProducerTask.parseProducerTaskList(contentProducers);
-      afterCommentProducerTasks = ProducerEngine.ProducerTask.parseProducerTaskList(commentProducers);
-    }
-    catch (Throwable t) {
-      logger.error("Setting up MirBasicOpenPostingLocalizer failed: " + t.getMessage());
-    }
-  }
-
-  public void afterContentPosting() {
-    MirGlobal.producerEngine().addTasks(afterContentProducerTasks);
-  }
-
-  public void afterContentPosting(EntityContent aContent) {
-    afterContentPosting();
-  }
-
-  public void afterCommentPosting() {
-    MirGlobal.producerEngine().addTasks(afterCommentProducerTasks);
-  }
-
-  public void afterCommentPosting(EntityComment aComment) {
-    afterCommentPosting();
-  }
-
-  public String chooseOpenPostingLanguage(HttpServletRequest req) {
-    Locale locale = req.getLocale();
-
-    return locale.getLanguage();
-  }
-
-}
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.localizer.basic;\r
+\r
+import java.util.List;\r
+import java.util.Locale;\r
+import java.util.*;\r
+import javax.servlet.http.HttpServletRequest;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.*;\r
+import mir.config.*;\r
+import mir.session.Request;\r
+import mir.session.Response;\r
+import mir.session.*;\r
+\r
+import mircoders.entity.EntityComment;\r
+import mircoders.entity.EntityContent;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.global.ProducerEngine;\r
+import mircoders.localizer.*;\r
+\r
+public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer {\r
+  private List afterContentProducerTasks;\r
+  private List afterCommentProducerTasks;\r
+  protected LoggerWrapper logger;\r
+  protected MirPropertiesConfiguration configuration;\r
+\r
+\r
+  public MirBasicOpenPostingLocalizer() throws MirLocalizerExc, MirLocalizerFailure {\r
+    logger = new LoggerWrapper("Localizer.Basic.OpenPosting");\r
+\r
+    try {\r
+      configuration = MirPropertiesConfiguration.instance();\r
+    }\r
+    catch (Throwable e) {\r
+      throw new MirLocalizerFailure("Can't get configuration: " + e.getMessage(), e);\r
+    }\r
+\r
+    try {\r
+      String contentProducers = MirGlobal.config().getString("Mir.Localizer.OpenPosting.ContentProducers");\r
+      String commentProducers = MirGlobal.config().getString("Mir.Localizer.OpenPosting.CommentProducers");\r
+\r
+      afterContentProducerTasks = ProducerEngine.ProducerTask.parseProducerTaskList(contentProducers);\r
+      afterCommentProducerTasks = ProducerEngine.ProducerTask.parseProducerTaskList(commentProducers);\r
+    }\r
+    catch (Throwable t) {\r
+      logger.error("Setting up MirBasicOpenPostingLocalizer failed: " + t.getMessage());\r
+\r
+      throw new MirLocalizerFailure(t);\r
+    }\r
+  }\r
+\r
+  public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure {\r
+    if (aSession.getAttribute("handler")==null)\r
+      aSession.setAttribute("handler", new MirBasicCommentPostingSessionHandler());\r
+\r
+    return (SessionHandler) aSession.getAttribute("handler");\r
+  }\r
+\r
+  public void afterContentPosting() {\r
+    MirGlobal.producerEngine().addTasks(afterContentProducerTasks);\r
+  }\r
+\r
+  public void afterContentPosting(EntityContent aContent) {\r
+    afterContentPosting();\r
+  }\r
+\r
+  public void afterCommentPosting(EntityComment aComment) {\r
+    afterCommentPosting();\r
+  }\r
+\r
+  public void afterCommentPosting() {\r
+    MirGlobal.producerEngine().addTasks(afterCommentProducerTasks);\r
+  }\r
+\r
+  public String generateOnetimePassword() {\r
+    Random r = new Random();\r
+    int random = r.nextInt();\r
+\r
+    long l = System.currentTimeMillis();\r
+\r
+    l = (l*l*l*l)/random;\r
+    if (l<0)\r
+      l = l * -1;\r
+\r
+    String returnString = ""+l;\r
+\r
+    return returnString.substring(5);\r
+  }\r
+\r
+}\r
diff --git a/source/mircoders/media/MediaUploadProcessor.java b/source/mircoders/media/MediaUploadProcessor.java
new file mode 100755 (executable)
index 0000000..a23be01
--- /dev/null
@@ -0,0 +1,115 @@
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.media;\r
+\r
+import java.util.GregorianCalendar;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import mir.entity.Entity;\r
+import mir.media.MediaExc;\r
+import mir.media.MediaFailure;\r
+import mir.media.MediaHelper;\r
+import mir.media.MirMedia;\r
+import mir.misc.StringUtil;\r
+import mir.session.UploadedFile;\r
+import mir.storage.Database;\r
+\r
+import mircoders.module.ModuleMediaType;\r
+\r
+public class MediaUploadProcessor {\r
+  public static Entity processMediaUpload(UploadedFile aFile) throws MediaExc, MediaFailure {\r
+    String mediaId;\r
+    MirMedia mediaHandler;\r
+    Entity mediaType;\r
+    ModuleMediaType mediaTypeModule;\r
+    Database mediaStorage;\r
+    Map values = new HashMap();\r
+    String MediaId;\r
+    Entity mediaEntity;\r
+\r
+\r
+    try {\r
+      String contentType = aFile.getContentType();\r
+\r
+      if (contentType.equals("text/plain") ||\r
+          contentType.equals("application/octet-stream") ||\r
+          contentType == null) {\r
+        throw new MediaExc("Invalid content-type: " + contentType);\r
+      }\r
+\r
+      values.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
+      values.put("is_produced", "0");\r
+      values.put("is_published", "1");\r
+      values.put("to_publisher", "0");\r
+      values.put("to_media_folder", "7");\r
+      values.put("title", "");\r
+\r
+      mediaTypeModule = new ModuleMediaType();\r
+      mediaType = mediaTypeModule.findMediaTypeForMimeType(contentType);\r
+\r
+      try {\r
+        mediaHandler = MediaHelper.getHandler(mediaType);\r
+        mediaStorage = MediaHelper.getStorage(mediaType, "mircoders.storage.Database");\r
+      }\r
+      catch (Throwable e) {\r
+        throw new MediaFailure(e);\r
+      }\r
+\r
+      values.put("to_media_type", mediaType.getId());\r
+\r
+      try {\r
+        mediaEntity = (Entity) mediaStorage.getEntityClass().newInstance();\r
+        mediaEntity.setStorage(mediaStorage);\r
+      }\r
+      catch (Throwable e) {\r
+        throw new MediaFailure(e);\r
+      }\r
+\r
+      mediaEntity.setValues(values);\r
+      mediaId = mediaEntity.insert();\r
+\r
+      try {\r
+        mediaHandler.set(aFile.getInputStream(), mediaEntity, mediaType);\r
+      }\r
+      catch (Throwable e) {\r
+        throw new MediaFailure(e);\r
+      }\r
+\r
+      return mediaEntity;\r
+    }\r
+    catch (Throwable e) {\r
+      throw new MediaFailure(e);\r
+    }\r
+\r
+  }\r
+}
\ No newline at end of file
index af8ec8c..57237e3 100755 (executable)
@@ -1,3 +1,34 @@
+/*
+ * Copyright (C) 2001, 2002  The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with the com.oreilly.servlet library, any library
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of
+ * the above that use the same license as the above), and distribute linked
+ * combinations including the two.  You must obey the GNU General Public
+ * License in all respects for all of the code used other than the above
+ * mentioned libraries.  If you modify this file, you may extend this exception
+ * to your version of the file, but you are not obligated to do so.  If you do
+ * not wish to do so, delete this exception statement from your version.
+ */
+
 package mircoders.media;
 
 import mir.media.MediaExc;
index f697f8b..cd4142e 100755 (executable)
@@ -38,13 +38,14 @@ import mir.module.ModuleExc;
 import mir.module.ModuleFailure;
 import mir.storage.StorageObject;
 
-/*
- *  ContentObjekt -
- *
- * @version $Id: ModuleContent.java,v 1.18 2003/03/09 19:14:21 idfx Exp $
- *
- * @author RK, mir-coders
+/**
  *
+ * <p>Title: ModuleContent</p>
+ * <p>Description: helper routines to manage articles</p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
  */
 
 public class ModuleContent extends AbstractModule
@@ -59,110 +60,6 @@ public class ModuleContent extends AbstractModule
     this.theStorage = theStorage;
   }
 
-//
-// various methods to retrieve content entities
-
-//  public EntityList getFeatures(int offset, int limit) throws ModuleExc, ModuleFailure {
-//    return getContent("is_published=true AND to_article_type=2", "webdb_create desc",
-//                      offset, limit);
-//  }
-
-//  public EntityList getNewsWire(int offset, int limit) throws ModuleExc, ModuleFailure {
-//    return getContent("is_published=true AND to_article_type = 1",
-//                      "webdb_create desc",offset,limit);
-//  }
-
-//  public EntityList getStartArticle() throws ModuleExc, ModuleFailure {
-//    EntityList returnList = getContent("is_published=true AND to_article_type=4",
-//                                       "webdb_create desc",0,1);
-//if no startspecial exists
-//    if (returnList==null || returnList.size()==0)
-//      returnList = getContent("is_published=true AND to_article_type=3",
-//                              "webdb_create desc",0,1);
-
-//    return returnList;
-//  }
-
-/*
-      public EntityList getContent(Map searchValues, boolean concat, int offset, EntityUsers user) throws ModuleException {
-
-    try {
-
-      String whereClause ="", aField, aValue;
-      boolean first = true;
-
-      Set set = searchValues.keySet();
-      Iterator it = set.iterator();
-      for (int i=0;i<set.size();i++) {
-        aField = (String)it.next();
-        aValue = (String)searchValues.get(aField);
-
-        if (first == false)
-          whereClause +=  (concat) ? " and " : " or ";
-        else
-          first = false;
-
-        whereClause += "(";
-
-// default: hier splitten der eintraege und verknupfung mit AND OR NOT
-        StringTokenizer st = new StringTokenizer(aValue);
-        boolean firstToken = true;
-        while(st.hasMoreTokens()) {
-          String notString = "";
-          String tokenConcat = " OR ";
-          String nextToken = st.nextToken();
-
-          if (nextToken.startsWith("+")) {
-            nextToken = nextToken.substring(1);
-            tokenConcat = " AND ";
-          }
-          if (nextToken.startsWith("-")) {
-            nextToken = nextToken.substring(1);
-            tokenConcat = " AND ";
-            notString = " NOT ";
-          }
-          if (firstToken == true) {
-            tokenConcat = "";
-            firstToken = false;
-          }
-
-
-          whereClause += tokenConcat + aField + notString + " like '";
-          whereClause += nextToken + "%'";
-        }
-        whereClause += ") ";
-      }
-      return theStorage.selectByWhereClause(whereClause, offset);
-    }
-    catch (StorageObjectFailure e){
-      throw new ModuleException(e.toString());
-    }
-
-  }
-*/
-/*
-  public EntityList getContentByField(String aField, String aValue, String orderBy, int offset,
-                                      EntityUsers user) throws ModuleException
-  {
-    String whereClause = "lower("+aField + ") like lower('%" + JDBCStringRoutines.escapeStringLiteral(aValue) + "%')";
-    return getContent(whereClause, orderBy, offset, user);
-  }
-
-
-  public EntityList getContent(String whereClause, String orderBy, int offset,
-                               int limit, EntityUsers user) throws ModuleException {
-
-    try {
-      if (user!=null){
-        if (!user.isAdmin())
-          whereClause += " and to_publisher='" + user.getId()+"'";
-      }
-      return theStorage.selectByWhereClause(whereClause, orderBy, offset, limit);
-    }
-    catch (StorageObjectFailure e){    throw new ModuleException(e.toString()); }
-  }
-*/
-
   public EntityList getContent(String whereClause, String orderBy,int offset, int limit) throws ModuleExc, ModuleFailure {
     try {
       return theStorage.selectByWhereClause(whereClause, orderBy, offset, limit);
@@ -171,55 +68,6 @@ public class ModuleContent extends AbstractModule
       throw new ModuleFailure(e);
     }
   }
-/*
-  public EntityList getContent(String whereClause, String orderBy, int offset, EntityUsers user)
-      throws ModuleException
-  {
-    try {
-      if (whereClause !=null) {
-
-// for the different article_types
-        if(whereClause.equals("newswire")) {
-          whereClause="is_published='1' and to_article_type='1'";
-          orderBy = "webdb_create desc";
-        }
-        if(whereClause.equals("feature")) {
-          whereClause="is_published='1' and to_article_type='2'";
-          orderBy = "webdb_create desc";
-        }
-        if(whereClause.equals("themenspecial")) {
-          whereClause="is_published='1' and to_article_type='3'";
-          orderBy = "webdb_create desc";
-        }
-        if(whereClause.equals("special")) {
-          whereClause="is_published='1' and to_article_type='4'";
-          orderBy = "webdb_create desc";
-        }
-
-        if(whereClause.equals("comments")) {
-          whereClause="not (comment is null or comment like '')";
-          orderBy = "webdb_lastchange desc";
-        }
-
-        if(whereClause.equals("nfrei")) {
-          whereClause="is_published='0'"; orderBy="webdb_create desc";
-        }
-
-        if(whereClause.equals("lastchange")) {
-          whereClause=""; orderBy="webdb_lastchange desc";
-        }
-
-        if(whereClause.equals("media")) {
-          return DatabaseContentToMedia.getInstance().getContent();
-        }
-      }
-      return theStorage.selectByWhereClause(whereClause, orderBy, offset);
-    }
-    catch (StorageObjectFailure e) {
-      throw new ModuleException(e.toString());
-    }
-  }
-*/
 }
 
 
diff --git a/source/mircoders/module/ModuleMediaType.java b/source/mircoders/module/ModuleMediaType.java
new file mode 100755 (executable)
index 0000000..9aac62c
--- /dev/null
@@ -0,0 +1,72 @@
+package mircoders.module;\r
+\r
+import java.util.List;\r
+\r
+import mir.entity.Entity;\r
+import mir.entity.EntityList;\r
+import mir.log.LoggerWrapper;\r
+import mir.module.AbstractModule;\r
+import mir.module.ModuleExc;\r
+import mir.module.ModuleFailure;\r
+import mir.storage.StorageObject;\r
+import mir.util.JDBCStringRoutines;\r
+import mir.util.StringRoutines;\r
+import mircoders.storage.DatabaseMediaType;\r
+\r
+public class ModuleMediaType extends AbstractModule {\r
+  static LoggerWrapper logger = new LoggerWrapper("Module.Content");\r
+\r
+  public ModuleMediaType() {\r
+    this (DatabaseMediaType.getInstance());\r
+  }\r
+\r
+  public ModuleMediaType(StorageObject aStorage) {\r
+    this.theStorage = aStorage;\r
+  }\r
+\r
+  public Entity findMediaTypeForMimeType(String aMimeType) throws ModuleExc, ModuleFailure {\r
+    List contentTypeParts = StringRoutines.splitString(aMimeType, "/");\r
+\r
+    if (contentTypeParts.size()!=2) {\r
+      throw new InvalidMimeTypeExc("Invalid mimetype: " + aMimeType, aMimeType);\r
+    }\r
+    String mimeTypeMajor = (String) contentTypeParts.get(0);\r
+\r
+    EntityList mediaTypes;\r
+\r
+    mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(aMimeType)+"'");\r
+    if (mediaTypes.size() == 0) {\r
+      mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(mimeTypeMajor+"/*")+"'");\r
+    }\r
+    if (mediaTypes.size() == 0) {\r
+      throw new UnsupportedMimeTypeExc("Unsupported mimetype: " + aMimeType, aMimeType);\r
+    }\r
+\r
+    return (Entity) mediaTypes.get(0);\r
+  }\r
+\r
+  public static class MimeTypeExc extends ModuleExc {\r
+    private String mimeType;\r
+\r
+    public MimeTypeExc(String aMessage, String aMimeType) {\r
+      super (aMessage);\r
+      mimeType = aMimeType;\r
+    }\r
+\r
+    public String getMimeType() {\r
+      return mimeType;\r
+    }\r
+  }\r
+\r
+  public static class UnsupportedMimeTypeExc extends MimeTypeExc {\r
+    public UnsupportedMimeTypeExc(String aMessage, String aMimeType) {\r
+      super(aMessage, aMimeType);\r
+    }\r
+  }\r
+\r
+  public static class InvalidMimeTypeExc extends MimeTypeExc {\r
+    public InvalidMimeTypeExc(String aMessage, String aMimeType) {\r
+      super(aMessage, aMimeType);\r
+    }\r
+  }\r
+}
\ No newline at end of file
index e875ce8..5586424 100755 (executable)
@@ -1,52 +1,55 @@
-/*
- * Copyright (C) 2001, 2002  The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with the com.oreilly.servlet library, any library
- * licensed under the Apache Software License, The Sun (tm) Java Advanced
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of
- * the above that use the same license as the above), and distribute linked
- * combinations including the two.  You must obey the GNU General Public
- * License in all respects for all of the code used other than the above
- * mentioned libraries.  If you modify this file, you may extend this exception
- * to your version of the file, but you are not obligated to do so.  If you do
- * not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.module;
-
-import mir.log.LoggerWrapper;
-import mir.module.AbstractModule;
-import mir.storage.StorageObject;
-
-/*
- *  ThemenModule -
- *
- *
- * @author RK
- */
-
-public class ModuleUploadedMedia extends AbstractModule
-{
-  static LoggerWrapper logger = new LoggerWrapper("Module.UploadedMedia");
-
-  public ModuleUploadedMedia(StorageObject theStorage) {
-    this.theStorage = theStorage;
-  }
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.module;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.module.AbstractModule;\r
+import mir.storage.StorageObject;\r
+\r
+/**\r
+ *\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author the mir coders\r
+ * @version 1.0\r
+ */\r
+\r
+public class ModuleUploadedMedia extends AbstractModule\r
+{\r
+  static LoggerWrapper logger = new LoggerWrapper("Module.UploadedMedia");\r
+\r
+  public ModuleUploadedMedia(StorageObject aStorage) {\r
+    theStorage = aStorage;\r
+  }\r
 }
\ No newline at end of file
index efe8dbc..dbffa3a 100755 (executable)
@@ -1,3 +1,34 @@
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
 package mircoders.servlet;\r
 \r
 import java.io.PrintWriter;\r
@@ -88,7 +119,7 @@ public class ServletHelper {
     Generator generator;\r
 \r
     try {\r
-      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator);\r
+      generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);\r
 \r
       generator.generate(aWriter, aGenerationData, new PrintWriter(new NullWriter()));\r
     }\r
index e2d955b..faf1e81 100755 (executable)
@@ -1,5 +1,36 @@
-package mircoders.servlet;
-
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.servlet;\r
+\r
 import java.util.Locale;\r
 import java.util.Map;\r
 import javax.servlet.http.HttpServletRequest;\r
@@ -10,141 +41,141 @@ import mir.servlet.ServletModule;
 import mir.servlet.ServletModuleFailure;\r
 import mir.util.HTTPRequestParser;\r
 import mir.util.URLBuilder;\r
-import mircoders.global.MirGlobal;
-
-public class ServletModuleAbuse extends ServletModule {
-  private static ServletModuleAbuse instance = new ServletModuleAbuse();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleAbuse() {
-    logger = new LoggerWrapper("ServletModule.Abuse");
-    defaultAction = "showsettings";
-  }
-
-  public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-    String type=requestParser.getParameterWithDefault("type", "");
-    String id=requestParser.getParameterWithDefault("id", "");
-    String expression=requestParser.getParameterWithDefault("expression", "");
-
-    if (id.equals("")) {
-      MirGlobal.abuse().addFilter(type, expression);
-    }
-    else {
-      MirGlobal.abuse().setFilter(id, type, expression);
-    }
-
-    MirGlobal.abuse().save();
-
-    showfilters(aRequest, aResponse);
-  }
-
-  public void deletefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-    String id=requestParser.getParameterWithDefault("id", "");
-    MirGlobal.abuse().deleteFilter(id);
-
-    MirGlobal.abuse().save();
-
-    showfilters(aRequest, aResponse);
-  }
-
-  public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    URLBuilder urlBuilder = new URLBuilder();
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
-
-      urlBuilder.setValue("module", "Abuse");
-      urlBuilder.setValue("do", "showfilters");
-      responseData.put("thisurl", urlBuilder.getQuery());
-
-      responseData.put("filters", MirGlobal.abuse().getFilters());
-      responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.filters.template");
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-
-  public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    URLBuilder urlBuilder = new URLBuilder();
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
-
-      urlBuilder.setValue("module", "Abuse");
-      urlBuilder.setValue("do", "showsettings");
-
-      responseData.put("thisurl", urlBuilder.getQuery());
-
-      responseData.put("articleactions", MirGlobal.abuse().getArticleActions());
-      responseData.put("commentactions", MirGlobal.abuse().getCommentActions());
-
-      responseData.put("disableop", new Boolean(MirGlobal.abuse().getOpenPostingDisabled()));
-      responseData.put("passwordop", new Boolean(MirGlobal.abuse().getOpenPostingPassword()));
-      responseData.put("logenabled", new Boolean(MirGlobal.abuse().getLogEnabled()));
-      responseData.put("logsize", Integer.toString(MirGlobal.abuse().getLogSize()));
-      responseData.put("usecookies", new Boolean(MirGlobal.abuse().getCookieOnBlock()));
-      responseData.put("articleaction", MirGlobal.abuse().getArticleBlockAction());
-      responseData.put("commentaction", MirGlobal.abuse().getCommentBlockAction());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.template");
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void savesettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    try {
-      HTTPRequestParser parser = new HTTPRequestParser(aRequest);
-
-      MirGlobal.abuse().setOpenPostingDisabled(parser.getParameterWithDefault("disableop", "").equals("1"));
-      MirGlobal.abuse().setOpenPostingPassword(parser.getParameterWithDefault("passwordop", "").equals("1"));
-      MirGlobal.abuse().setLogEnabled(parser.getParameterWithDefault("logenabled", "").equals("1"));
-
-      try {
-        MirGlobal.abuse().setLogSize(parser.getIntegerWithDefault("logsize", MirGlobal.abuse().getLogSize()));
-      }
-      catch (Throwable t) {
-      }
-
-      MirGlobal.abuse().setCookieOnBlock(parser.getParameterWithDefault("usecookies", "").equals("1"));
-
-      MirGlobal.abuse().setArticleBlockAction(parser.getParameter("articleaction"));
-      MirGlobal.abuse().setCommentBlockAction(parser.getParameter("commentaction"));
-
-      MirGlobal.abuse().save();
-
-      showsettings(aRequest, aResponse);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void showlog(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    URLBuilder urlBuilder = new URLBuilder();
-    int count;
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
-      urlBuilder.setValue("module", "Abuse");
-      urlBuilder.setValue("do", "showlog");
-      responseData.put("thisurl", urlBuilder.getQuery());
-
-      responseData.put("log", MirGlobal.abuse().getLog());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.log.template");
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
+import mircoders.global.MirGlobal;\r
+\r
+public class ServletModuleAbuse extends ServletModule {\r
+  private static ServletModuleAbuse instance = new ServletModuleAbuse();\r
+  public static ServletModule getInstance() { return instance; }\r
+\r
+  private ServletModuleAbuse() {\r
+    logger = new LoggerWrapper("ServletModule.Abuse");\r
+    defaultAction = "showsettings";\r
+  }\r
+\r
+  public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+    String type=requestParser.getParameterWithDefault("type", "");\r
+    String id=requestParser.getParameterWithDefault("id", "");\r
+    String expression=requestParser.getParameterWithDefault("expression", "");\r
+\r
+    if (id.equals("")) {\r
+      MirGlobal.abuse().addFilter(type, expression);\r
+    }\r
+    else {\r
+      MirGlobal.abuse().setFilter(id, type, expression);\r
+    }\r
+\r
+    MirGlobal.abuse().save();\r
+\r
+    showfilters(aRequest, aResponse);\r
+  }\r
+\r
+  public void deletefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+    String id=requestParser.getParameterWithDefault("id", "");\r
+    MirGlobal.abuse().deleteFilter(id);\r
+\r
+    MirGlobal.abuse().save();\r
+\r
+    showfilters(aRequest, aResponse);\r
+  }\r
+\r
+  public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+\r
+      urlBuilder.setValue("module", "Abuse");\r
+      urlBuilder.setValue("do", "showfilters");\r
+      responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+      responseData.put("filters", MirGlobal.abuse().getFilters());\r
+      responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.filters.template");\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+\r
+  public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+\r
+      urlBuilder.setValue("module", "Abuse");\r
+      urlBuilder.setValue("do", "showsettings");\r
+\r
+      responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+      responseData.put("articleactions", MirGlobal.abuse().getArticleActions());\r
+      responseData.put("commentactions", MirGlobal.abuse().getCommentActions());\r
+\r
+      responseData.put("disableop", new Boolean(MirGlobal.abuse().getOpenPostingDisabled()));\r
+      responseData.put("passwordop", new Boolean(MirGlobal.abuse().getOpenPostingPassword()));\r
+      responseData.put("logenabled", new Boolean(MirGlobal.abuse().getLogEnabled()));\r
+      responseData.put("logsize", Integer.toString(MirGlobal.abuse().getLogSize()));\r
+      responseData.put("usecookies", new Boolean(MirGlobal.abuse().getCookieOnBlock()));\r
+      responseData.put("articleaction", MirGlobal.abuse().getArticleBlockAction());\r
+      responseData.put("commentaction", MirGlobal.abuse().getCommentBlockAction());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.template");\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void savesettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    try {\r
+      HTTPRequestParser parser = new HTTPRequestParser(aRequest);\r
+\r
+      MirGlobal.abuse().setOpenPostingDisabled(parser.getParameterWithDefault("disableop", "").equals("1"));\r
+      MirGlobal.abuse().setOpenPostingPassword(parser.getParameterWithDefault("passwordop", "").equals("1"));\r
+      MirGlobal.abuse().setLogEnabled(parser.getParameterWithDefault("logenabled", "").equals("1"));\r
+\r
+      try {\r
+        MirGlobal.abuse().setLogSize(parser.getIntegerWithDefault("logsize", MirGlobal.abuse().getLogSize()));\r
+      }\r
+      catch (Throwable t) {\r
+      }\r
+\r
+      MirGlobal.abuse().setCookieOnBlock(parser.getParameterWithDefault("usecookies", "").equals("1"));\r
+\r
+      MirGlobal.abuse().setArticleBlockAction(parser.getParameter("articleaction"));\r
+      MirGlobal.abuse().setCommentBlockAction(parser.getParameter("commentaction"));\r
+\r
+      MirGlobal.abuse().save();\r
+\r
+      showsettings(aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void showlog(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+    int count;\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+      urlBuilder.setValue("module", "Abuse");\r
+      urlBuilder.setValue("do", "showlog");\r
+      responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+      responseData.put("log", MirGlobal.abuse().getLog());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.log.template");\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
 }
\ No newline at end of file
index dac1b8e..890c57c 100755 (executable)
-/*
- * Copyright (C) 2001, 2002  The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with the com.oreilly.servlet library, any library
- * licensed under the Apache Software License, The Sun (tm) Java Advanced
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of
- * the above that use the same license as the above), and distribute linked
- * combinations including the two.  You must obey the GNU General Public
- * License in all respects for all of the code used other than the above
- * mentioned libraries.  If you modify this file, you may extend this exception
- * to your version of the file, but you are not obligated to do so.  If you do
- * not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.servlet;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
-import java.util.Vector;
-import java.util.Locale;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import gnu.regexp.RE;
-import gnu.regexp.REMatch;
-import gnu.regexp.REMatchEnumeration;
-import gnu.regexp.REException;
-
-
-import org.apache.commons.net.smtp.SMTPClient;
-import org.apache.commons.net.smtp.SMTPReply;
-//import org.apache.fop.apps.Driver;
-//import org.apache.fop.apps.XSLTInputHandler;
-import org.apache.log.Hierarchy;
-import org.apache.log.Priority;
-import org.apache.lucene.analysis.standard.StandardAnalyzer;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.queryParser.QueryParser;
-import org.apache.lucene.search.Hits;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.Query;
-import org.apache.lucene.search.Searcher;
-import org.apache.struts.util.MessageResources;
-import mir.entity.Entity;
-import mir.entity.EntityList;
-import mir.generator.Generator;
-import mir.log.LoggerWrapper;
-import mir.misc.FileHandler;
-import mir.misc.StringUtil;
-import mir.misc.WebdbMultipartRequest;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleExc;
-import mir.servlet.ServletModuleFailure;
-import mir.servlet.ServletModuleUserExc;
-import mir.storage.StorageObjectFailure;
-import mir.util.ExceptionFunctions;
-import mir.util.HTTPRequestParser;
-import mir.util.StringRoutines;
-import mircoders.entity.EntityComment;
-import mircoders.entity.EntityContent;
-import mircoders.global.MirGlobal;
-import mircoders.media.MediaRequest;
-import mircoders.media.UnsupportedMediaFormatExc;
-import mircoders.module.ModuleComment;
-import mircoders.module.ModuleContent;
-import mircoders.module.ModuleImages;
-import mircoders.module.ModuleTopics;
-import mircoders.pdf.PDFGenerator;
-import mircoders.search.AudioSearchTerm;
-import mircoders.search.ContentSearchTerm;
-import mircoders.search.ImagesSearchTerm;
-import mircoders.search.KeywordSearchTerm;
-import mircoders.search.TextSearchTerm;
-import mircoders.search.TopicSearchTerm;
-import mircoders.search.UnIndexedSearchTerm;
-import mircoders.search.VideoSearchTerm;
-import mircoders.storage.DatabaseComment;
-import mircoders.storage.DatabaseContent;
-import mircoders.storage.DatabaseContentToMedia;
-import mircoders.storage.DatabaseContentToTopics;
-import mircoders.storage.DatabaseImages;
-import mircoders.storage.DatabaseLanguage;
-import mircoders.storage.DatabaseTopics;
-
-/*
- *  ServletModuleOpenIndy -
- *   is the open-access-servlet, which is responsible for
- *    adding comments to articles &
- *    open-postings to the newswire
- *
- * @author mir-coders group
- * @version $Id: ServletModuleOpenIndy.java,v 1.73 2003/04/14 19:19:16 john Exp $
- *
- */
-
-public class ServletModuleOpenIndy extends ServletModule
-{
-
-  private String        commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
-  private String        postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
-  private String        searchResultsTemplate;
-  private String        prepareMailTemplate,sentMailTemplate;
-  private ModuleContent contentModule;
-  private ModuleComment commentModule;
-  private ModuleImages  imageModule;
-  private ModuleTopics  topicsModule;
-  private String        directOp ="yes";
-  // Singelton / Kontruktor
-  private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleOpenIndy() {
-    super();
-    try {
-      logger = new LoggerWrapper("ServletModule.OpenIndy");
-
-      commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
-      commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
-      commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
-      postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
-      postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
-      postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
-      searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
-      prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
-      sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
-      directOp = configuration.getString("DirectOpenposting").toLowerCase();
-      mainModule = new ModuleComment(DatabaseComment.getInstance());
-      contentModule = new ModuleContent(DatabaseContent.getInstance());
-      topicsModule = new ModuleTopics(DatabaseTopics.getInstance());
-      imageModule = new ModuleImages(DatabaseImages.getInstance());
-      defaultAction="addposting";
-    }
-    catch (StorageObjectFailure e) {
-      logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
-    }
-  }
-
-  /**
-   * Method to return an "apology" when open postings are disabled
-   *
-   * @param aRequest
-   * @param aResponse
-   * @throws ServletModuleExc
-   * @throws ServletModuleUserExc
-   * @throws ServletModuleFailure
-   */
-  public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    deliver(aRequest, aResponse, (Map) null, null,
-       configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
-  }
-
-
-  /**
-   *  Method for making a comment
-   */
-
-  public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
-  {
-    if (MirGlobal.abuse().getOpenPostingDisabled()) {
-      openPostingDisabled(req, res);
-
-      return;
-    }
-
-    String aid = req.getParameter("aid"); // the article id the comment will belong to
-/*
-    String language = req.getParameter("language");
- */
-
-    if (aid!=null && !aid.equals("")) {
-      try {
-        Map mergeData = new HashMap();
-
-        // onetimepasswd
-        if (MirGlobal.abuse().getOpenPostingPassword()) {
-          String passwd = this.createOneTimePasswd();
-          HttpSession session = req.getSession(false);
-          session.setAttribute("passwd", passwd);
-          mergeData.put("passwd", passwd);
-        }
-        else {
-          mergeData.put("passwd", (String) null);
-        }
-/*
-        if (language != null) {
-          HttpSession session = req.getSession(false);
-          session.setAttribute("Locale", new Locale(language, ""));
-          session.setAttribute("language", language);
-        }
-*/
-        mergeData.put("aid", aid);
-
-        Map extraInfo = new HashMap();
-        extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
-
-        deliver(req, res, mergeData, extraInfo, commentFormTemplate);
-      }
-      catch (Throwable t) {
-        throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
-      }
-    }
-    else throw new ServletModuleExc("aid not set!");
-  }
-
-  /**
-   *  Method for inserting a comment into the Database and delivering
-   *  the commentDone Page
-   */
-
-  public void inscomment(HttpServletRequest req, HttpServletResponse res)
-    throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
-  {
-    if (MirGlobal.abuse().getOpenPostingDisabled()) {
-      openPostingDisabled(req, res);
-
-      return;
-    }
-
-    String aid = req.getParameter("to_media"); // the article id the comment will belong to
-    if (aid!=null && !aid.equals(""))
-      {
-        // ok, collecting data from form
-        try {
-          Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
-
-          //no html in comments(for now)
-          for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
-            String k=(String)i.next();
-            String v=(String)withValues.get(k);
-
-            withValues.put(k,StringUtil.removeHTMLTags(v));
-          }
-          withValues.put("is_published","1");
-          withValues.put("to_comment_status","1");
-
-          //checking the onetimepasswd
-          HttpSession session = req.getSession(false);
-          String sessionPasswd = (String) session.getAttribute("passwd");
-          if ( sessionPasswd != null){
-            String passwd = req.getParameter("passwd");
-            if ( passwd == null || passwd.length()==0) {
-              throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});
-            }
-            if (!sessionPasswd.equals(passwd)) {
-              throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});
-            }
-            session.invalidate();
-          }
-
-          String id = mainModule.add(withValues);
-
-          if(id==null){
-            deliver(req, res, (Map) null, null, commentFormDupeTemplate);
-          }
-          else {
-            MirGlobal.abuse().logComment(req.getRemoteAddr(), id, new Date(), (String) req.getHeader("User-Agent"));
-
-            DatabaseContent.getInstance().setUnproduced("id="+aid);
-
-            try {
-              EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
-              MirGlobal.abuse().checkComment(comment, req, res);
-              MirGlobal.localizer().openPostings().afterCommentPosting(comment);
-            }
-            catch (Throwable t) {
-              throw new ServletModuleExc(t.getMessage());
-            }
-          }
-
-          // redirecting to url
-          // should implement back to article
-          Map mergeData = new HashMap();
-          deliver(req, res, mergeData, null, commentFormDoneTemplate);
-        }
-        catch (Throwable e) {
-          throw new ServletModuleFailure(e);
-        }
-      }
-    else throw new ServletModuleExc("aid not set!");
-
-  }
-
-  /**
-   *  Method for delivering the form-Page for open posting
-   */
-
-  public void addposting(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
-  {
-    try {
-      if (MirGlobal.abuse().getOpenPostingDisabled()) {
-        openPostingDisabled(req, res);
-
-        return;
-      }
-
-      Map mergeData = new HashMap();
-
-      // onetimepasswd
-      if (MirGlobal.abuse().getOpenPostingPassword()) {
-        String passwd = this.createOneTimePasswd();
-        HttpSession session = req.getSession(false);
-        session.setAttribute("passwd", passwd);
-        mergeData.put("passwd", passwd);
-      }
-      else {
-        mergeData.put("passwd", (String)null);
-      }
-
-      String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
-      String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
-      String numOfMedia = req.getParameter("medianum");
-
-      if (numOfMedia == null || numOfMedia.equals("")) {
-        numOfMedia = defaultMedia;
-      }
-      else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
-        numOfMedia = maxMedia;
-      }
-
-      int mediaNum = Integer.parseInt(numOfMedia);
-      List mediaFields = new Vector();
-      for (int i = 0; i < mediaNum; i++) {
-        Integer mNum = new Integer(i + 1);
-        mediaFields.add(mNum.toString());
-      }
-      mergeData.put("medianum", numOfMedia);
-      mergeData.put("mediafields", mediaFields);
-      mergeData.put("to_topic", null);
-
-      Map extraInfo = new HashMap();
-      extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
-      extraInfo.put("themenPopupData", topicsModule.getTopicsAsSimpleList());
-
-      extraInfo.put("topics", topicsModule.getTopicsList());
-      deliver(req, res, mergeData, extraInfo, postingFormTemplate);
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  /**
-   *  Method for inserting an open posting into the Database and delivering
-   *  the postingDone Page
-   */
-
-  public void insposting(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
-  {
-    if (MirGlobal.abuse().getOpenPostingDisabled()) {
-      openPostingDisabled(req, res);
-
-      return;
-    }
-
-    Map mergeData = new HashMap();
-    boolean setMedia=false;
-    boolean setTopic = false;
-
-    try {
-
-      WebdbMultipartRequest mp = null;
-      EntityList mediaList = null;
-      try {
-        // new MediaRequest, "1" is the id for the openPosting user
-        MediaRequest mediaReq = new MediaRequest("1", true);
-        mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);
-        mediaList = mediaReq.getEntityList();
-      }
-      catch (Throwable e) {
-        throw new ServletModuleFailure(e);
-      }
-
-      Map withValues = mp.getParameters();
-
-      //checking the onetimepasswd
-      HttpSession session = req.getSession(false);
-      String sessionPasswd = (String) session.getAttribute("passwd");
-      if (sessionPasswd != null){
-        String passwd = (String) withValues.get("passwd");
-
-        logger.debug("session password = " + sessionPasswd + ", form password = " + passwd);
-
-        if ( passwd == null || passwd.length()==0) {
-          throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});
-        }
-        if (!sessionPasswd.equals(passwd)) {
-          throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});
-        }
-        session.invalidate();
-      }
-
-      if ((((String)withValues.get("title")).length() == 0) ||
-          (((String)withValues.get("description")).length() == 0) ||
-          (((String)withValues.get("content_data")).length() == 0))
-        throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
-
-      // call the routines that escape html
-
-      for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
-        String k=(String)i.next();
-        String v=(String)withValues.get(k);
-
-        if (k.equals("content_data")){
-          //this doesn't quite work yet, so for now, all html goes
-          //withValues.put(k,StringUtil.approveHTMLTags(v));
-          withValues.put(k,StringUtil.deleteForbiddenTags(v));
-        }
-        else if (k.equals("description")) {
-          String tmp = StringUtil.deleteForbiddenTags(v);
-          withValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
-        }
-        else {
-          withValues.put(k,StringUtil.removeHTMLTags(v));
-        }
-
-      }
-
-      withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
-      withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
-      withValues.put("is_produced", "0");
-      withValues.put("is_published","1");
-      if (directOp.equals("yes"))
-        withValues.put("to_article_type","1");
-
-      withValues.put("to_publisher","1");
-
-      // inserting  content into database
-      String cid = contentModule.add(withValues);
-      logger.debug("id: "+cid);
-      //insert was not successfull
-      if(cid==null){
-
-        //How do we know that it was not succesful cause of a
-        //dupe, what if it failed cause of "No space left on device"?
-        //Or is there something I am missing? Wouldn't it be better
-        //to have an explicit dupe check and then insert? I have no
-        //idea what I am talking about. this comment is in case
-        //I forget to explicitely ask. -mh
-        deliver(req, res, mergeData, null, postingFormDupeTemplate);
-        return;
-      }
-
-      MirGlobal.abuse().logArticle(req.getRemoteAddr(), cid, new Date(), (String) req.getHeader("User-Agent"));
-
-      String[] to_topicsArr = mp.getParameterValues("to_topic");
-
-      if (to_topicsArr != null && to_topicsArr.length > 0) {
-        try{
-          DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
-          setTopic = true;
-        }
-        catch (Throwable e) {
-          logger.error("setting content_x_topic failed");
-          contentModule.deleteById(cid);
-          throw new ServletModuleFailure("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString(), e);
-        } //end try
-      } //end if
-
-      //if we're here all is ok... associate the media to the article
-      for(int i=0;i<mediaList.size();i++) {
-        Entity mediaEnt = (Entity)mediaList.elementAt(i);
-        DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());
-      }
-
-      EntityContent article = (EntityContent) contentModule.getById(cid);
-
-      try {
-        MirGlobal.abuse().checkArticle(article, req, res);
-        MirGlobal.localizer().openPostings().afterContentPosting(article);
-      }
-      catch (Throwable t) {
-        logger.error("Error while post-processing article: " + t.getMessage());
-      }
-    }
-    catch (Throwable e) {
-      Throwable cause = ExceptionFunctions.traceCauseException(e);
-
-      if (cause instanceof UnsupportedMediaFormatExc) {
-        throw new ServletModuleUserExc("media.unsupportedformat", new String[] {} );
-      }
-      throw new ServletModuleFailure(e);
-    }
-
-    deliver(req, res, mergeData, null, postingFormDoneTemplate);
-  }
-
-  /**
-   * Method for preparing and sending a content as an email message
-   */
-
-  public void mail(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
-  {
-    String aid = req.getParameter("mail_aid");
-    if (aid == null){
-      throw new ServletModuleExc("An article id must be specified in requests to email an article.  Something therefore went badly wrong....");
-    }
-
-    String to = req.getParameter("mail_to");
-    String from = req.getParameter("mail_from");
-    String from_name = req.getParameter("mail_from_name");
-    String comment = req.getParameter("mail_comment");
-    String mail_language = req.getParameter("mail_language");
-
-    Map mergeData = new HashMap();
-
-    if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
-
-      for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {
-        String pName=(String)theParams.nextElement();
-        if (pName.startsWith("mail_")){
-          mergeData.put( pName,req.getParameter(pName) );
-        }
-      }
-
-      deliver(req, res, mergeData, null, prepareMailTemplate);
-    }
-    else {
-      //run checks on to and from and mail_language to make sure no monkey business occurring
-      if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {
-        throw new ServletModuleExc("Invalid language");
-      }
-      if (to.indexOf('\n') != -1
-          || to.indexOf('\r') != -1
-          || to.indexOf(',') != -1) {
-        throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});
-      }
-      if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {
-        throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});
-      }
-
-
-      EntityContent contentEnt;
-      try{
-        contentEnt = (EntityContent)contentModule.getById(aid);
-      }
-      catch (Throwable e){
-        throw new ServletModuleFailure("Couldn't get content for article "+aid + ": " + e.getMessage(), e);
-      }
-      String producerStorageRoot=configuration.getString("Producer.StorageRoot");
-      String producerDocRoot=configuration.getString("Producer.DocRoot");
-      String publishPath = contentEnt.getValue("publish_path");
-      String txtFilePath = producerStorageRoot + producerDocRoot + "/" + mail_language +
-                                                                                                         publishPath + "/" + aid + ".txt";
-
-
-      File inputFile = new File(txtFilePath);
-      String content;
-
-      try{
-        FileReader in = new FileReader(inputFile);
-        StringWriter out = new StringWriter();
-        int c;
-        while ((c = in.read()) != -1)
-          out.write(c);
-        in.close();
-        content= out.toString();
-      }
-      catch (FileNotFoundException e){
-        throw new ServletModuleFailure("No text file found in " + txtFilePath, e);
-      }
-      catch (IOException e){
-        throw new ServletModuleFailure("Problem reading file in " + txtFilePath, e);
-      }
-      // add some headers
-      content = "To: " + to + "\nReply-To: "+ from + "\n" + content;
-      // put in the comment where it should go
-      if (comment != null) {
-        String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
-        try {
-          content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
-        }
-        catch (Throwable e){
-          throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
-        }
-      }
-      else{
-        try {
-          content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
-        }
-        catch (Throwable e){
-          throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
-        }
-      }
-
-      SMTPClient client=new SMTPClient();
-      try {
-        int reply;
-        client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
-
-        reply = client.getReplyCode();
-
-        if (!SMTPReply.isPositiveCompletion(reply)) {
-          client.disconnect();
-          throw new ServletModuleExc("SMTP server refused connection.");
-        }
-
-        client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
-
-        client.disconnect();
-        //mission accomplished
-        deliver(req, res, mergeData, null, sentMailTemplate);
-      }
-      catch(IOException e) {
-        if(client.isConnected()) {
-          try {
-            client.disconnect();
-          } catch(IOException f) {
-            // do nothing
-          }
-        }
-        throw new ServletModuleFailure(e);
-      }
-    }
-  }
-
-  /**
-   * Method for querying a lucene index
-   *
-   * @param req
-   * @param res
-   * @throws ServletModuleExc
-   * @throws ServletModuleUserExc
-   * @throws ServletModuleFailure
-   */
-
-  public void search(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    try {
-      final String[] search_variables = { "search_content", "search_boolean", "search_creator",
-          "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",
-          "search_submit", "search_back", "search_forward" };
-      HTTPRequestParser requestParser = new HTTPRequestParser(req);
-
-      int increment=10;
-
-      HttpSession session = req.getSession(false);
-
-      String queryString="";
-
-      Map mergeData = new HashMap();
-
-      KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted","search_date","webdb_create_formatted","webdb_create_formatted","webdb_create_formatted");
-      UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("","","","where","where");
-      TextSearchTerm creatorTerm = new TextSearchTerm("creator","search_creator","creator","creator","creator");
-      TextSearchTerm titleTerm = new TextSearchTerm("title","search_content","title","title","title");
-      TextSearchTerm descriptionTerm =  new TextSearchTerm("description","search_content","description","description","description");
-      ContentSearchTerm contentTerm = new ContentSearchTerm("content_data","search_content","content","","");
-      TopicSearchTerm topicTerm = new TopicSearchTerm();
-      ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
-      AudioSearchTerm audioTerm = new AudioSearchTerm();
-      VideoSearchTerm videoTerm = new VideoSearchTerm();
-
-      //make the query available to subsequent iterations
-
-      Iterator j = Arrays.asList(search_variables).iterator();
-      while (j.hasNext()) {
-        String variable = (String) j.next();
-
-        mergeData.put(variable, requestParser.getParameter(variable));
-      }
-
-      try{
-        mergeData.put("topics", topicsModule.getTopicsAsSimpleList());
-      }
-      catch(Throwable e) {
-        logger.debug("Can't get topics: " + e.toString());
-      }
-
-      String searchBackValue = req.getParameter("search_back");
-      String searchForwardValue = req.getParameter("search_forward");
-
-      if (searchBackValue != null){
-        int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();
-        int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()-increment;
-        if (newPosition<0)
-          newPosition=0;
-        if (newPosition >= totalHits)
-          newPosition=totalHits-1;
-        session.setAttribute("positionInResults",new Integer(newPosition));
-      }
-      else {
-        if (searchForwardValue != null){
-          int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();
-          int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment;
-          if (newPosition<0)
-            newPosition=0;
-          if (newPosition >= totalHits)
-            newPosition=totalHits-1;
-
-          session.setAttribute("positionInResults",new Integer(newPosition));
-        }
-        else {
-          String indexPath=configuration.getString("IndexPath");
-
-
-          String creatorFragment = creatorTerm.makeTerm(req);
-          if (creatorFragment != null){
-            queryString = queryString + " +" + creatorFragment;
-          }
-
-          // search title, description, and content for something
-          // the contentTerm uses param "search_boolean" to combine its terms
-          String contentFragment = contentTerm.makeTerm(req);
-          if (contentFragment != null){
-            logger.debug("contentFragment: " + contentFragment);
-            queryString = queryString + " +" + contentFragment;
-          }
-
-          String topicFragment = topicTerm.makeTerm(req);
-          if (topicFragment != null){
-            queryString = queryString + " +" + topicFragment;
-          }
-
-          String imagesFragment = imagesTerm.makeTerm(req);
-          if (imagesFragment != null){
-            queryString = queryString + " +" + imagesFragment;
-          }
-
-          String audioFragment = audioTerm.makeTerm(req);
-          if (audioFragment != null){
-            queryString = queryString + " +" + audioFragment;
-          }
-
-          String videoFragment = videoTerm.makeTerm(req);
-          if (videoFragment != null){
-            queryString = queryString + " +" + videoFragment;
-          }
-
-          if (queryString == null || queryString == ""){
-            queryString = "";
-          }
-          else{
-            try{
-              Searcher searcher = null;
-              try {
-                searcher = new IndexSearcher(indexPath);
-              }
-              catch(IOException e) {
-                logger.debug("Can't open indexPath: " + indexPath);
-                throw new ServletModuleExc("Problem with Search Index! : "+ e.toString());
-              }
-
-              Query query = null;
-              try {
-                query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
-              }
-              catch(Exception e) {
-                searcher.close();
-                logger.debug("Query don't parse: " + queryString);
-                throw new ServletModuleExc("Problem with Query String! (was '"+queryString+"')");
-              }
-
-              Hits hits = null;
-              try {
-                hits = searcher.search(query);
-              }
-              catch(IOException e) {
-                searcher.close();
-                logger.debug("Can't get hits: " + e.toString());
-                throw new ServletModuleExc("Problem getting hits!");
-              }
-
-              int start = 0;
-              int end = hits.length();
-
-              String sortBy=req.getParameter("search_sort");
-              if (sortBy == null || sortBy.equals("")){
-                throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
-              }
-
-              // here is where the documents will go for storage across sessions
-              ArrayList theDocumentsSorted = new ArrayList();
-
-              if (sortBy.equals("score")){
-                for(int i = start; i < end; i++) {
-                  theDocumentsSorted.add(hits.doc(i));
-                }
-              }
-              else{
-                // then we'll sort by date!
-                Map dateToPosition = new HashMap(end,1.0F); //we know how big it will be
-                for(int i = start; i < end; i++) {
-                  String creationDate=(hits.doc(i)).get("creationDate");
-                  // do a little dance in case two contents created at the same second!
-                  if (dateToPosition.containsKey(creationDate)){
-                    ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
-                  }
-                  else{
-                    ArrayList thePositions = new ArrayList();
-                    thePositions.add(new Integer(i));
-                    dateToPosition.put(creationDate,thePositions);
-                  }
-                }
-                Set keys = dateToPosition.keySet();
-                ArrayList keyList= new ArrayList(keys);
-                Collections.sort(keyList);
-                if (sortBy.equals("date_desc")){
-                  Collections.reverse(keyList);
-                }
-                else{
-                  if (!sortBy.equals("date_asc")){
-                    throw new ServletModuleExc("don't know how to sort by: "+ sortBy);
-                  }
-                }
-                ListIterator keyTraverser = keyList.listIterator();
-                while (keyTraverser.hasNext()){
-                  ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next()));
-                  ListIterator positionsTraverser=positions.listIterator();
-                  while (positionsTraverser.hasNext()){
-                    theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue()));
-                  }
-                }
-              }
-
-              try{
-                searcher.close();
-              }
-              catch (IOException e){
-                logger.debug("Can't close searcher: " + e.toString());
-                throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
-              }
-
-
-              session.removeAttribute("numberOfHits");
-              session.removeAttribute("theDocumentsSorted");
-              session.removeAttribute("positionInResults");
-
-              session.setAttribute("numberOfHits",new Integer(end));
-              session.setAttribute("theDocumentsSorted",theDocumentsSorted);
-              session.setAttribute("positionInResults",new Integer(0));
-
-            }
-            catch (IOException e){
-              logger.debug("Can't close searcher: " + e.toString());
-              throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
-            }
-          }
-        }
-      }
-
-      try {
-        ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted");
-        if (theDocs != null){
-
-          mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString());
-          List theHits = new Vector();
-          int pIR=((Integer)session.getAttribute("positionInResults")).intValue();
-          int terminus;
-          int numHits=((Integer)session.getAttribute("numberOfHits")).intValue();
-
-          if (!(pIR+increment>=numHits)){
-            mergeData.put("hasNext","y");
-          }
-          else {
-            mergeData.put("hasNext", null);
-          }
-          if (pIR>0){
-            mergeData.put("hasPrevious","y");
-          }
-          else {
-            mergeData.put("hasPrevious", null);
-          }
-
-          if ((pIR+increment)>numHits){
-            terminus=numHits;
-          }
-          else {
-            terminus=pIR+increment;
-          }
-          for(int i = pIR; i < terminus; i++) {
-            Map h = new HashMap();
-            Document theHit = (Document)theDocs.get(i);
-            whereTerm.returnMeta(h,theHit);
-            creatorTerm.returnMeta(h,theHit);
-            titleTerm.returnMeta(h,theHit);
-            descriptionTerm.returnMeta(h,theHit);
-            dateTerm.returnMeta(h,theHit);
-            imagesTerm.returnMeta(h,theHit);
-            audioTerm.returnMeta(h,theHit);
-            videoTerm.returnMeta(h,theHit);
-            theHits.add(h);
-          }
-          mergeData.put("hits",theHits);
-        }
-      }
-      catch (Throwable e) {
-        logger.error("Can't iterate over hits: " + e.toString());
-
-        throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
-      }
-
-      mergeData.put("queryString",queryString);
-
-      deliver(req, res, mergeData, null, searchResultsTemplate);
-    }
-    catch (NullPointerException n){
-      throw new ServletModuleFailure("Null Pointer: "+n.toString(), n);
-    }
-  }
-
-  /*
-   * Method for dynamically generating a pdf using iText
-   */
-
-
-  public void getpdf(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    String ID_REQUEST_PARAM = "id";
-    try {
-        String idParam = req.getParameter(ID_REQUEST_PARAM);
-        if (idParam != null) {
-         ByteArrayOutputStream out = new ByteArrayOutputStream();
-          PDFGenerator pdfMaker = new PDFGenerator(out);
-         
-         RE re = new RE("[0-9]+");
-         
-         
-         REMatch[] idMatches=re.getAllMatches(idParam);
-         
-         if (idMatches.length > 1){
-           pdfMaker.addLine();
-           for (int i = 0; i < idMatches.length; i++){
-             REMatch aMatch = idMatches[i];
-             String id=aMatch.toString();
-             EntityContent contentEnt = (EntityContent)contentModule.getById(id);
-             pdfMaker.addIndexItem(contentEnt);
-             
-           }
-         }
-
-         for (int i = 0; i < idMatches.length; i++){
-           REMatch aMatch = idMatches[i];
-           
-           String id=aMatch.toString();
-           
-           EntityContent contentEnt = (EntityContent)contentModule.getById(id);
-           pdfMaker.add(contentEnt);
-           
-         }
-         
-         pdfMaker.stop();
-         res.setContentType("application/pdf");
-         byte[] content = out.toByteArray();
-          res.setContentLength(content.length);
-         res.getOutputStream().write(content);
-          res.getOutputStream().flush();
-
-       }
-       else {
-          throw new ServletModuleExc("Missing id.");
-        }
-    }
-    catch (Throwable t) {
-      logger.error(t.toString());
-      throw new ServletModuleFailure(t);
-    }
-
-  }
-
-
-  /*
-   * Method for dynamically generating a pdf from a fo file
-   * (deprecated until fop gets its act together regarding floats)
-   */
-
-  /*
-  public void getpdf(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    String ID_REQUEST_PARAM = "id";
-    String language = req.getParameter("language");
-    String generateFO=configuration.getString("GenerateFO");
-    String generatePDF=configuration.getString("GeneratePDF");
-
-
-    //don't do anything if we are not making FO files, or if we are
-    //pregenerating PDF's
-    if (generateFO.equals("yes") && generatePDF.equals("no")){
-      //fop complains unless you do the logging this way
-      org.apache.log.Logger log = null;
-      Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
-      log = hierarchy.getLoggerFor("fop");
-      log.setPriority(Priority.WARN);
-
-      String producerStorageRoot=configuration.getString("Producer.StorageRoot");
-      String producerDocRoot=configuration.getString("Producer.DocRoot");
-      //      String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
-      String xslSheet=configuration.getString("Producer.HTML2FOStyleSheet");
-      try {
-        String idParam = req.getParameter(ID_REQUEST_PARAM);
-        if (idParam != null) {
-          EntityContent contentEnt =
-            (EntityContent)contentModule.getById(idParam);
-          String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date"));
-          String foFile;
-
-          if (language == null){
-            foFile = producerStorageRoot + producerDocRoot + "/"
-              + publishPath  + idParam + ".fo";
-          }
-          else{
-            foFile = producerStorageRoot + producerDocRoot + "/"
-              + language + publishPath  + idParam + ".fo";
-          }
-          logger.debug("USING FILES" + foFile + " and " + xslSheet);
-          XSLTInputHandler input = new XSLTInputHandler(new File(foFile),
-                                                        new File(xslSheet));
-
-          ByteArrayOutputStream out = new ByteArrayOutputStream();
-          res.setContentType("application/pdf");
-
-          Driver driver = new Driver();
-          driver.setLogger(log);
-          driver.setRenderer(Driver.RENDER_PDF);
-          driver.setOutputStream(out);
-          driver.render(input.getParser(), input.getInputSource());
-
-          byte[] content = out.toByteArray();
-          res.setContentLength(content.length);
-          res.getOutputStream().write(content);
-          res.getOutputStream().flush();
-        }
-        else {
-          throw new ServletModuleExc("Missing id.");
-        }
-      }
-      catch (Throwable t) {
-        logger.error(t.toString());
-
-        throw new ServletModuleFailure(t);
-      }
-    }
-    else {
-      throw new ServletModuleExc("Can't generate a PDF because the config tells me not to.");
-    }
-  }
-  */
-  protected String createOneTimePasswd(){
-    Random r = new Random();
-    int random = r.nextInt();
-    long l = System.currentTimeMillis();
-    l = (l*l*l*l)/random;
-    if(l<0) l = l * -1;
-    String returnString = ""+l;
-
-    return returnString.substring(5);
-  }
-
-
-  /* this is an overwritten method of ServletModule in order
-     to use different bundles for open and admin */
-/*  public void deliver(HttpServletRequest req, HttpServletResponse res,
-                      TemplateModelRoot rtm, TemplateModelRoot popups,
-                      String templateFilename) throws ServletModuleFailure
-  {
-  }
-*/
-  public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
-      throws ServletModuleFailure {
-    try {
-      deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
-      throws ServletModuleFailure {
-    try {
-      Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open");
-      responseData.put("data", aData);
-      responseData.put("extra", anExtra);
-
-
-      Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
-      generator.generate(anOutputWriter, responseData, logger.asPrintWriter(logger.INFO_MESSAGE));
-
-      anOutputWriter.close();
-    }
-    catch (Throwable e) {
-      logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
-
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
-    try {
-      logger.error("error: " + anException);
-      anException.printStackTrace();
-      Map data = new HashMap();
-
-      data.put("errorstring", anException.getMessage());
-      data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
-
-      deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
-                               PrintWriter out, ServletModuleUserExc anException) {
-    try {
-      logger.warn("user error: " + anException.getMessage());
-      Map data = new HashMap();
-
-      MessageResources messages = MessageResources.getMessageResources("bundles.open");
-      data.put("errorstring",
-              messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters())
-          );
-      data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
-
-      deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.servlet;\r
+\r
+import java.io.ByteArrayOutputStream;\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileReader;\r
+import java.io.IOException;\r
+import java.io.PrintWriter;\r
+import java.io.StringWriter;\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.Collections;\r
+import java.util.Date;\r
+import java.util.Enumeration;\r
+import java.util.GregorianCalendar;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.ListIterator;\r
+import java.util.Map;\r
+import java.util.Set;\r
+import java.util.Vector;\r
+import java.util.*;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+import javax.servlet.http.HttpSession;\r
+import javax.servlet.http.HttpUtils;\r
+\r
+import gnu.regexp.RE;\r
+import gnu.regexp.REMatch;\r
+import gnu.regexp.REMatchEnumeration;\r
+import gnu.regexp.REException;\r
+\r
+import org.apache.commons.net.smtp.SMTPClient;\r
+import org.apache.commons.net.smtp.SMTPReply;\r
+import org.apache.log.Hierarchy;\r
+import org.apache.log.Priority;\r
+import org.apache.lucene.analysis.standard.StandardAnalyzer;\r
+import org.apache.lucene.document.Document;\r
+import org.apache.lucene.queryParser.QueryParser;\r
+import org.apache.lucene.search.Hits;\r
+import org.apache.lucene.search.IndexSearcher;\r
+import org.apache.lucene.search.Query;\r
+import org.apache.lucene.search.Searcher;\r
+import org.apache.struts.util.MessageResources;\r
+\r
+import mir.entity.Entity;\r
+import mir.entity.EntityList;\r
+import mir.generator.Generator;\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.FileHandler;\r
+import mir.misc.StringUtil;\r
+import mir.misc.WebdbMultipartRequest;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.servlet.ServletModuleFailure;\r
+import mir.servlet.ServletModuleUserExc;\r
+import mir.storage.StorageObjectFailure;\r
+import mir.util.*;\r
+import mircoders.pdf.PDFGenerator;\r
+import mir.session.*;\r
+import mir.util.HTTPRequestParser;\r
+import mir.util.StringRoutines;\r
+import mircoders.entity.EntityComment;\r
+import mircoders.entity.EntityContent;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.media.*;\r
+import mircoders.media.UnsupportedMediaFormatExc;\r
+import mircoders.module.ModuleComment;\r
+import mircoders.module.ModuleContent;\r
+import mircoders.module.ModuleImages;\r
+import mircoders.module.ModuleTopics;\r
+import mircoders.search.AudioSearchTerm;\r
+import mircoders.search.ContentSearchTerm;\r
+import mircoders.search.ImagesSearchTerm;\r
+import mircoders.search.KeywordSearchTerm;\r
+import mircoders.search.TextSearchTerm;\r
+import mircoders.search.TopicSearchTerm;\r
+import mircoders.search.UnIndexedSearchTerm;\r
+import mircoders.search.VideoSearchTerm;\r
+import mircoders.storage.DatabaseComment;\r
+import mircoders.storage.DatabaseContent;\r
+import mircoders.storage.DatabaseContentToMedia;\r
+import mircoders.storage.DatabaseCommentToMedia;\r
+import mircoders.storage.DatabaseContentToTopics;\r
+import mircoders.storage.DatabaseImages;\r
+import mircoders.storage.DatabaseLanguage;\r
+import mircoders.storage.DatabaseTopics;\r
+\r
+/*\r
+ *  ServletModuleOpenIndy -\r
+ *   is the open-access-servlet, which is responsible for\r
+ *    adding comments to articles &\r
+ *    open-postings to the newswire\r
+ *\r
+ * @author mir-coders group\r
+ * @version $Id: ServletModuleOpenIndy.java,v 1.74 2003/04/16 03:26:46 zapata Exp $\r
+ *\r
+ */\r
+\r
+public class ServletModuleOpenIndy extends ServletModule\r
+{\r
+\r
+  private String        commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;\r
+  private String        postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;\r
+  private String        searchResultsTemplate;\r
+  private String        prepareMailTemplate,sentMailTemplate;\r
+  private ModuleContent contentModule;\r
+  private ModuleComment commentModule;\r
+  private ModuleImages  imageModule;\r
+  private ModuleTopics  topicsModule;\r
+  private String        directOp ="yes";\r
+  // Singelton / Kontruktor\r
+  private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();\r
+  public static ServletModule getInstance() { return instance; }\r
+\r
+  private ServletModuleOpenIndy() {\r
+    super();\r
+    try {\r
+      logger = new LoggerWrapper("ServletModule.OpenIndy");\r
+\r
+      commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");\r
+      commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");\r
+      commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");\r
+\r
+      postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");\r
+      postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");\r
+      postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");\r
+\r
+      searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");\r
+      prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");\r
+      sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");\r
+      directOp = configuration.getString("DirectOpenposting").toLowerCase();\r
+      commentModule = new ModuleComment(DatabaseComment.getInstance());\r
+      mainModule = commentModule;\r
+      contentModule = new ModuleContent(DatabaseContent.getInstance());\r
+      topicsModule = new ModuleTopics(DatabaseTopics.getInstance());\r
+      imageModule = new ModuleImages(DatabaseImages.getInstance());\r
+      defaultAction="addposting";\r
+    }\r
+    catch (StorageObjectFailure e) {\r
+      logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Method to return an "apology" when open postings are disabled\r
+   *\r
+   * @param aRequest\r
+   * @param aResponse\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleUserExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+  public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
+    deliver(aRequest, aResponse, (Map) null, null,\r
+       configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));\r
+  }\r
+\r
+  /**\r
+   *  Method for making a comment\r
+   */\r
+\r
+  public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
+    if (MirGlobal.abuse().getOpenPostingDisabled()) {\r
+      openPostingDisabled(req, res);\r
+\r
+      return;\r
+    }\r
+\r
+    String aid = req.getParameter("aid"); // the article id the comment will belong to\r
+\r
+    if (aid != null && !aid.equals("")) {\r
+      try {\r
+        Map mergeData = new HashMap();\r
+\r
+        // onetimepasswd\r
+        if (MirGlobal.abuse().getOpenPostingPassword()) {\r
+          String passwd = this.createOneTimePasswd();\r
+          HttpSession session = req.getSession(false);\r
+          session.setAttribute("passwd", passwd);\r
+          mergeData.put("passwd", passwd);\r
+        }\r
+        else {\r
+          mergeData.put("passwd", (String)null);\r
+        }\r
+        mergeData.put("aid", aid);\r
+\r
+        Map extraInfo = new HashMap();\r
+        extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());\r
+\r
+        deliver(req, res, mergeData, extraInfo, commentFormTemplate);\r
+      }\r
+      catch (Throwable t) {\r
+        throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);\r
+      }\r
+    }\r
+    else\r
+      throw new ServletModuleExc("aid not set!");\r
+  }\r
+\r
+  /**\r
+   *  Method for inserting a comment into the Database and delivering\r
+   *  the commentDone Page\r
+   */\r
+\r
+  public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
+    if (MirGlobal.abuse().getOpenPostingDisabled()) {\r
+      openPostingDisabled(req, res);\r
+\r
+      return;\r
+    }\r
+\r
+    String aid = req.getParameter("to_media"); // the article id the comment will belong to\r
+    if (aid != null && !aid.equals("")) {\r
+      // ok, collecting data from form\r
+      try {\r
+        Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());\r
+\r
+        //no html in comments(for now)\r
+        for (Iterator i = withValues.keySet().iterator(); i.hasNext(); ) {\r
+          String k = (String) i.next();\r
+          String v = (String) withValues.get(k);\r
+\r
+          withValues.put(k, StringUtil.removeHTMLTags(v));\r
+        }\r
+        withValues.put("is_published", "1");\r
+        withValues.put("to_comment_status", "1");\r
+        withValues.put("is_html", "0");\r
+\r
+        //checking the onetimepasswd\r
+        HttpSession session = req.getSession(false);\r
+        String sessionPasswd = (String) session.getAttribute("passwd");\r
+        if (sessionPasswd != null) {\r
+          String passwd = req.getParameter("passwd");\r
+          if (passwd == null || passwd.length() == 0) {\r
+            throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});\r
+          }\r
+          if (!sessionPasswd.equals(passwd)) {\r
+            throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});\r
+          }\r
+          session.invalidate();\r
+        }\r
+\r
+        String id = mainModule.add(withValues);\r
+\r
+        SimpleResponse response = new SimpleResponse();\r
+        response.setResponseGenerator(commentFormDoneTemplate);\r
+\r
+        if (id == null) {\r
+          deliver(req, res, (Map)null, null, commentFormDupeTemplate);\r
+        }\r
+        else {\r
+          DatabaseContent.getInstance().setUnproduced("id=" + aid);\r
+\r
+          try {\r
+            EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);\r
+            MirGlobal.localizer().openPostings().afterCommentPosting(comment);\r
+            MirGlobal.abuse().checkComment(\r
+                comment, new HTTPAdapters.HTTPRequestAdapter(req), res);\r
+          }\r
+          catch (Throwable t) {\r
+            throw new ServletModuleExc(t.getMessage());\r
+          }\r
+        }\r
+\r
+        // redirecting to url\r
+        // should implement back to article\r
+        deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());\r
+      }\r
+      catch (Throwable e) {\r
+        throw new ServletModuleFailure(e);\r
+      }\r
+    }\r
+    else\r
+      throw new ServletModuleExc("aid not set!");\r
+\r
+  }\r
+\r
+  /**\r
+   *  Method for delivering the form-Page for open posting\r
+   */\r
+\r
+  public void addposting(HttpServletRequest req, HttpServletResponse res)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
+  {\r
+    try {\r
+      if (MirGlobal.abuse().getOpenPostingDisabled()) {\r
+        openPostingDisabled(req, res);\r
+\r
+        return;\r
+      }\r
+\r
+      Map mergeData = new HashMap();\r
+\r
+      // onetimepasswd\r
+      if (MirGlobal.abuse().getOpenPostingPassword()) {\r
+        String passwd = generateOnetimePassword();\r
+        HttpSession session = req.getSession(false);\r
+        session.setAttribute("passwd", passwd);\r
+        mergeData.put("passwd", passwd);\r
+      }\r
+      else {\r
+        mergeData.put("passwd", (String)null);\r
+      }\r
+\r
+      String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");\r
+      String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");\r
+      String numOfMedia = req.getParameter("medianum");\r
+\r
+      if (numOfMedia == null || numOfMedia.equals("")) {\r
+        numOfMedia = defaultMedia;\r
+      }\r
+      else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {\r
+        numOfMedia = maxMedia;\r
+      }\r
+\r
+      int mediaNum = Integer.parseInt(numOfMedia);\r
+      List mediaFields = new Vector();\r
+      for (int i = 0; i < mediaNum; i++) {\r
+        Integer mNum = new Integer(i + 1);\r
+        mediaFields.add(mNum.toString());\r
+      }\r
+      mergeData.put("medianum", numOfMedia);\r
+      mergeData.put("mediafields", mediaFields);\r
+      mergeData.put("to_topic", null);\r
+\r
+      Map extraInfo = new HashMap();\r
+      extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());\r
+      extraInfo.put("themenPopupData", topicsModule.getTopicsAsSimpleList());\r
+\r
+      extraInfo.put("topics", topicsModule.getTopicsList());\r
+      deliver(req, res, mergeData, extraInfo, postingFormTemplate);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  /**\r
+   *  Method for inserting an open posting into the Database and delivering\r
+   *  the postingDone Page\r
+   */\r
+\r
+  public void insposting(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
+  {\r
+    if (MirGlobal.abuse().getOpenPostingDisabled()) {\r
+      openPostingDisabled(req, res);\r
+\r
+      return;\r
+    }\r
+\r
+    Map mergeData = new HashMap();\r
+    boolean setMedia=false;\r
+    boolean setTopic = false;\r
+\r
+    try {\r
+\r
+      WebdbMultipartRequest mp = null;\r
+      EntityList mediaList = null;\r
+      try {\r
+        // new MediaRequest, "1" is the id for the openPosting user\r
+        MediaRequest mediaReq = new MediaRequest("1", true);\r
+        mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);\r
+        mediaList = mediaReq.getEntityList();\r
+      }\r
+      catch (Throwable e) {\r
+        throw new ServletModuleFailure(e);\r
+      }\r
+\r
+      Map withValues = mp.getParameters();\r
+\r
+      //checking the onetimepasswd\r
+      HttpSession session = req.getSession(false);\r
+      String sessionPasswd = (String) session.getAttribute("passwd");\r
+      if (sessionPasswd != null){\r
+        String passwd = (String) withValues.get("passwd");\r
+\r
+        if ( passwd == null || passwd.length()==0) {\r
+          throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});\r
+        }\r
+        if (!sessionPasswd.equals(passwd)) {\r
+          throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});\r
+        }\r
+        session.invalidate();\r
+      }\r
+\r
+      if ((((String)withValues.get("title")).length() == 0) ||\r
+          (((String)withValues.get("description")).length() == 0) ||\r
+          (((String)withValues.get("content_data")).length() == 0))\r
+        throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});\r
+\r
+      // call the routines that escape html\r
+\r
+      for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){\r
+        String k=(String)i.next();\r
+        String v=(String)withValues.get(k);\r
+\r
+        if (k.equals("content_data")){\r
+          //this doesn't quite work yet, so for now, all html goes\r
+          //withValues.put(k,StringUtil.approveHTMLTags(v));\r
+          withValues.put(k,StringUtil.deleteForbiddenTags(v));\r
+        }\r
+        else if (k.equals("description")) {\r
+          String tmp = StringUtil.deleteForbiddenTags(v);\r
+          withValues.put(k,StringUtil.deleteHTMLTableTags(tmp));\r
+        }\r
+        else {\r
+          withValues.put(k,StringUtil.removeHTMLTags(v));\r
+        }\r
+\r
+      }\r
+\r
+      withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
+      withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));\r
+      withValues.put("is_produced", "0");\r
+      withValues.put("is_published","1");\r
+      if (directOp.equals("yes"))\r
+        withValues.put("to_article_type","1");\r
+\r
+      withValues.put("to_publisher","1");\r
+\r
+      // inserting  content into database\r
+      String cid = contentModule.add(withValues);\r
+      logger.debug("id: "+cid);\r
+      //insert was not successfull\r
+      if(cid==null){\r
+\r
+        //How do we know that it was not succesful cause of a\r
+        //dupe, what if it failed cause of "No space left on device"?\r
+        //Or is there something I am missing? Wouldn't it be better\r
+        //to have an explicit dupe check and then insert? I have no\r
+        //idea what I am talking about. this comment is in case\r
+        //I forget to explicitely ask. -mh\r
+        deliver(req, res, mergeData, null, postingFormDupeTemplate);\r
+        return;\r
+      }\r
+\r
+      String[] to_topicsArr = mp.getParameterValues("to_topic");\r
+\r
+      if (to_topicsArr != null && to_topicsArr.length > 0) {\r
+        try{\r
+          DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);\r
+          setTopic = true;\r
+        }\r
+        catch (Throwable e) {\r
+          logger.error("setting content_x_topic failed");\r
+          contentModule.deleteById(cid);\r
+          throw new ServletModuleFailure("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString(), e);\r
+        } //end try\r
+      } //end if\r
+\r
+      //if we're here all is ok... associate the media to the article\r
+      for(int i=0;i<mediaList.size();i++) {\r
+        Entity mediaEnt = (Entity)mediaList.elementAt(i);\r
+        DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());\r
+      }\r
+\r
+      EntityContent article = (EntityContent) contentModule.getById(cid);\r
+\r
+      try {\r
+        MirGlobal.abuse().checkArticle(article, req, res);\r
+        MirGlobal.localizer().openPostings().afterContentPosting(article);\r
+      }\r
+      catch (Throwable t) {\r
+        logger.error("Error while post-processing article: " + t.getMessage());\r
+      }\r
+    }\r
+    catch (Throwable e) {\r
+      Throwable cause = ExceptionFunctions.traceCauseException(e);\r
+\r
+      if (cause instanceof UnsupportedMediaFormatExc) {\r
+        throw new ServletModuleUserExc("media.unsupportedformat", new String[] {} );\r
+      }\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+\r
+    deliver(req, res, mergeData, null, postingFormDoneTemplate);\r
+  }\r
+\r
+  /**\r
+   * Routine for innitiation tha d\r
+   *\r
+   * @param aRequest\r
+   * @param aResponse\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleUserExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+/*\r
+  public void comment(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
+    try {\r
+      if (MirGlobal.abuse().getOpenPostingDisabled()) {\r
+        openPostingDisabled(aRequest, aResponse);\r
+\r
+        return;\r
+      }\r
+\r
+      Request request = new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest, 1000000, "/tmp"));\r
+      Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());\r
+      SimpleResponse response = new SimpleResponse(\r
+          ServletHelper.makeGenerationData(new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open"));\r
+\r
+      Iterator i = DatabaseContent.getInstance().getFields().iterator();\r
+      while (i.hasNext()) {\r
+        response.setResponseValue((String) i.next(), null);\r
+      }\r
+\r
+      MirGlobal.localizer().openPostings().initializeCommentPosting(request, session, response);\r
+\r
+      ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());\r
+    }\r
+    catch (Throwable t) {\r
+      t.printStackTrace(System.out);\r
+      System.out.println("comment: " + t.toString());\r
+      throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);\r
+    }\r
+  }\r
+\r
+  public void processcomment(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
+    try {\r
+      if (MirGlobal.abuse().getOpenPostingDisabled()) {\r
+        openPostingDisabled(aRequest, aResponse);\r
+\r
+        return;\r
+      }\r
+\r
+      Request request = new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest, 1000000, "/tmp"));\r
+      Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());\r
+      SimpleResponse response = new SimpleResponse(\r
+          ServletHelper.makeGenerationData(new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open"));\r
+      Map commentFields = new HashMap();\r
+\r
+      Iterator i = DatabaseContent.getInstance().getFields().iterator();\r
+      while (i.hasNext()) {\r
+        String field = (String) i.next();\r
+        response.setResponseValue(field, request.getParameter(field));\r
+        if (request.getParameter(field)!=null) {\r
+          commentFields.put(field, request.getParameter(field));\r
+        }\r
+      }\r
+\r
+      List validationErrors = MirGlobal.localizer().openPostings().validateCommentPosting(request, session);\r
+\r
+      if (validationErrors != null && validationErrors.size()>0) {\r
+        MirGlobal.localizer().openPostings().processCommentPosting(request, session, response);\r
+\r
+        ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());\r
+      }\r
+      else {\r
+        EntityComment comment = (EntityComment) commentModule.createNew ();\r
+        comment.setValues(commentFields);\r
+        MirGlobal.abuse().checkComment(comment, aRequest, aResponse);\r
+        MirGlobal.localizer().openPostings().finishCommentPosting(request, session, comment);\r
+\r
+        String id = comment.insert();\r
+        if(id==null){\r
+          MirGlobal.localizer().openPostings().afterDuplicateCommentPosting(request, session, response, comment);\r
+\r
+          logger.info("Dupe comment rejected");\r
+\r
+          ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());\r
+        }\r
+        else {\r
+          // media\r
+          List mediaItems = new Vector();\r
+          i = request.getUploadedFiles().iterator();\r
+          while (i.hasNext()) {\r
+            UploadedFile file = (UploadedFile) i.next();\r
+            Entity mediaItem = MediaUploadProcessor.processMediaUpload(file);\r
+            DatabaseCommentToMedia.getInstance().addMedia(comment.getId(), mediaItem.getId());\r
+          }\r
+\r
+          MirGlobal.localizer().openPostings().afterCommentPosting(request, session, response, comment);\r
+\r
+          MirGlobal.abuse().logComment(aRequest.getRemoteAddr(), id, new Date(), (String) aRequest.getHeader("User-Agent"));\r
+          DatabaseContent.getInstance().setUnproduced("id=" + comment.getValue("to_media"));\r
+          logger.info("Comment posted");\r
+          ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());\r
+        }\r
+      }\r
+    }\r
+    catch (Throwable t) {\r
+      ExceptionFunctions.traceCauseException(t).printStackTrace();\r
+\r
+      throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);\r
+    }\r
+  }\r
+*/\r
+\r
+  private static final String SESSION_REQUEST_KEY="sessionid";\r
+\r
+  public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
+\r
+    try {\r
+      Request request = new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest, 1000000, "/tmp"));\r
+\r
+      if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&\r
+          !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))\r
+        aRequest.getSession().invalidate();\r
+\r
+      Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());\r
+\r
+      SimpleResponse response = new SimpleResponse(\r
+          ServletHelper.makeGenerationData(new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)},\r
+             "bundles.open"));\r
+\r
+      response.setResponseValue("actionURL", aResponse.encodeURL(HttpUtils.getRequestURL(aRequest).toString())+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());\r
+\r
+      SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);\r
+\r
+      handler.processRequest(request, session, response);\r
+      ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());\r
+    }\r
+    catch (Throwable t) {\r
+      logger.error(t.toString());\r
+      t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));\r
+\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Method for preparing and sending a content as an email message\r
+   */\r
+\r
+  public void mail(HttpServletRequest req, HttpServletResponse res)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
+  {\r
+    String aid = req.getParameter("mail_aid");\r
+    if (aid == null){\r
+      throw new ServletModuleExc("An article id must be specified in requests to email an article.  Something therefore went badly wrong....");\r
+    }\r
+\r
+    String to = req.getParameter("mail_to");\r
+    String from = req.getParameter("mail_from");\r
+    String from_name = req.getParameter("mail_from_name");\r
+    String comment = req.getParameter("mail_comment");\r
+    String mail_language = req.getParameter("mail_language");\r
+\r
+    Map mergeData = new HashMap();\r
+\r
+    if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){\r
+\r
+      for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {\r
+        String pName=(String)theParams.nextElement();\r
+        if (pName.startsWith("mail_")){\r
+          mergeData.put( pName,req.getParameter(pName) );\r
+        }\r
+      }\r
+\r
+      deliver(req, res, mergeData, null, prepareMailTemplate);\r
+    }\r
+    else {\r
+      //run checks on to and from and mail_language to make sure no monkey business occurring\r
+      if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {\r
+        throw new ServletModuleExc("Invalid language");\r
+      }\r
+      if (to.indexOf('\n') != -1\r
+          || to.indexOf('\r') != -1\r
+          || to.indexOf(',') != -1) {\r
+        throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});\r
+      }\r
+      if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {\r
+        throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});\r
+      }\r
+\r
+\r
+      EntityContent contentEnt;\r
+      try{\r
+        contentEnt = (EntityContent)contentModule.getById(aid);\r
+      }\r
+      catch (Throwable e){\r
+        throw new ServletModuleFailure("Couldn't get content for article "+aid + ": " + e.getMessage(), e);\r
+      }\r
+      String producerStorageRoot=configuration.getString("Producer.StorageRoot");\r
+      String producerDocRoot=configuration.getString("Producer.DocRoot");\r
+      String publishPath = contentEnt.getValue("publish_path");\r
+      String txtFilePath = producerStorageRoot + producerDocRoot + "/" + mail_language +\r
+                                                                                                         publishPath + "/" + aid + ".txt";\r
+\r
+\r
+      File inputFile = new File(txtFilePath);\r
+      String content;\r
+\r
+      try{\r
+        FileReader in = new FileReader(inputFile);\r
+        StringWriter out = new StringWriter();\r
+        int c;\r
+        while ((c = in.read()) != -1)\r
+          out.write(c);\r
+        in.close();\r
+        content= out.toString();\r
+      }\r
+      catch (FileNotFoundException e){\r
+        throw new ServletModuleFailure("No text file found in " + txtFilePath, e);\r
+      }\r
+      catch (IOException e){\r
+        throw new ServletModuleFailure("Problem reading file in " + txtFilePath, e);\r
+      }\r
+      // add some headers\r
+      content = "To: " + to + "\nReply-To: "+ from + "\n" + content;\r
+      // put in the comment where it should go\r
+      if (comment != null) {\r
+        String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;\r
+        try {\r
+          content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);\r
+        }\r
+        catch (Throwable e){\r
+          throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);\r
+        }\r
+      }\r
+      else{\r
+        try {\r
+          content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");\r
+        }\r
+        catch (Throwable e){\r
+          throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);\r
+        }\r
+      }\r
+\r
+      SMTPClient client=new SMTPClient();\r
+      try {\r
+        int reply;\r
+        client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));\r
+\r
+        reply = client.getReplyCode();\r
+\r
+        if (!SMTPReply.isPositiveCompletion(reply)) {\r
+          client.disconnect();\r
+          throw new ServletModuleExc("SMTP server refused connection.");\r
+        }\r
+\r
+        client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);\r
+\r
+        client.disconnect();\r
+        //mission accomplished\r
+        deliver(req, res, mergeData, null, sentMailTemplate);\r
+      }\r
+      catch(IOException e) {\r
+        if(client.isConnected()) {\r
+          try {\r
+            client.disconnect();\r
+          } catch(IOException f) {\r
+            // do nothing\r
+          }\r
+        }\r
+        throw new ServletModuleFailure(e);\r
+      }\r
+    }\r
+  }\r
+\r
+\r
+\r
+  /**\r
+   * Method for querying a lucene index\r
+   *\r
+   * @param req\r
+   * @param res\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleUserExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+\r
+  public void search(HttpServletRequest req, HttpServletResponse res)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
+    try {\r
+      final String[] search_variables = { "search_content", "search_boolean", "search_creator",\r
+          "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",\r
+          "search_submit", "search_back", "search_forward" };\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(req);\r
+\r
+      int increment=10;\r
+\r
+      HttpSession session = req.getSession(false);\r
+\r
+      String queryString="";\r
+\r
+      Map mergeData = new HashMap();\r
+\r
+      KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted","search_date","webdb_create_formatted","webdb_create_formatted","webdb_create_formatted");\r
+      UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("","","","where","where");\r
+      TextSearchTerm creatorTerm = new TextSearchTerm("creator","search_creator","creator","creator","creator");\r
+      TextSearchTerm titleTerm = new TextSearchTerm("title","search_content","title","title","title");\r
+      TextSearchTerm descriptionTerm =  new TextSearchTerm("description","search_content","description","description","description");\r
+      ContentSearchTerm contentTerm = new ContentSearchTerm("content_data","search_content","content","","");\r
+      TopicSearchTerm topicTerm = new TopicSearchTerm();\r
+      ImagesSearchTerm imagesTerm = new ImagesSearchTerm();\r
+      AudioSearchTerm audioTerm = new AudioSearchTerm();\r
+      VideoSearchTerm videoTerm = new VideoSearchTerm();\r
+\r
+      //make the query available to subsequent iterations\r
+\r
+      Iterator j = Arrays.asList(search_variables).iterator();\r
+      while (j.hasNext()) {\r
+        String variable = (String) j.next();\r
+\r
+        mergeData.put(variable, requestParser.getParameter(variable));\r
+      }\r
+\r
+      try{\r
+        mergeData.put("topics", topicsModule.getTopicsAsSimpleList());\r
+      }\r
+      catch(Throwable e) {\r
+        logger.debug("Can't get topics: " + e.toString());\r
+      }\r
+\r
+      String searchBackValue = req.getParameter("search_back");\r
+      String searchForwardValue = req.getParameter("search_forward");\r
+\r
+      if (searchBackValue != null){\r
+        int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
+        int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()-increment;\r
+        if (newPosition<0)\r
+          newPosition=0;\r
+        if (newPosition >= totalHits)\r
+          newPosition=totalHits-1;\r
+        session.setAttribute("positionInResults",new Integer(newPosition));\r
+      }\r
+      else {\r
+        if (searchForwardValue != null){\r
+          int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
+          int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment;\r
+          if (newPosition<0)\r
+            newPosition=0;\r
+          if (newPosition >= totalHits)\r
+            newPosition=totalHits-1;\r
+\r
+          session.setAttribute("positionInResults",new Integer(newPosition));\r
+        }\r
+        else {\r
+          String indexPath=configuration.getString("IndexPath");\r
+\r
+\r
+          String creatorFragment = creatorTerm.makeTerm(req);\r
+          if (creatorFragment != null){\r
+            queryString = queryString + " +" + creatorFragment;\r
+          }\r
+\r
+          // search title, description, and content for something\r
+          // the contentTerm uses param "search_boolean" to combine its terms\r
+          String contentFragment = contentTerm.makeTerm(req);\r
+          if (contentFragment != null){\r
+            logger.debug("contentFragment: " + contentFragment);\r
+            queryString = queryString + " +" + contentFragment;\r
+          }\r
+\r
+          String topicFragment = topicTerm.makeTerm(req);\r
+          if (topicFragment != null){\r
+            queryString = queryString + " +" + topicFragment;\r
+          }\r
+\r
+          String imagesFragment = imagesTerm.makeTerm(req);\r
+          if (imagesFragment != null){\r
+            queryString = queryString + " +" + imagesFragment;\r
+          }\r
+\r
+          String audioFragment = audioTerm.makeTerm(req);\r
+          if (audioFragment != null){\r
+            queryString = queryString + " +" + audioFragment;\r
+          }\r
+\r
+          String videoFragment = videoTerm.makeTerm(req);\r
+          if (videoFragment != null){\r
+            queryString = queryString + " +" + videoFragment;\r
+          }\r
+\r
+          if (queryString == null || queryString == ""){\r
+            queryString = "";\r
+          }\r
+          else{\r
+            try{\r
+              Searcher searcher = null;\r
+              try {\r
+                searcher = new IndexSearcher(indexPath);\r
+              }\r
+              catch(IOException e) {\r
+                logger.debug("Can't open indexPath: " + indexPath);\r
+                throw new ServletModuleExc("Problem with Search Index! : "+ e.toString());\r
+              }\r
+\r
+              Query query = null;\r
+              try {\r
+                query = QueryParser.parse(queryString, "content", new StandardAnalyzer());\r
+              }\r
+              catch(Exception e) {\r
+                searcher.close();\r
+                logger.debug("Query don't parse: " + queryString);\r
+                throw new ServletModuleExc("Problem with Query String! (was '"+queryString+"')");\r
+              }\r
+\r
+              Hits hits = null;\r
+              try {\r
+                hits = searcher.search(query);\r
+              }\r
+              catch(IOException e) {\r
+                searcher.close();\r
+                logger.debug("Can't get hits: " + e.toString());\r
+                throw new ServletModuleExc("Problem getting hits!");\r
+              }\r
+\r
+              int start = 0;\r
+              int end = hits.length();\r
+\r
+              String sortBy=req.getParameter("search_sort");\r
+              if (sortBy == null || sortBy.equals("")){\r
+                throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");\r
+              }\r
+\r
+              // here is where the documents will go for storage across sessions\r
+              ArrayList theDocumentsSorted = new ArrayList();\r
+\r
+              if (sortBy.equals("score")){\r
+                for(int i = start; i < end; i++) {\r
+                  theDocumentsSorted.add(hits.doc(i));\r
+                }\r
+              }\r
+              else{\r
+                // then we'll sort by date!\r
+                Map dateToPosition = new HashMap(end,1.0F); //we know how big it will be\r
+                for(int i = start; i < end; i++) {\r
+                  String creationDate=(hits.doc(i)).get("creationDate");\r
+                  // do a little dance in case two contents created at the same second!\r
+                  if (dateToPosition.containsKey(creationDate)){\r
+                    ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));\r
+                  }\r
+                  else{\r
+                    ArrayList thePositions = new ArrayList();\r
+                    thePositions.add(new Integer(i));\r
+                    dateToPosition.put(creationDate,thePositions);\r
+                  }\r
+                }\r
+                Set keys = dateToPosition.keySet();\r
+                ArrayList keyList= new ArrayList(keys);\r
+                Collections.sort(keyList);\r
+                if (sortBy.equals("date_desc")){\r
+                  Collections.reverse(keyList);\r
+                }\r
+                else{\r
+                  if (!sortBy.equals("date_asc")){\r
+                    throw new ServletModuleExc("don't know how to sort by: "+ sortBy);\r
+                  }\r
+                }\r
+                ListIterator keyTraverser = keyList.listIterator();\r
+                while (keyTraverser.hasNext()){\r
+                  ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next()));\r
+                  ListIterator positionsTraverser=positions.listIterator();\r
+                  while (positionsTraverser.hasNext()){\r
+                    theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue()));\r
+                  }\r
+                }\r
+              }\r
+\r
+              try{\r
+                searcher.close();\r
+              }\r
+              catch (IOException e){\r
+                logger.debug("Can't close searcher: " + e.toString());\r
+                throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);\r
+              }\r
+\r
+\r
+              session.removeAttribute("numberOfHits");\r
+              session.removeAttribute("theDocumentsSorted");\r
+              session.removeAttribute("positionInResults");\r
+\r
+              session.setAttribute("numberOfHits",new Integer(end));\r
+              session.setAttribute("theDocumentsSorted",theDocumentsSorted);\r
+              session.setAttribute("positionInResults",new Integer(0));\r
+\r
+            }\r
+            catch (IOException e){\r
+              logger.debug("Can't close searcher: " + e.toString());\r
+              throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);\r
+            }\r
+          }\r
+        }\r
+      }\r
+\r
+      try {\r
+        ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted");\r
+        if (theDocs != null){\r
+\r
+          mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString());\r
+          List theHits = new Vector();\r
+          int pIR=((Integer)session.getAttribute("positionInResults")).intValue();\r
+          int terminus;\r
+          int numHits=((Integer)session.getAttribute("numberOfHits")).intValue();\r
+\r
+          if (!(pIR+increment>=numHits)){\r
+            mergeData.put("hasNext","y");\r
+          }\r
+          else {\r
+            mergeData.put("hasNext", null);\r
+          }\r
+          if (pIR>0){\r
+            mergeData.put("hasPrevious","y");\r
+          }\r
+          else {\r
+            mergeData.put("hasPrevious", null);\r
+          }\r
+\r
+          if ((pIR+increment)>numHits){\r
+            terminus=numHits;\r
+          }\r
+          else {\r
+            terminus=pIR+increment;\r
+          }\r
+          for(int i = pIR; i < terminus; i++) {\r
+            Map h = new HashMap();\r
+            Document theHit = (Document)theDocs.get(i);\r
+            whereTerm.returnMeta(h,theHit);\r
+            creatorTerm.returnMeta(h,theHit);\r
+            titleTerm.returnMeta(h,theHit);\r
+            descriptionTerm.returnMeta(h,theHit);\r
+            dateTerm.returnMeta(h,theHit);\r
+            imagesTerm.returnMeta(h,theHit);\r
+            audioTerm.returnMeta(h,theHit);\r
+            videoTerm.returnMeta(h,theHit);\r
+            theHits.add(h);\r
+          }\r
+          mergeData.put("hits",theHits);\r
+        }\r
+      }\r
+      catch (Throwable e) {\r
+        logger.error("Can't iterate over hits: " + e.toString());\r
+\r
+        throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);\r
+      }\r
+\r
+      mergeData.put("queryString",queryString);\r
+\r
+      deliver(req, res, mergeData, null, searchResultsTemplate);\r
+    }\r
+    catch (NullPointerException n){\r
+      throw new ServletModuleFailure("Null Pointer: "+n.toString(), n);\r
+    }\r
+  }\r
+\r
+  /*\r
+   * Method for dynamically generating a pdf using iText\r
+   */\r
+\r
+\r
+  public void getpdf(HttpServletRequest req, HttpServletResponse res)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
+    String ID_REQUEST_PARAM = "id";\r
+    try {\r
+        String idParam = req.getParameter(ID_REQUEST_PARAM);\r
+        if (idParam != null) {\r
+          ByteArrayOutputStream out = new ByteArrayOutputStream();\r
+          PDFGenerator pdfMaker = new PDFGenerator(out);\r
+\r
+          RE re = new RE("[0-9]+");\r
+\r
+\r
+          REMatch[] idMatches=re.getAllMatches(idParam);\r
+\r
+          if (idMatches.length > 1){\r
+            pdfMaker.addLine();\r
+            for (int i = 0; i < idMatches.length; i++){\r
+              REMatch aMatch = idMatches[i];\r
+              String id=aMatch.toString();\r
+              EntityContent contentEnt = (EntityContent)contentModule.getById(id);\r
+              pdfMaker.addIndexItem(contentEnt);\r
+\r
+            }\r
+          }\r
+\r
+          for (int i = 0; i < idMatches.length; i++){\r
+            REMatch aMatch = idMatches[i];\r
+\r
+            String id=aMatch.toString();\r
+\r
+            EntityContent contentEnt = (EntityContent)contentModule.getById(id);\r
+            pdfMaker.add(contentEnt);\r
+\r
+          }\r
+\r
+          pdfMaker.stop();\r
+          res.setContentType("application/pdf");\r
+          byte[] content = out.toByteArray();\r
+          res.setContentLength(content.length);\r
+          res.getOutputStream().write(content);\r
+          res.getOutputStream().flush();\r
+\r
+        }\r
+        else {\r
+          throw new ServletModuleExc("Missing id.");\r
+        }\r
+    }\r
+    catch (Throwable t) {\r
+      logger.error(t.toString());\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+\r
+  }\r
+\r
+\r
+  /*\r
+   * Method for dynamically generating a pdf from a fo file\r
+   * (deprecated until fop gets its act together regarding floats)\r
+   */\r
+\r
+  /*\r
+  public void getpdf(HttpServletRequest req, HttpServletResponse res)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
+    String ID_REQUEST_PARAM = "id";\r
+    String language = req.getParameter("language");\r
+    String generateFO=configuration.getString("GenerateFO");\r
+    String generatePDF=configuration.getString("GeneratePDF");\r
+\r
+\r
+    //don't do anything if we are not making FO files, or if we are\r
+    //pregenerating PDF's\r
+    if (generateFO.equals("yes") && generatePDF.equals("no")){\r
+      //fop complains unless you do the logging this way\r
+      org.apache.log.Logger log = null;\r
+      Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();\r
+      log = hierarchy.getLoggerFor("fop");\r
+      log.setPriority(Priority.WARN);\r
+\r
+      String producerStorageRoot=configuration.getString("Producer.StorageRoot");\r
+      String producerDocRoot=configuration.getString("Producer.DocRoot");\r
+      //      String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");\r
+      String xslSheet=configuration.getString("Producer.HTML2FOStyleSheet");\r
+      try {\r
+        String idParam = req.getParameter(ID_REQUEST_PARAM);\r
+        if (idParam != null) {\r
+          EntityContent contentEnt =\r
+            (EntityContent)contentModule.getById(idParam);\r
+          String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date"));\r
+          String foFile;\r
+\r
+          if (language == null){\r
+            foFile = producerStorageRoot + producerDocRoot + "/"\r
+              + publishPath  + idParam + ".fo";\r
+          }\r
+          else{\r
+            foFile = producerStorageRoot + producerDocRoot + "/"\r
+              + language + publishPath  + idParam + ".fo";\r
+          }\r
+          logger.debug("USING FILES" + foFile + " and " + xslSheet);\r
+          XSLTInputHandler input = new XSLTInputHandler(new File(foFile),\r
+                                                        new File(xslSheet));\r
+\r
+          ByteArrayOutputStream out = new ByteArrayOutputStream();\r
+          res.setContentType("application/pdf");\r
+\r
+          Driver driver = new Driver();\r
+          driver.setLogger(log);\r
+          driver.setRenderer(Driver.RENDER_PDF);\r
+          driver.setOutputStream(out);\r
+          driver.render(input.getParser(), input.getInputSource());\r
+\r
+          byte[] content = out.toByteArray();\r
+          res.setContentLength(content.length);\r
+          res.getOutputStream().write(content);\r
+          res.getOutputStream().flush();\r
+        }\r
+        else {\r
+          throw new ServletModuleExc("Missing id.");\r
+        }\r
+      }\r
+      catch (Throwable t) {\r
+        logger.error(t.toString());\r
+\r
+        throw new ServletModuleFailure(t);\r
+      }\r
+    }\r
+    else {\r
+      throw new ServletModuleExc("Can't generate a PDF because the config tells me not to.");\r
+    }\r
+  }\r
+  */\r
+\r
+  public String generateOnetimePassword() {\r
+    Random r = new Random();\r
+    int random = r.nextInt();\r
+\r
+    long l = System.currentTimeMillis();\r
+\r
+    l = (l * l * l * l) / random;\r
+    if (l < 0)\r
+      l = l * -1;\r
+\r
+    String returnString = "" + l;\r
+\r
+    return returnString.substring(5);\r
+  }\r
+\r
+  public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)\r
+      throws ServletModuleFailure {\r
+    try {\r
+      deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)\r
+      throws ServletModuleFailure {\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open");\r
+      responseData.put("data", aData);\r
+      responseData.put("extra", anExtra);\r
+\r
+\r
+      Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);\r
+      generator.generate(anOutputWriter, responseData, logger.asPrintWriter(logger.INFO_MESSAGE));\r
+\r
+      anOutputWriter.close();\r
+    }\r
+    catch (Throwable e) {\r
+      logger.error("Error while generating " + aGenerator + ": " + e.getMessage());\r
+\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {\r
+    try {\r
+      logger.error("error: " + anException);\r
+      Map data = new HashMap();\r
+\r
+      data.put("errorstring", anException.getMessage());\r
+      data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));\r
+\r
+      deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
+                               PrintWriter out, ServletModuleUserExc anException) {\r
+    try {\r
+      logger.warn("user error: " + anException.getMessage());\r
+      Map data = new HashMap();\r
+\r
+      MessageResources messages = MessageResources.getMessageResources("bundles.open");\r
+      data.put("errorstring",\r
+              messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters())\r
+          );\r
+      data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));\r
+\r
+      deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  private String createOneTimePasswd() {\r
+    return "";\r
+  }\r
+}\r
index 942a2b2..56c6e9b 100755 (executable)
@@ -1,3 +1,34 @@
+/*\r
+ * Copyright (C) 2001, 2002  The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two.  You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries.  If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so.  If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
 package tool;\r
 \r
 import java.util.*;\r
index 485a834..51e10ba 100755 (executable)
 
 
 
+
+<function PulldownTableRow (label, fieldname, entrieslist, keyfield, valuefield, value, langprefix)>
+  <tr>
+     <td align="right" class="table_left">
+       <b>${label}:</b>
+     </td>
+     <td class="listrow2">
+       <select name="${fieldname}">
+         <list entrieslist as a>
+           <option value="${a[keyfield]}" <if (a[keyfield] == value)>selected</if>><if langprefix>${lang(langprefix+a[valuefield])}<else>${a[valuefield]}</if></option>
+         </list>
+       </select>
+     </td>
+   </tr>
+</function>   
+
+
 <comment>4 functions to create Table rows with input-fields</comment>
 <function TextInputTableRow (label, size, maxlength, fieldname, fieldcontent)>
        <tr>
                </td>
                
                <td class="listrow2">
-                       <input type="text" size="${size}" maxlength="${maxlength}" name="${fieldname}" value="${fieldcontent}">
+                       <input type="text" size="${size}" maxlength="${maxlength}" name="${fieldname}" value="${utility.encodeHTML(fieldcontent)}">
                </td>
        </tr>
 </function>
                </td>
                
                <td class="listrow1">
-                       <input type="text" size="${size}" maxlength="${maxlength}" name="${fieldname}" value="${fieldcontent}">
+                       <input type="text" size="${size}" maxlength="${maxlength}" name="${fieldname}" value="${utility.encodeHTML(fieldcontent)}">
                </td>
        </tr>
 </function>
 
+<function CheckboxTableRow (label, fieldname, fieldcontent )>
+       <tr>
+               <td align="right" valign="top" class="table_left">
+                       <b>${label}:</b>
+               </td>
+               
+               <td class="listrow2">
+                       <input type="checkbox" name="${fieldname}" value="1"<if fieldcontent=="1"> checked</if>>&nbsp;&nbsp;
+               </td>
+       </tr>
+</function>    
 
-
-<function TextAreaTableRow (label, cols, rows, fieldname, fieldcontent )>
+<function TextAreaTableRow (label, hint, cols, rows, fieldname, fieldcontent )>
        <tr>
                <td align="right" valign="top" class="table_left">
                        <b>${label}:</b>
+                       <if hint>
+        <br>
+        <span class="small">${hint}</span>                     
+      </if>
                </td>
                
                <td class="listrow2">
-                       <textarea cols="${cols}" rows="${rows}" name="${fieldname}">${fieldcontent}</textarea>
+                       <textarea cols="${cols}" rows="${rows}" name="${fieldname}" wrap="virtual">${utility.encodeHTML(fieldcontent)}</textarea>
                </td>
        </tr>
 </function>
 
-<function TextAreaTableRowLight (label, cols, rows, fieldname, fieldcontent )>
+
+<function TextAreaTableRowLight (label, hint, cols, rows, fieldname, fieldcontent )>
        <tr>
                <td align="right" valign="top" class="table_left_light">
                        <b>${label}:</b>
+                       <if hint>
+        <br>
+        <span class="small">${hint}</span>                     
+      </if>
                </td>
                
                <td class="listrow1">
-                       <textarea cols="${cols}" rows="${rows}" name="${fieldname}">${fieldcontent}</textarea>
+                       <textarea cols="${cols}" rows="${rows}" name="${fieldname}" wrap="virtual">${utility.encodeHTML(fieldcontent)}</textarea>
                </td>
        </tr>
 </function>
index b8410ad..dc78231 100755 (executable)
@@ -9,7 +9,7 @@
           <td>
             <select name="type">
               <list filtertypes as t>
-                <option value="${t.id}" <if t.id==aType>selected</if>>${lang(t.resource)}</option>
+                <option value="${t.id}" <if t.id==aType>selected</if>>${lang("abuse.filtertype."+t.resource)}</option>
               </list>
             </select>
           </td>
index 0c82b95..25a8083 100755 (executable)
                        <td class="table_head"><b>${lang("abuse.setting")}</b></td>
                        <td class="table_head"><b>${lang("abuse.value")}</b></td>
                </tr>
-               <tr>
-                       <td class="table_left">
-                               ${lang("abuse.disableopenpostings")}
-                       </td>
-                       <td class="listrow2">
-                               <input type="checkbox" name="disableop" value="1" <if disableop=="1">checked="1"</if>>
-                       </td>
-               </tr>
-               <tr>
-                       <td class="table_left">
-                               ${lang("abuse.openpostingpassword")}
-                       </td>
-                       <td class="listrow2">
-                               <input type="checkbox" name="passwordop" value="1" <if passwordop=="1">checked="1"</if>>
-                       </td>
-               </tr>
+
+    <call CheckboxTableRow (lang("abuse.disableopenpostings"), "disableop", disableop)>
+    <call CheckboxTableRow (lang("abuse.openpostingpassword"), "passwordop", passwordop)>
                
                <tr class="x-small"><td colspan="2">&nbsp;</td></tr>
-               
-               <tr>
-                       <td class="table_left">
-                               ${lang("abuse.logpostings")}
-                       </td>
-                       <td class="listrow2">
-                               <input type="checkbox" name="logenabled" value="1" <if logenabled=="1">checked="1"</if>>
-                       </td>
-               </tr>
-               <tr>
-                       <td class="table_left">
-                               ${lang("abuse.logsize")}
-                       </td>
-                       <td class="listrow2">
-                               <input type="text" size="10" name="logsize" value="${logsize}">
-                       </td>
-               </tr>
+
+    <call CheckboxTableRow (lang("abuse.logpostings"), "logenabled", logenabled)>
+    <call TextInputTableRow (lang("abuse.logsize"), 10, 10, "logsize", logsize)>
                
                <tr class="x-small"><td colspan="2">&nbsp;</td></tr>            
                
-               <tr>
-                       <td class="table_left">
-                               ${lang("abuse.cookies")}
-                       </td>
-                       <td class="listrow2">
-                               <input type="checkbox" name="usecookies" value="1" <if usecookies=="1">checked="1"</if>>
-                       </td>
-               </tr>
+    <call CheckboxTableRow (lang("abuse.cookies"), "usecookies", usecookies)>
                
                <tr class="x-small"><td colspan="2">&nbsp;</td></tr>            
-               
-               <tr>
-                       <td class="table_left">
-                               ${lang("abuse.articleaction")}
-                       </td>
-                       <td class="listrow2">
-                       <select name="articleaction">
-                               <list articleactions as a>
-                               <option value="${a.identifier}" <if articleaction==a.identifier>selected="1"</if>>${utility.encodeHTML(lang(a.resource))}</option>
-                               </list>
-                       </select>
-                       </td>
-               </tr>
-               <tr>
-                       <td class="table_left">
-                               ${lang("abuse.commentaction")}
-                       </td>
-                       <td class="listrow2">
-                       <select name="commentaction">
-                               <list commentactions as a>
-                               <option value="${a.identifier}" <if commentaction==a.identifier>selected="1"</if>>${utility.encodeHTML(lang(a.resource))}</option>
-                               </list>
-                       </select>
-                       </td>
-               </tr>
+
+    <call PulldownTableRow (lang("abuse.articleaction"), "articleaction", articleactions, "identifier", "resource", articleaction, "content.operation.")>
+    <call PulldownTableRow (lang("abuse.commentaction"), "commentaction", commentactions, "identifier", "resource", commentaction, "comment.operation.")>
+
                <tr>
                        <td colspan="2" class="table_foot">
                                <input class="majorbutton" type="submit" name="submit" value="${lang("save")}">
index 7355611..904a74c 100755 (executable)
@@ -6,6 +6,7 @@
   <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
     
                <include "FUNCTIONS.template">
+    <include "head.template">
 
                <assign contentlist = data.contentlist>
                <assign column_nr = 3>
                <assign module_jumpback = "Admin">
                <assign do_jumpback = "superusermenu">
        
-       <include "templates/admin/head.template">
+    <include "templates/admin/head.template">
        
-       <call AddOrBack(module_name, module_jumpback, do_jumpback)>
+    <call AddOrBack(module_name, module_jumpback, do_jumpback)>
 
     <if data.contentlist>
-               <call ListTable(contentlist, data_keys, column_head_texts, column_head_CSS, listrow1CSS, listrow2CSS, footer_css, module_name)>
-               <call AddOrBack(module_name, module_jumpback, do_jumpback)>
-       <else>
+      <call ListTable(contentlist, data_keys, column_head_texts, column_head_CSS, listrow1CSS, listrow2CSS, footer_css, module_name)>
+      <call AddOrBack(module_name, module_jumpback, do_jumpback)>
+    <else>
       <P align="center">${lang("no_matches_found")}</p>
     </if>
-    
 
     <include "foot.template">
   </body>
index d916214..b18e018 100755 (executable)
@@ -85,8 +85,8 @@ function openWin(url) {
        <call TextInputTableRowLight (lang("year"), 20, 40, "year", data.year)>
        <call TextInputTableRow (lang("media.location"), 40, 80, "place", data.place)>
        <call TextInputTableRow (lang("media.creator"), 40, 80, "creator", data.creator)>
-       <call TextAreaTableRow (lang("media.keywords"), 40, 2, "keywords", data.keywords)>
-       <call TextAreaTableRow (lang("media.comment"), 40, 2, "comment", data.comment)>
+       <call TextAreaTableRow (lang("media.keywords"), "", 40, 2, "keywords", data.keywords)>
+       <call TextAreaTableRow (lang("media.comment"), "", 40, 2, "comment", data.comment)>
        <call TextInputTableRow (lang("media.source"), 40, 80, "source", data.source)>
        
        <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
index 517f6fe..d96f46a 100755 (executable)
             ${utility.encodeHTML(utility.encodeHTML(comment.webdb_create))}
           </td>
         </tr>
-      
-       
-               <tr>
-          <td align="right" class="table_left">
-            ${lang("comment.status")}
-          </td>
-          <td class="listrow2">
-            <select name="to_comment_status">
-              <list commentstatuses as a>
-                <option value="${a.id}" <if (a.id == comment.to_comment_status)>selected</if>>${lang("commentstatus."+a.name)}</option>
-              </list>
-            </select>
-          </td>
-        </tr>
-       
-        
-               <call TextInputTableRow (lang("comment.title"), 40, 255, "title", utility.encodeHTML(comment.title))>
-               <call TextInputTableRow (lang("comment.creator"), 40, 80, "creator", utility.encodeHTML(comment.creator))>
-               <call TextInputTableRow (lang("comment.url"), 40, 255, "main_url", utility.encodeHTML(comment.main_url))>
-               <call TextInputTableRow (lang("comment.email"), 40, 80, "email", utility.encodeHTML(comment.email))>
-               <call TextInputTableRow (lang("comment.phone"), 40, 80, "phone", utility.encodeHTML(comment.phone))>
-               <call TextInputTableRow (lang("comment.address"), 40, 80, "address", utility.encodeHTML(comment.address))>
+
+
+    <call PulldownTableRow (lang("comment.status"), "to_comment_status", commentstatuses, "id", "name", comment.to_comment_status, "commentstatus.")>
+
+               <call TextInputTableRow (lang("comment.title"), 40, 255, "title", comment.title)>
+               <call TextInputTableRow (lang("comment.creator"), 40, 80, "creator", comment.creator)>
+               <call TextInputTableRow (lang("comment.url"), 40, 255, "main_url", comment.main_url)>
+               <call TextInputTableRow (lang("comment.email"), 40, 80, "email", comment.email)>
+               <call TextInputTableRow (lang("comment.phone"), 40, 80, "phone", comment.phone)>
+               <call TextInputTableRow (lang("comment.address"), 40, 80, "address", comment.address)>
                
-       
-        <tr>
-          <td align="right" class="table_left">
-           ${lang("comment.language")}
-         </td>
-          <td class="listrow2">
-            <select name="to_language">
-              <list languages as l>
-                <option value="${l.id}" <if (l.id == comment.to_language)>selected</if>>${l.name}</option>
-              </list>
-            </select>
-          </td>
-        </tr>
-      
-        <tr>
-          <td align="right" class="table_left" valign="top">
-            ${lang("comment.text")}<br>
-            ${lang("comment.html")}<input type="checkbox" name="is_html" value="1"<if comment.is_html=="1"> checked</if>>
-          </td>
-          <td class="listrow2">
-            <textarea cols="60" rows="10" name="description" wrap="virtual">${utility.encodeHTML(comment.description)}</textarea>
-          </td>
-        </tr>
+    <call PulldownTableRow (lang("comment.language"), "to_language", languages, "id", "name", comment.to_language, "")>
+    <call CheckboxTableRow       (lang("comment.html"), "is_html", comment.is_html )>
+    <call TextAreaTableRow       (lang("comment.text"), "", 70, 15, "description", comment.description)>
+
         <tr>
           <td colspan="2" align="right" class="table_foot" > 
             <span class="text">
index 944270a..7b73ce2 100755 (executable)
                        ${lang("content.create_date")}:
                </td>
                <td class="listrow2">
-                       ${utility.encodeHTML(article.webdb_create)}<br>${lang("edit")}:
-                       <input type="text" size="10" maxlength="16" name="webdb_create" value=""> &nbsp; <span class="small">(yyyy-mm-dd [HH:mm])</span>
+               ${utility.encodeHTML(article.webdb_create)}<br>${lang("edit")}:
+               <input type="text" size="10" maxlength="16" name="webdb_create" value=""> &nbsp; <span class="small">(yyyy-mm-dd [HH:mm])</span>
                </td>
        </tr>
 
-       <tr>
-               <td align="right" valign="top" class="table_left">
-                       ${lang("content.articletype")}:
-               </td>
-               <td class="listrow2">
-                               <select name="to_article_type">
-                                       <list articletypes as a>
-                                       <option value="${a.id}" <if (a.id == article.to_article_type)>selected</if>>${lang("articletypes."+a.name)}</option>
-                                       </list>
-                               </select>
-               </td>
-       </tr>
-       
-       <tr>
-               <td align="right" class="table_left">
-                       ${lang("content.language")}
-               </td>
-               <td class="listrow2">
-                       <select name="to_language">
-                               <list languages as l>
-                               <option value="${l.id}" <if (l.id == article.to_language)>selected</if>>${l.name}</option>
-                               </list>
-                       </select>
-               </td>
-       </tr>
-       
-       
-       
+
+  <call PulldownTableRow (lang("content.articletype"), "to_article_type", articletypes, "id", "name", article.to_article_type, "articletypes.")>
+  <call PulldownTableRow (lang("content.language"), "to_language", languages, "id", "name", article.to_language, "")>
        
        <tr>
                <td align="right" valign="top" class="table_left">
                </td>
        </tr>
        
-       <call TextInputTableRow      (lang("content.title"), 40, 255, "title", utility.encodeHTML(article.title))>
-       <call TextInputTableRowLight (lang("content.subtitle"), 20, 20, "subtitle", utility.encodeHTML(article.subtitle))>
-    <comment>
-               <call TextInputTableRowLight ("", 20, 20, "subtitle", utility.encodeHTML(article.edittitle))>
-       </comment>
-       <call TextInputTableRowLight (lang("content.location"), 40, 40, "source", utility.encodeHTML(article.source))>
-       <call TextInputTableRow      (lang("content.creator"), 40, 40, "creator", utility.encodeHTML(article.creator))>
-       <call TextInputTableRowLight (lang("content.creator.email"), 40, 60, "creator_email", utility.encodeHTML(article.creator_email))>
-       <call TextInputTableRowLight (lang("content.creator.url"), 40, 60, "creator_main_url", utility.encodeHTML(article.creator_main_url))>
-       <call TextInputTableRowLight (lang("content.creator.address"), 20, 40, "creator_address", utility.encodeHTML(article.creator_address))>
-       <call TextInputTableRowLight (lang("content.creator.telephone"), 20, 40, "creator_phone", utility.encodeHTML(article.creator_phone))>
+       <call TextInputTableRow      (lang("content.title"), 40, 255, "title", article.title)>
+       <call TextInputTableRowLight (lang("content.subtitle"), 20, 20, "subtitle", article.subtitle)>
+  <comment>
+               <call TextInputTableRowLight ("", 20, 20, "subtitle", article.edittitle)>
+  </comment>
+       <call TextInputTableRowLight (lang("content.location"), 40, 40, "source", article.source)>
+       <call TextInputTableRow      (lang("content.creator"), 40, 40, "creator", article.creator)>
+       <call TextInputTableRowLight (lang("content.creator.email"), 40, 60, "creator_email", article.creator_email)>
+       <call TextInputTableRowLight (lang("content.creator.url"), 40, 60, "creator_main_url", article.creator_main_url)>
+       <call TextInputTableRowLight (lang("content.creator.address"), 20, 40, "creator_address", article.creator_address)>
+       <call TextInputTableRowLight (lang("content.creator.telephone"), 20, 40, "creator_phone", article.creator_phone)>
+  <call CheckboxTableRow       (lang("content.html"), "is_html", article.is_html )>
+       <call TextAreaTableRow       (lang("content.abstract"), "", 70, 15, "description", article.description)>
+       <call TextAreaTableRow       (lang("content.content"), "", 70, 20, "content_data", article.content_data)>
+       <call TextAreaTableRow       (lang("content.comment"), lang("content.internal"), 70, 6, "comment", article.comment)>
 
        <tr>
-               <td align="right" valign="top" class="table_left">
-                       ${lang("content.abstract")}:
-               </td>
-               <td class="listrow2">
-                       <textarea cols="70" rows="15" name="description" wrap=virtual>${utility.encodeHTML(article.description)}</textarea>
-               </td>
-       </tr>
-
-       <tr>
-               <td align="right" valign="top" class="table_left">
-                       ${lang("content.content")}: 
-                       <br>
-                       ${lang("content.html")}&nbsp;
-                       <input type="checkbox" name="is_html" value="1"<if article.is_html=="1"> checked</if>>&nbsp;&nbsp;
-               </td>
-               <td class="listrow2">
-                       <textarea cols="70" rows="20" name="content_data" wrap=virtual>${utility.encodeHTML(article.content_data)}</textarea>
-               </td>
-       </tr>
-       
-       <tr>
-               <td align="right" valign="top" class="table_left">
-                       ${lang("content.comment")}:<br>
-                       <span class="small">${lang("content.internal")}</span>
-               </td>
-               <td class="listrow2">
-                       <textarea cols="70" rows="6" name="comment" wrap=virtual>${utility.encodeHTML(article.comment)}</textarea>
-               </td>
-       </tr>
-       <tr>
                <td colspan="2" align="right" valign="top">
                        <if new=="1">
                                <input type="submit" name="save" value="${lang("insert")}">
index d73d153..6972c92 100755 (executable)
@@ -91,8 +91,8 @@ function openWin(url) {
        <call TextInputTableRowLight (lang("year"), 20, 40, "year", data.year)>
        <call TextInputTableRow (lang("media.location"), 40, 80, "place", data.place)>
        <call TextInputTableRow (lang("media.creator"), 40, 80, "creator", data.creator)>
-       <call TextAreaTableRow (lang("media.keywords"), 40, 2, "keywords", data.keywords)>
-       <call TextAreaTableRow (lang("media.comment"), 40, 2, "comment", data.comment)>
+       <call TextAreaTableRow (lang("media.keywords"), "", 40, 2, "keywords", data.keywords)>
+       <call TextAreaTableRow (lang("media.comment"), "", 40, 2, "comment", data.comment)>
        <call TextInputTableRow (lang("media.source"), 40, 80, "source", data.source)>
        
        <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
index a7e827b..c2ec8cc 100755 (executable)
@@ -87,8 +87,8 @@ function openWin(url) {
        <call TextInputTableRowLight (lang("year"), 20, 40, "year", data.year)>
        <call TextInputTableRow (lang("media.location"), 40, 80, "place", data.place)>
        <call TextInputTableRow (lang("media.creator"), 40, 80, "creator", data.creator)>
-       <call TextAreaTableRow (lang("media.keywords"), 40, 2, "keywords", data.keywords)>
-       <call TextAreaTableRow (lang("media.comment"), 40, 2, "comment", data.comment)>
+       <call TextAreaTableRow (lang("media.keywords"), "", 40, 2, "keywords", data.keywords)>
+       <call TextAreaTableRow (lang("media.comment"), "", 40, 2, "comment", data.comment)>
        <call TextInputTableRow (lang("media.source"), 40, 80, "source", data.source)>
        
        <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
index 85e5145..e832b7b 100755 (executable)
@@ -19,8 +19,8 @@
 <call TextInputTableRow (lang("mediafolder.date"), 8, 8, "date", data.date)>
 <call TextInputTableRow (lang("mediafolder.name"), 40, 80, "name", data.name)>  
 <call TextInputTableRow (lang("mediafolder.location"), 40, 80, "place", data.place)>  
-<call TextAreaTableRow (lang("mediafolder.comment"), 40, 5, "comment", data.comment)>  
-<call TextAreaTableRow (lang("mediafolder.keywords"), 40, 4, "keywords", data.keywords)>  
+<call TextAreaTableRow (lang("mediafolder.comment"), "", 40, 5, "comment", data.comment)>  
+<call TextAreaTableRow (lang("mediafolder.keywords"), "", 40, 4, "keywords", data.keywords)>  
 
 
   <tr>
index bf99bcd..bccccf1 100755 (executable)
@@ -31,7 +31,7 @@
   
   <call TextInputTableRow (lang("message.title"), 30, 30, "title", data.title)> 
   <call TextInputTableRow (lang("message.creator"), 12, 30, "creator", data.creator)> 
-  <call TextAreaTableRow  (lang("message.text"), 50, 5, "description", data.description)> 
+  <call TextAreaTableRow  (lang("message.text"), "", 50, 5, "description", data.description)> 
   
 
 
index 4d06206..f27f39f 100755 (executable)
@@ -20,7 +20,7 @@
 
       <table border="0">
                <call TextInputTableRow (lang("topic.title"), 40, 255, "title", data.title)>
-               <call TextAreaTableRow (lang("topic.description"), 40, 3, "description", data.description)>
+               <call TextAreaTableRow (lang("topic.description"), "", 40, 3, "description", data.description)>
                <call TextInputTableRow (lang("topic.filename"), 20, 255, "filename", data.filename)>
                <call TextInputTableRow (lang("topic.main_url"), 40, 255, "main_url", data.main_url)>
                <call TextInputTableRow (lang("topic.archive_url"), 40, 255, "archiv_url", data.archiv_url)>
index 71283a4..7736abc 100755 (executable)
@@ -85,8 +85,8 @@ function openWin(url) {
        <call TextInputTableRowLight (lang("year"), 20, 40, "year", data.year)>
        <call TextInputTableRow (lang("media.location"), 40, 80, "place", data.place)>
        <call TextInputTableRow (lang("media.creator"), 40, 80, "creator", data.creator)>
-       <call TextAreaTableRow (lang("media.keywords"), 40, 2, "keywords", data.keywords)>
-       <call TextAreaTableRow (lang("media.comment"), 40, 2, "comment", data.comment)>
+       <call TextAreaTableRow (lang("media.keywords"), "", 40, 2, "keywords", data.keywords)>
+       <call TextAreaTableRow (lang("media.comment"), "", 40, 2, "comment", data.comment)>
        <call TextInputTableRow (lang("media.source"), 40, 80, "source", data.source)>
        
        <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
@@ -133,11 +133,11 @@ function openWin(url) {
        </if>
 
     <td colspan="2" align="right" class="table_foot">
-       <if data.new>
+    <if data.new>
       <input type="submit" name="save" value="${lang("insert")}">
     <else>
-     ${lang("media.is_published")} <input type="checkbox" name="is_published" value="1"<if data.is_published!="0" && data.is_published!=""> checked</if>>
-    &nbsp;&nbsp;<input type="submit" name="save" value="${lang("save")}">
+      ${lang("media.is_published")} <input type="checkbox" name="is_published" value="1"<if data.is_published!="0" && data.is_published!=""> checked</if>>
+      &nbsp;&nbsp;<input type="submit" name="save" value="${lang("save")}">
     </if> </form>
     </td>
 </table>