From: zapata Date: Wed, 16 Apr 2003 03:26:44 +0000 (+0000) Subject: - experimental opensessions X-Git-Tag: BEFORE_MERGE_1_1~175 X-Git-Url: http://erislabs.org.uk/gitweb/?a=commitdiff_plain;h=d7429fe1376f25d0c4420c35c69dc9edd651ab25;p=mir.git - experimental opensessions - experimental media in comments support - first attempts of replacing cos - support for Beans by the freemarker generator --- diff --git a/etc/bundles/producer_en.properties b/etc/bundles/producer_en.properties index 737e5dcb..aae675ff 100755 --- a/etc/bundles/producer_en.properties +++ b/etc/bundles/producer_en.properties @@ -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 index 00000000..bf9d1ed4 --- /dev/null +++ b/etc/open/donecomment.template @@ -0,0 +1,37 @@ + + + + + ${lang("commentdone.htmltitle")} + + + + + + + + + + + + + +
+ ${lang("commentdone.thanks")} +
+ +
+ ${lang("commentdone.wait")} +
+ ${lang("commentdone.criteria")} +
+ ${lang("commentdone.stay_calm")}
+
+ +
+ >> ${lang("commentdone.back")} +
+ + + diff --git a/etc/open/dupecomment.template b/etc/open/dupecomment.template new file mode 100755 index 00000000..2e9ce66e --- /dev/null +++ b/etc/open/dupecomment.template @@ -0,0 +1,37 @@ + + + + + ${lang("commentdupe.htmltitle")} + + + + + + + + + + + + + +
+ + ${lang("commentdupe.title")} + +
+ +
+ ${lang("commentdupe.explanation")} +
+
${lang("commentdupe.no_panic")}

+
+
+
+ >> ${lang("commentdupe.back")} +
+ + + diff --git a/etc/open/editcomment.template b/etc/open/editcomment.template new file mode 100755 index 00000000..54140176 --- /dev/null +++ b/etc/open/editcomment.template @@ -0,0 +1,234 @@ + + + + ${lang("comment.htmltitle")} + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 
+ Your input had the following errors:

+ + + + ${lang("comment."+e.field)}: + + ${lang(e.message)}
+
+
+
  + ${lang("comment.note")} +
${data.passwd}
+
+
 
+ ${lang("comment.password")}: +  
+ + ${lang("comment.formtitle")} +  
 
  + R E Q U I R E D information +  
 
+ ${lang("comment.title")}: + + +
+ ${lang("comment.text")}: + + +
+ ${lang("comment.name")}:

+
+ +

+
  + Additional information +  
 
+ ${lang("comment.language")}:

+
+ +

+
 
  + Contact information +  
 
  + ${lang("comment.contact.info")} +  
+ ${lang("comment.email")}: + + +  
+ ${lang("comment.url")}: + + +  
+ ${lang("comment.address")}: + + +  
+ ${lang("comment.phone")}

+
+

+
 
+ ${lang("posting.media.title")} 1: + +
+
${lang("posting.media.media")} 1 + +
+ ${lang("posting.media.title")} 2: + +
+
${lang("posting.media.media")} 2 + +
+ ${lang("posting.media.title")} 3: + +
+
${lang("posting.media.media")} 3 + +
  + +  
 

+
+ + diff --git a/etc/producer/article.template b/etc/producer/article.template index 83f90d8d..77aaf970 100755 --- a/etc/producer/article.template +++ b/etc/producer/article.template @@ -162,7 +162,7 @@
-   +   ${lang("article.addcomment")}>>
@@ -171,6 +171,31 @@
${utility.encodeHTML(c.title)}
${c.creationdate.formatted["dd.MM.yyyy HH:mm"]}
+ + + + ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]} + + + + + + ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]} + + + + + ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]} + + + + ${image[ +
${image["title"]} +
+ + ${c.description_parsed} diff --git a/lib/commons-beanutils-1.6.1.jar b/lib/commons-beanutils-1.6.1.jar new file mode 100755 index 00000000..795655a6 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 index 00000000..ab993566 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 index 00000000..b99c9375 Binary files /dev/null and b/lib/commons-logging-1.0.3.jar differ diff --git a/source/OpenMir.java b/source/OpenMir.java index f8cc73ef..791e3457 100755 --- a/source/OpenMir.java +++ b/source/OpenMir.java @@ -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) diff --git a/source/default.properties b/source/default.properties index 356f6bb8..531c749c 100755 --- a/source/default.properties +++ b/source/default.properties @@ -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 diff --git a/source/mir/entity/adapter/EntityAdapterExc.java b/source/mir/entity/adapter/EntityAdapterExc.java index b3a76810..9d21d57e 100755 --- a/source/mir/entity/adapter/EntityAdapterExc.java +++ b/source/mir/entity/adapter/EntityAdapterExc.java @@ -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; diff --git a/source/mir/generator/FreemarkerGenerator.java b/source/mir/generator/FreemarkerGenerator.java index d4fda8cf..ea0c69dd 100755 --- a/source/mir/generator/FreemarkerGenerator.java +++ b/source/mir/generator/FreemarkerGenerator.java @@ -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; diff --git a/source/mir/generator/GeneratorLibraryRepository.java b/source/mir/generator/GeneratorLibraryRepository.java index 06dde953..639c9c19 100755 --- a/source/mir/generator/GeneratorLibraryRepository.java +++ b/source/mir/generator/GeneratorLibraryRepository.java @@ -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; diff --git a/source/mir/module/AbstractModule.java b/source/mir/module/AbstractModule.java index 25a22824..36877488 100755 --- a/source/mir/module/AbstractModule.java +++ b/source/mir/module/AbstractModule.java @@ -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 diff --git a/source/mir/producer/RSSProducerNode.java b/source/mir/producer/RSSProducerNode.java index d3ee397e..6db80886 100755 --- a/source/mir/producer/RSSProducerNode.java +++ b/source/mir/producer/RSSProducerNode.java @@ -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; diff --git a/source/mir/producer/SimpleProducerVerb.java b/source/mir/producer/SimpleProducerVerb.java index 57c39ccb..66d2f901 100755 --- a/source/mir/producer/SimpleProducerVerb.java +++ b/source/mir/producer/SimpleProducerVerb.java @@ -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 { diff --git a/source/mir/producer/reader/ProducerConfigReader.java b/source/mir/producer/reader/ProducerConfigReader.java index 1eabcc2f..f71c5b1e 100755 --- a/source/mir/producer/reader/ProducerConfigReader.java +++ b/source/mir/producer/reader/ProducerConfigReader.java @@ -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) { diff --git a/source/mir/servlet/ServletModule.java b/source/mir/servlet/ServletModule.java index f114804d..6dc534c0 100755 --- a/source/mir/servlet/ServletModule.java +++ b/source/mir/servlet/ServletModule.java @@ -475,8 +475,6 @@ public abstract class ServletModule { for (int i = 0; i < theFieldList.size(); i++) { aField = (String) theFieldList.get(i); - logger.debug("field " + aField + " = " + parser.getParameter(aField)); - aValue = parser.getParameter(aField); if (aValue != null) withValues.put(aField, aValue); diff --git a/source/mir/session/CommonsUploadedFileAdapter.java b/source/mir/session/CommonsUploadedFileAdapter.java new file mode 100755 index 00000000..42b2d915 --- /dev/null +++ b/source/mir/session/CommonsUploadedFileAdapter.java @@ -0,0 +1,27 @@ +package mir.session; + +import org.apache.commons.fileupload.*; +import java.io.*; + +public class CommonsUploadedFileAdapter implements UploadedFile { + private FileItem fileItem; + private Object container; + + public CommonsUploadedFileAdapter(Object aContainer, FileItem aFileItem) { + container = aContainer; + fileItem = aFileItem; + } + + public InputStream getInputStream() throws SessionExc, SessionFailure{ + try { + return fileItem.getInputStream(); + } + catch (Throwable t) { + throw new SessionFailure(t); + } + }; + + public String getContentType() { + return fileItem.getContentType(); + }; +} \ No newline at end of file diff --git a/source/mir/session/HTTPAdapters.java b/source/mir/session/HTTPAdapters.java new file mode 100755 index 00000000..b8d4181e --- /dev/null +++ b/source/mir/session/HTTPAdapters.java @@ -0,0 +1,91 @@ +package mir.session; + +import java.util.Arrays; +import java.util.List; +import java.util.Vector; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.commons.fileupload.FileItem; + +import mir.util.HTTPParsedRequest; + +public class HTTPAdapters { + public static class HTTPRequestAdapter implements Request { + private HttpServletRequest request; + + public HTTPRequestAdapter(HttpServletRequest aRequest) { + request = aRequest; + } + + public String getParameter(String aName) { + return request.getParameter(aName); + }; + + public List getUploadedFiles() { + return new Vector(); + }; + + public List getParameters(String aName) { + return Arrays.asList(request.getParameterValues(aName)); + }; + + public HttpServletRequest getRequest() { + return request; + } + } + + public static class HTTPParsedRequestAdapter implements Request { + private HTTPParsedRequest request; + + public HTTPParsedRequestAdapter(HTTPParsedRequest aRequest) { + request = aRequest; + } + + public String getParameter(String aName) { + return request.getParameter(aName); + }; + + public List getParameters(String aName) { + return request.getParameterList(aName); + }; + + public List getUploadedFiles() { + List result = new Vector(); + List files = request.getFiles(); + + for (int i=0; i0 && ((String) parts.get(0)).trim().toLowerCase().equals(MULTIPART_FORMDATA_CONTENTTYPE)) { + parseMultipartRequest(); + } + } + catch (Throwable t) { + t.printStackTrace(); + + throw new UtilFailure(t); + } + } + + protected void parseMultipartRequest() throws UtilExc, UtilFailure { + try { + FileUpload upload = new FileUpload(); + + upload.setSizeMax(maxUploadSize); + upload.setSizeThreshold(4096); + upload.setRepositoryPath(tempDir); + + List items = upload.parseRequest(request); + + Iterator i = items.iterator(); + while (i.hasNext()) { + FileItem item = (FileItem) i.next(); + + if (item.isFormField()) { + if (!stringValues.containsKey(item.getName())) { + stringValues.put(item.getFieldName(), item.getString()); + } + + List listValue = (List) listValues.get(item.getFieldName()); + if (listValue == null) { + listValue = new Vector(); + listValues.put(item.getFieldName(), listValue); + } + listValue.add(item.getString()); + } + else { + if (item.getSize()>0) + files.add(item); + } + } + } + catch (Throwable t) { + throw new UtilFailure(t); + } + } +} diff --git a/source/mir/util/HTTPRequestParser.java b/source/mir/util/HTTPRequestParser.java index 20bfd910..043dc7c1 100755 --- a/source/mir/util/HTTPRequestParser.java +++ b/source/mir/util/HTTPRequestParser.java @@ -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 +/* + * 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 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; + } +} diff --git a/source/mir/util/InternetFunctions.java b/source/mir/util/InternetFunctions.java index 5193daa0..171e8f89 100755 --- a/source/mir/util/InternetFunctions.java +++ b/source/mir/util/InternetFunctions.java @@ -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/JDBCStringRoutines.java b/source/mir/util/JDBCStringRoutines.java index 0e273f2a..a039d109 100755 --- a/source/mir/util/JDBCStringRoutines.java +++ b/source/mir/util/JDBCStringRoutines.java @@ -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; /** diff --git a/source/mir/util/PropertiesManipulator.java b/source/mir/util/PropertiesManipulator.java index a60a8ca3..194f31b6 100755 --- a/source/mir/util/PropertiesManipulator.java +++ b/source/mir/util/PropertiesManipulator.java @@ -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; diff --git a/source/mir/util/SQLQueryBuilder.java b/source/mir/util/SQLQueryBuilder.java index eef1844b..dcf3a2a5 100755 --- a/source/mir/util/SQLQueryBuilder.java +++ b/source/mir/util/SQLQueryBuilder.java @@ -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 { diff --git a/source/mir/util/StringRoutines.java b/source/mir/util/StringRoutines.java index 4c58d6a0..579e9211 100755 --- a/source/mir/util/StringRoutines.java +++ b/source/mir/util/StringRoutines.java @@ -1,212 +1,213 @@ -/* - * 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; iseperateString("a:b:c", ":"); will lead to - * a List with 3 Strings: "a", "b" and "c" - * - * @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: - *
    - *
  • - * seperateString("a:b:c", ":"); will lead to - * a List with 2 Strings: "a" and "b:c" - *
  • - * seperateString("abc", ":"); will lead to - * a List with a single String: "abc" - *
- * - * - * @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; - } +/* + * 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; iseperateString("a:b:c", ":"); will lead to + * a List with 3 Strings: "a", "b" and "c" + * + * @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; + + if (aString!=null) { + 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: + *
    + *
  • + * seperateString("a:b:c", ":"); will lead to + * a List with 2 Strings: "a" and "b:c" + *
  • + * seperateString("abc", ":"); will lead to + * a List with a single String: "abc" + *
+ * + * + * @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; + } } \ No newline at end of file diff --git a/source/mir/util/URLBuilder.java b/source/mir/util/URLBuilder.java index f64fb904..c36cdf9e 100755 --- a/source/mir/util/URLBuilder.java +++ b/source/mir/util/URLBuilder.java @@ -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 index 00000000..7810effd --- /dev/null +++ b/source/mir/util/UtilExc.java @@ -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 index 00000000..99902962 --- /dev/null +++ b/source/mir/util/UtilFailure.java @@ -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); + } +} diff --git a/source/mircoders/entity/EntityMedia.java b/source/mircoders/entity/EntityMedia.java index cf8f801b..0784743e 100755 --- a/source/mircoders/entity/EntityMedia.java +++ b/source/mircoders/entity/EntityMedia.java @@ -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); - } - - } -} +/* + * 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); + } + + } +} diff --git a/source/mircoders/global/Abuse.java b/source/mircoders/global/Abuse.java index 0d2e630f..b3e18550 100755 --- a/source/mircoders/global/Abuse.java +++ b/source/mircoders/global/Abuse.java @@ -1,601 +1,655 @@ -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(); - } - } - } - +/* + * 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.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 mir.session.*; +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("/"); + + if (aResponse!=null) + 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, Request aRequest, HttpServletResponse aResponse) { + try { + long time = System.currentTimeMillis(); + String address = "0.0.0.0"; + String browser = "unknown"; + Cookie[] cookies = {}; + + HttpServletRequest request = null; + + if (aRequest instanceof HTTPAdapters.HTTPParsedRequestAdapter) { + request = ((HTTPAdapters.HTTPParsedRequestAdapter) aRequest).getRequest(); + } + else if (aRequest instanceof HTTPAdapters.HTTPRequestAdapter) { + request = ((HTTPAdapters.HTTPRequestAdapter) aRequest).getRequest(); + } + if (request!=null) { + browser = (String) request.getHeader("User-Agent"); + address = request.getRemoteAddr(); + cookies = request.getCookies(); + } + + logComment(address, aComment.getId(), new Date(), browser); + + MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction); + + if (checkCookie(Arrays.asList(cookies)) || checkIpFilter(address) || 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(); + + logArticle(aRequest.getRemoteAddr(), anArticle.getId(), new Date(), (String) aRequest.getHeader("User-Agent")); + + 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", "ip"); + entry.put("id", IP_FILTER_TYPE); + result.add(entry); + + entry = new HashMap(); + entry.put("resource", "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", 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", 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(); + } + } + } + } \ No newline at end of file diff --git a/source/mircoders/localizer/MirLocalizer.java b/source/mircoders/localizer/MirLocalizer.java index 4d487ae7..8e3cf154 100755 --- a/source/mircoders/localizer/MirLocalizer.java +++ b/source/mircoders/localizer/MirLocalizer.java @@ -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 diff --git a/source/mircoders/localizer/MirOpenPostingLocalizer.java b/source/mircoders/localizer/MirOpenPostingLocalizer.java index 49601623..b3232751 100755 --- a/source/mircoders/localizer/MirOpenPostingLocalizer.java +++ b/source/mircoders/localizer/MirOpenPostingLocalizer.java @@ -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); -} +/* + * 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 java.util.Arrays; +import java.util.List; + +import mir.session.Request; +import mir.session.Response; +import mir.session.*; +import mircoders.entity.EntityComment; +import mircoders.entity.EntityContent; + +public interface MirOpenPostingLocalizer { + + /** + * Class to encapsulate a validation error + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + + /** + * + * @param aRequest + * @param aSession + * @return + * @throws MirLocalizerExc + * @throws MirLocalizerFailure + */ + public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure; + + /** + * + * @param aComment + * @throws MirLocalizerExc + * @throws MirLocalizerFailure + */ + public void afterCommentPosting(EntityComment aComment) throws MirLocalizerExc, MirLocalizerFailure; + + /** + * + * @param aContent + * @throws MirLocalizerExc + * @throws MirLocalizerFailure + */ + public void afterContentPosting(EntityContent aContent) throws MirLocalizerExc, MirLocalizerFailure; +} diff --git a/source/mircoders/localizer/basic/MirBasicCommentPostingSessionHandler.java b/source/mircoders/localizer/basic/MirBasicCommentPostingSessionHandler.java new file mode 100755 index 00000000..bf219f84 --- /dev/null +++ b/source/mircoders/localizer/basic/MirBasicCommentPostingSessionHandler.java @@ -0,0 +1,307 @@ +package mircoders.localizer.basic; + +import java.util.*; +import mir.log.LoggerWrapper; +import mir.session.*; +import mir.config.*; +import mir.util.*; +import mir.entity.*; +import mircoders.storage.*; +import mircoders.global.*; +import mircoders.localizer.*; +import mircoders.entity.*; +import mircoders.module.*; +import mircoders.media.*; + +/** + * + *

Title: Experimental session handler for comment postings

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class MirBasicCommentPostingSessionHandler implements SessionHandler { + protected LoggerWrapper logger; + protected MirPropertiesConfiguration configuration; + protected boolean initialRequest; + protected ModuleComment commentModule; + protected DatabaseCommentToMedia commentToMedia = DatabaseCommentToMedia.getInstance(); + + public MirBasicCommentPostingSessionHandler() { + logger = new LoggerWrapper("Localizer.OpenPosting.Comment"); + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (Throwable t) { + logger.fatal("Cannont load configuration: " + t.toString()); + + throw new RuntimeException("Cannont load configuration: " + t.toString()); + } + initialRequest= true; + commentModule= new ModuleComment(DatabaseComment.getInstance()); + } + + public void processRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure { + if (aSession.getAttribute("initialRequest")==null) { + initialRequest(aRequest, aSession, aResponse); + aSession.setAttribute("initialRequest", "no"); + } + else { + subsequentRequest(aRequest, aSession, aResponse); + } + }; + + public String generateOnetimePassword() { + 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); + } + + public void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure { + if (MirGlobal.abuse().getOpenPostingPassword()) { + String password = (String) aSession.getAttribute("password"); + if (password==null) { + password = generateOnetimePassword(); + aSession.setAttribute("password", password); + } + aResponse.setResponseValue("password", password); + } + else { + aResponse.setResponseValue("password", null); + aSession.deleteAttribute("password"); + } + + aResponse.setResponseValue("errors", null); + }; + + public void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure{ + Iterator i = DatabaseContent.getInstance().getFields().iterator(); + while (i.hasNext()) { + aResponse.setResponseValue( (String) i.next(), null); + } + + String articleId = aRequest.getParameter("to_media"); + + if (articleId == null) + throw new SessionExc("MirBasicCommentPostingSessionHandler.initialRequest: article id not set!"); + + aSession.setAttribute("to_media", articleId); + + initializeResponseData(aRequest, aSession, aResponse); + + try { + aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate")); + } + catch (Throwable e) { + throw new SessionFailure("Can't get configuration: " + e.getMessage(), e); + } + + } + + public boolean testFieldExists(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) { + Object value = aRequest.getParameter(aFieldName); + if (value==null || !(value instanceof String) || ((String) value).trim().length()==0) { + logger.debug(" missing field " + aFieldName + " value = " + value); + aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource)); + return false; + } + else + return true; + } + + public boolean testFieldIsNumeric(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) { + Object value = aRequest.getParameter(aFieldName); + if (value!=null) { + try { + Integer.parseInt((String) value); + return true; + } + catch (Throwable t) { + logger.debug(" field not numeric: " + aFieldName + " value = " + value); + aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource)); + return false; + } + } + return true; + } + + + public List validate(Request aRequest, Session aSession) throws SessionExc, SessionFailure { + List result = new Vector(); + + testFieldExists(aRequest, "title", "validationerror.missing", result); + testFieldExists(aRequest, "description", "validationerror.missing", result); + testFieldExists(aRequest, "creator", "validationerror.missing", result); + + return result; + } + + public void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure { + try { + Map commentFields = new HashMap(); + + Iterator i = DatabaseContent.getInstance().getFields().iterator(); + while (i.hasNext()) { + String field = (String) i.next(); + aResponse.setResponseValue(field, aRequest.getParameter(field)); + if (aRequest.getParameter(field)!=null) { + commentFields.put(field, aRequest.getParameter(field)); + } + } + + initializeResponseData(aRequest, aSession, aResponse); + + List validationErrors = validate(aRequest, aSession); + + if (validationErrors != null && validationErrors.size()>0) { + returnValidationErrors(aRequest, aSession, aResponse, validationErrors); + } + else { + EntityComment comment = (EntityComment) commentModule.createNew (); + comment.setValues(commentFields); + + finishComment(aRequest, aSession, comment); + + String id = comment.insert(); + if(id==null){ + afterDuplicateCommentPosting(aRequest, aSession, aResponse, comment); + logger.info("Dupe comment rejected"); + aSession.terminate(); + } + else { + i = aRequest.getUploadedFiles().iterator(); + while (i.hasNext()) { + UploadedFile file = (UploadedFile) i.next(); + processMediaFile(aRequest, aSession, comment, file); + } + + afterCommentPosting(aRequest, aSession, aResponse, comment); + MirGlobal.abuse().checkComment(comment, aRequest, null); + MirGlobal.localizer().openPostings().afterCommentPosting(comment); + logger.info("Comment posted"); + aSession.terminate(); + } + } + } + catch (Throwable t) { + ExceptionFunctions.traceCauseException(t).printStackTrace(); + + throw new SessionFailure("MirBasicCommentPostingSessionHandler.subsequentRequest: " + t.getMessage(), t); + } + } + + public void initializeCommentPosting(Request aRequest, Session aSession, Response aResponse) throws SessionFailure, SessionExc { + String articleId = aRequest.getParameter("to_media"); + if (articleId==null) + articleId = aRequest.getParameter("aid"); + + if (articleId==null) + throw new SessionExc("initializeCommentPosting: article id not set!"); + + aSession.setAttribute("to_media", articleId); + processCommentPosting(aRequest, aSession, aResponse); + }; + + public void returnValidationErrors(Request aRequest, Session aSession, Response aResponse, List aValidationErrors) throws SessionFailure, SessionExc { + aResponse.setResponseValue("errors", aValidationErrors); + aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate")); + }; + + public void processCommentPosting(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure { + if (MirGlobal.abuse().getOpenPostingPassword()) { + String password = generateOnetimePassword(); + aSession.setAttribute("password", password); + aResponse.setResponseValue("password", password); + aResponse.setResponseValue("passwd", password); + } + else { + aResponse.setResponseValue("password", null); + } + + aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate")); + }; + + public void processMediaFile(Request aRequest, Session aSession, EntityComment aComment, UploadedFile aFile) throws SessionExc, SessionFailure { + try { + Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile); + finishMedia(aRequest, aSession, aFile, mediaItem); + mediaItem.update(); + commentToMedia.addMedia(aComment.getId(), mediaItem.getId()); + } + catch (Throwable t) { + throw new SessionFailure(t); + } + } + + public void finishMedia(Request aRequest, Session aSession, UploadedFile aFile, Entity aMedia) throws SessionExc, SessionFailure { + } + + public void finishComment(Request aRequest, Session aSession, EntityComment aComment) throws SessionExc, SessionFailure { + if (aSession.getAttribute("to_media") == null) + throw new SessionExc("missing to_media"); + + aComment.setValueForProperty("is_published", "1"); + aComment.setValueForProperty("to_comment_status", "1"); + aComment.setValueForProperty("is_html","0"); + aComment.setValueForProperty("to_media", (String) aSession.getAttribute("to_media")); + }; + + public void addMedia(Request aRequest, Session aSession, EntityComment aComment) throws SessionExc, SessionFailure { + } + + public void afterCommentPosting(Request aRequest, Session aSession, Response aResponse, EntityComment aComment) { + DatabaseContent.getInstance().setUnproduced("id=" + aComment.getValue("to_media")); + aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.DoneTemplate")); + }; + + public void afterDuplicateCommentPosting(Request aRequest, Session aSession, Response aResponse, EntityComment aComment) { + aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.DupeTemplate")); + }; + + public class ValidationError { + private String field; + private String message; + private List parameters; + + public ValidationError(String aField, String aMessage) { + this (aField, aMessage, new String[] {}); + } + + public ValidationError(String aField, String aMessage, Object aParameter) { + this (aField, aMessage, new Object[] {aParameter}); + } + + public ValidationError(String aField, String aMessage, Object[] aParameters) { + field = aField; + message = aMessage; + parameters = Arrays.asList(aParameters); + } + + public String getMessage() { + return message; + } + + public String getField() { + return field; + } + + public List getParameters() { + return parameters; + } + } + + + +} \ No newline at end of file diff --git a/source/mircoders/localizer/basic/MirBasicLocalizer.java b/source/mircoders/localizer/basic/MirBasicLocalizer.java index 3dfb79a3..06823a1a 100755 --- a/source/mircoders/localizer/basic/MirBasicLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicLocalizer.java @@ -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(); }; diff --git a/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java b/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java index ad7dae97..f4b5d5c7 100755 --- a/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java @@ -1,90 +1,121 @@ -/* - * 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(); - } - -} +/* + * 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 java.util.*; +import javax.servlet.http.HttpServletRequest; + +import mir.log.LoggerWrapper; +import mir.servlet.*; +import mir.config.*; +import mir.session.Request; +import mir.session.Response; +import mir.session.*; + +import mircoders.entity.EntityComment; +import mircoders.entity.EntityContent; +import mircoders.global.MirGlobal; +import mircoders.global.ProducerEngine; +import mircoders.localizer.*; + +public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer { + private List afterContentProducerTasks; + private List afterCommentProducerTasks; + protected LoggerWrapper logger; + protected MirPropertiesConfiguration configuration; + + + public MirBasicOpenPostingLocalizer() throws MirLocalizerExc, MirLocalizerFailure { + logger = new LoggerWrapper("Localizer.Basic.OpenPosting"); + + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (Throwable e) { + throw new MirLocalizerFailure("Can't get configuration: " + e.getMessage(), e); + } + + 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()); + + throw new MirLocalizerFailure(t); + } + } + + public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure { + if (aSession.getAttribute("handler")==null) + aSession.setAttribute("handler", new MirBasicCommentPostingSessionHandler()); + + return (SessionHandler) aSession.getAttribute("handler"); + } + + public void afterContentPosting() { + MirGlobal.producerEngine().addTasks(afterContentProducerTasks); + } + + public void afterContentPosting(EntityContent aContent) { + afterContentPosting(); + } + + public void afterCommentPosting(EntityComment aComment) { + afterCommentPosting(); + } + + public void afterCommentPosting() { + MirGlobal.producerEngine().addTasks(afterCommentProducerTasks); + } + + public String generateOnetimePassword() { + 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); + } + +} diff --git a/source/mircoders/media/MediaUploadProcessor.java b/source/mircoders/media/MediaUploadProcessor.java new file mode 100755 index 00000000..a23be012 --- /dev/null +++ b/source/mircoders/media/MediaUploadProcessor.java @@ -0,0 +1,115 @@ +/* + * 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 java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Map; + +import mir.entity.Entity; +import mir.media.MediaExc; +import mir.media.MediaFailure; +import mir.media.MediaHelper; +import mir.media.MirMedia; +import mir.misc.StringUtil; +import mir.session.UploadedFile; +import mir.storage.Database; + +import mircoders.module.ModuleMediaType; + +public class MediaUploadProcessor { + public static Entity processMediaUpload(UploadedFile aFile) throws MediaExc, MediaFailure { + String mediaId; + MirMedia mediaHandler; + Entity mediaType; + ModuleMediaType mediaTypeModule; + Database mediaStorage; + Map values = new HashMap(); + String MediaId; + Entity mediaEntity; + + + try { + String contentType = aFile.getContentType(); + + if (contentType.equals("text/plain") || + contentType.equals("application/octet-stream") || + contentType == null) { + throw new MediaExc("Invalid content-type: " + contentType); + } + + values.put("date", StringUtil.date2webdbDate(new GregorianCalendar())); + values.put("is_produced", "0"); + values.put("is_published", "1"); + values.put("to_publisher", "0"); + values.put("to_media_folder", "7"); + values.put("title", ""); + + mediaTypeModule = new ModuleMediaType(); + mediaType = mediaTypeModule.findMediaTypeForMimeType(contentType); + + try { + mediaHandler = MediaHelper.getHandler(mediaType); + mediaStorage = MediaHelper.getStorage(mediaType, "mircoders.storage.Database"); + } + catch (Throwable e) { + throw new MediaFailure(e); + } + + values.put("to_media_type", mediaType.getId()); + + try { + mediaEntity = (Entity) mediaStorage.getEntityClass().newInstance(); + mediaEntity.setStorage(mediaStorage); + } + catch (Throwable e) { + throw new MediaFailure(e); + } + + mediaEntity.setValues(values); + mediaId = mediaEntity.insert(); + + try { + mediaHandler.set(aFile.getInputStream(), mediaEntity, mediaType); + } + catch (Throwable e) { + throw new MediaFailure(e); + } + + return mediaEntity; + } + catch (Throwable e) { + throw new MediaFailure(e); + } + + } +} \ No newline at end of file diff --git a/source/mircoders/media/UnsupportedMediaFormatExc.java b/source/mircoders/media/UnsupportedMediaFormatExc.java index af8ec8c3..57237e3c 100755 --- a/source/mircoders/media/UnsupportedMediaFormatExc.java +++ b/source/mircoders/media/UnsupportedMediaFormatExc.java @@ -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; diff --git a/source/mircoders/module/ModuleContent.java b/source/mircoders/module/ModuleContent.java index f697f8bf..cd4142e5 100755 --- a/source/mircoders/module/ModuleContent.java +++ b/source/mircoders/module/ModuleContent.java @@ -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 +/** * + *

Title: ModuleContent

+ *

Description: helper routines to manage articles

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @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;iTitle:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author the mir coders + * @version 1.0 + */ + +public class ModuleUploadedMedia extends AbstractModule +{ + static LoggerWrapper logger = new LoggerWrapper("Module.UploadedMedia"); + + public ModuleUploadedMedia(StorageObject aStorage) { + theStorage = aStorage; + } } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletHelper.java b/source/mircoders/servlet/ServletHelper.java index efe8dbce..dbffa3ac 100755 --- a/source/mircoders/servlet/ServletHelper.java +++ b/source/mircoders/servlet/ServletHelper.java @@ -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.servlet; import java.io.PrintWriter; @@ -88,7 +119,7 @@ public class ServletHelper { Generator generator; try { - generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator); + generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator); generator.generate(aWriter, aGenerationData, new PrintWriter(new NullWriter())); } diff --git a/source/mircoders/servlet/ServletModuleAbuse.java b/source/mircoders/servlet/ServletModuleAbuse.java index e2d955b0..faf1e815 100755 --- a/source/mircoders/servlet/ServletModuleAbuse.java +++ b/source/mircoders/servlet/ServletModuleAbuse.java @@ -1,5 +1,36 @@ -package mircoders.servlet; - +/* + * 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.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; @@ -10,141 +41,141 @@ import mir.servlet.ServletModule; import mir.servlet.ServletModuleFailure; import mir.util.HTTPRequestParser; import mir.util.URLBuilder; -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; + +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); + } + } } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletModuleOpenIndy.java b/source/mircoders/servlet/ServletModuleOpenIndy.java index dac1b8e4..890c57c2 100755 --- a/source/mircoders/servlet/ServletModuleOpenIndy.java +++ b/source/mircoders/servlet/ServletModuleOpenIndy.java @@ -1,1159 +1,1291 @@ -/* - * 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= 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); - } - } -} +/* + * 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.Set; +import java.util.Vector; +import java.util.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpUtils; + +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.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.*; +import mircoders.pdf.PDFGenerator; +import mir.session.*; +import mir.util.HTTPRequestParser; +import mir.util.StringRoutines; +import mircoders.entity.EntityComment; +import mircoders.entity.EntityContent; +import mircoders.global.MirGlobal; +import mircoders.media.*; +import mircoders.media.UnsupportedMediaFormatExc; +import mircoders.module.ModuleComment; +import mircoders.module.ModuleContent; +import mircoders.module.ModuleImages; +import mircoders.module.ModuleTopics; +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.DatabaseCommentToMedia; +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.74 2003/04/16 03:26:46 zapata 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(); + commentModule = new ModuleComment(DatabaseComment.getInstance()); + mainModule = commentModule; + 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 + + 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); + } + 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"); + withValues.put("is_html", "0"); + + //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); + + SimpleResponse response = new SimpleResponse(); + response.setResponseGenerator(commentFormDoneTemplate); + + if (id == null) { + deliver(req, res, (Map)null, null, commentFormDupeTemplate); + } + else { + DatabaseContent.getInstance().setUnproduced("id=" + aid); + + try { + EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id); + MirGlobal.localizer().openPostings().afterCommentPosting(comment); + MirGlobal.abuse().checkComment( + comment, new HTTPAdapters.HTTPRequestAdapter(req), res); + } + catch (Throwable t) { + throw new ServletModuleExc(t.getMessage()); + } + } + + // redirecting to url + // should implement back to article + deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator()); + } + 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 = generateOnetimePassword(); + 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"); + + 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; + } + + 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;i0) { + MirGlobal.localizer().openPostings().processCommentPosting(request, session, response); + + ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator()); + } + else { + EntityComment comment = (EntityComment) commentModule.createNew (); + comment.setValues(commentFields); + MirGlobal.abuse().checkComment(comment, aRequest, aResponse); + MirGlobal.localizer().openPostings().finishCommentPosting(request, session, comment); + + String id = comment.insert(); + if(id==null){ + MirGlobal.localizer().openPostings().afterDuplicateCommentPosting(request, session, response, comment); + + logger.info("Dupe comment rejected"); + + ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator()); + } + else { + // media + List mediaItems = new Vector(); + i = request.getUploadedFiles().iterator(); + while (i.hasNext()) { + UploadedFile file = (UploadedFile) i.next(); + Entity mediaItem = MediaUploadProcessor.processMediaUpload(file); + DatabaseCommentToMedia.getInstance().addMedia(comment.getId(), mediaItem.getId()); + } + + MirGlobal.localizer().openPostings().afterCommentPosting(request, session, response, comment); + + MirGlobal.abuse().logComment(aRequest.getRemoteAddr(), id, new Date(), (String) aRequest.getHeader("User-Agent")); + DatabaseContent.getInstance().setUnproduced("id=" + comment.getValue("to_media")); + logger.info("Comment posted"); + ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator()); + } + } + } + catch (Throwable t) { + ExceptionFunctions.traceCauseException(t).printStackTrace(); + + throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t); + } + } +*/ + + private static final String SESSION_REQUEST_KEY="sessionid"; + + public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + + try { + Request request = new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest, 1000000, "/tmp")); + + if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() && + !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY))) + aRequest.getSession().invalidate(); + + Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession()); + + SimpleResponse response = new SimpleResponse( + ServletHelper.makeGenerationData(new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}, + "bundles.open")); + + response.setResponseValue("actionURL", aResponse.encodeURL(HttpUtils.getRequestURL(aRequest).toString())+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId()); + + SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session); + + handler.processRequest(request, session, response); + ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator()); + } + catch (Throwable t) { + logger.error(t.toString()); + t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE)); + + throw new ServletModuleFailure(t); + } + } + + /** + * 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."); + } + } + */ + + public String generateOnetimePassword() { + 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); + } + + 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); + 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); + } + } + + private String createOneTimePasswd() { + return ""; + } +} diff --git a/source/tool/BundleTool.java b/source/tool/BundleTool.java index 942a2b24..56c6e9b8 100755 --- a/source/tool/BundleTool.java +++ b/source/tool/BundleTool.java @@ -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 tool; import java.util.*; diff --git a/templates/admin/FUNCTIONS.template b/templates/admin/FUNCTIONS.template index 485a8340..51e10ba1 100755 --- a/templates/admin/FUNCTIONS.template +++ b/templates/admin/FUNCTIONS.template @@ -79,6 +79,23 @@ + + + + + ${label}: + + + + + + + + 4 functions to create Table rows with input-fields @@ -87,7 +104,7 @@ - + @@ -99,33 +116,52 @@ - + + + + + ${label}: + + + + checked
>   + + + - - + ${label}: + +
+ ${hint} +
- +
- + + ${label}: + +
+ ${hint} +
- +
diff --git a/templates/admin/abuse.filters.template b/templates/admin/abuse.filters.template index b8410ad5..dc78231c 100755 --- a/templates/admin/abuse.filters.template +++ b/templates/admin/abuse.filters.template @@ -9,7 +9,7 @@ diff --git a/templates/admin/abuse.template b/templates/admin/abuse.template index 0c82b95e..25a8083f 100755 --- a/templates/admin/abuse.template +++ b/templates/admin/abuse.template @@ -25,79 +25,24 @@ ${lang("abuse.setting")} ${lang("abuse.value")} - - - ${lang("abuse.disableopenpostings")} - - - checked="1"
> - - - - - ${lang("abuse.openpostingpassword")} - - - checked="1"> - - + + +   - - - - ${lang("abuse.logpostings")} - - - checked="1"> - - - - - ${lang("abuse.logsize")} - - - - - + + +   - - - ${lang("abuse.cookies")} - - - checked="1"> - - +   - - - - ${lang("abuse.articleaction")} - - - - - - - - ${lang("abuse.commentaction")} - - - - - + + + + diff --git a/templates/admin/articletypelist.template b/templates/admin/articletypelist.template index 73556119..904a74c5 100755 --- a/templates/admin/articletypelist.template +++ b/templates/admin/articletypelist.template @@ -6,6 +6,7 @@ + @@ -19,17 +20,16 @@ - + - + - - - + + +

${lang("no_matches_found")}

- diff --git a/templates/admin/audio.template b/templates/admin/audio.template index d916214d..b18e018e 100755 --- a/templates/admin/audio.template +++ b/templates/admin/audio.template @@ -85,8 +85,8 @@ function openWin(url) { - - + +   diff --git a/templates/admin/comment.template b/templates/admin/comment.template index 517f6fe1..d96f46aa 100755 --- a/templates/admin/comment.template +++ b/templates/admin/comment.template @@ -31,52 +31,21 @@ ${utility.encodeHTML(utility.encodeHTML(comment.webdb_create))} - - - - - ${lang("comment.status")} - - - - - - - - - - - - - + + + + + + + + + + - - - - ${lang("comment.language")} - - - - - - - - - ${lang("comment.text")}
- ${lang("comment.html")} checked> - - - - - + + + + diff --git a/templates/admin/content.template b/templates/admin/content.template index 944270ab..7b73ce28 100755 --- a/templates/admin/content.template +++ b/templates/admin/content.template @@ -59,39 +59,14 @@ ${lang("content.create_date")}: - ${utility.encodeHTML(article.webdb_create)}
${lang("edit")}: -   (yyyy-mm-dd [HH:mm]) + ${utility.encodeHTML(article.webdb_create)}
${lang("edit")}: +   (yyyy-mm-dd [HH:mm]) - - - ${lang("content.articletype")}: - - - - - - - - - ${lang("content.language")} - - - - - - - - + + + @@ -131,49 +106,23 @@ - - - - - - - - - - - + + + + + + + + + + + + + + + - - ${lang("content.abstract")}: - - - - - - - - - ${lang("content.content")}: -
- ${lang("content.html")}  - checked>   - - - - - - - - - ${lang("content.comment")}:
- ${lang("content.internal")} - - - - - - diff --git a/templates/admin/image.template b/templates/admin/image.template index d73d1539..6972c927 100755 --- a/templates/admin/image.template +++ b/templates/admin/image.template @@ -91,8 +91,8 @@ function openWin(url) { - - + +   diff --git a/templates/admin/media.template b/templates/admin/media.template index a7e827b9..c2ec8cc1 100755 --- a/templates/admin/media.template +++ b/templates/admin/media.template @@ -87,8 +87,8 @@ function openWin(url) { - - + +   diff --git a/templates/admin/mediafolder.template b/templates/admin/mediafolder.template index 85e5145f..e832b7b2 100755 --- a/templates/admin/mediafolder.template +++ b/templates/admin/mediafolder.template @@ -19,8 +19,8 @@ - - + + diff --git a/templates/admin/message.template b/templates/admin/message.template index bf99bcd2..bccccf1e 100755 --- a/templates/admin/message.template +++ b/templates/admin/message.template @@ -31,7 +31,7 @@ - + diff --git a/templates/admin/topic.template b/templates/admin/topic.template index 4d062065..f27f39fd 100755 --- a/templates/admin/topic.template +++ b/templates/admin/topic.template @@ -20,7 +20,7 @@ - + diff --git a/templates/admin/video.template b/templates/admin/video.template index 71283a4d..7736abc9 100755 --- a/templates/admin/video.template +++ b/templates/admin/video.template @@ -85,8 +85,8 @@ function openWin(url) { - - + + @@ -133,11 +133,11 @@ function openWin(url) {
 
- + - ${lang("media.is_published")} checked> -    + ${lang("media.is_published")} checked> +