2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
6 * Mir is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * Mir is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Mir; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * In addition, as a special exception, The Mir-coders gives permission to link
21 * the code of this program with any library licensed under the Apache Software License,
22 * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23 * (or with modified versions of the above that use the same license as the above),
24 * and distribute linked combinations including the two. You must obey the
25 * GNU General Public License in all respects for all of the code used other than
26 * the above mentioned libraries. If you modify this file, you may extend this
27 * exception to your version of the file, but you are not obligated to do so.
28 * If you do not wish to do so, delete this exception statement from your version.
31 package mircoders.servlet;
34 import gnu.regexp.REMatch;
36 import java.io.ByteArrayOutputStream;
37 import java.io.IOException;
38 import java.io.PrintWriter;
39 import java.io.StringWriter;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Collections;
43 import java.util.GregorianCalendar;
44 import java.util.HashMap;
45 import java.util.Iterator;
46 import java.util.List;
47 import java.util.ListIterator;
48 import java.util.Locale;
50 import java.util.Random;
52 import java.util.Vector;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.servlet.http.HttpServletResponse;
56 import javax.servlet.http.HttpSession;
58 import mir.entity.Entity;
59 import mir.generator.Generator;
60 import mir.log.LoggerWrapper;
61 import mir.misc.StringUtil;
62 import mir.servlet.ServletModule;
63 import mir.servlet.ServletModuleExc;
64 import mir.servlet.ServletModuleFailure;
65 import mir.servlet.ServletModuleUserExc;
66 import mir.session.HTTPAdapters;
67 import mir.session.Request;
68 import mir.session.Session;
69 import mir.session.SessionHandler;
70 import mir.session.SimpleResponse;
71 import mir.session.UploadedFile;
72 import mir.storage.StorageObjectFailure;
73 import mir.util.ExceptionFunctions;
74 import mir.util.HTTPParsedRequest;
75 import mir.util.HTTPRequestParser;
76 import mir.util.StringRoutines;
77 import mircoders.entity.EntityComment;
78 import mircoders.entity.EntityContent;
79 import mircoders.global.CacheKey;
80 import mircoders.global.MirGlobal;
81 import mircoders.media.MediaUploadProcessor;
82 import mircoders.module.ModuleComment;
83 import mircoders.module.ModuleContent;
84 import mircoders.module.ModuleImages;
85 import mircoders.module.ModuleMediaType;
86 import mircoders.module.ModuleTopics;
87 import mircoders.pdf.PDFGenerator;
88 import mircoders.search.AudioSearchTerm;
89 import mircoders.search.ContentSearchTerm;
90 import mircoders.search.ImagesSearchTerm;
91 import mircoders.search.KeywordSearchTerm;
92 import mircoders.search.TextSearchTerm;
93 import mircoders.search.TopicMatrixSearchTerm;
94 import mircoders.search.TopicSearchTerm;
95 import mircoders.search.UnIndexedSearchTerm;
96 import mircoders.search.VideoSearchTerm;
97 import mircoders.storage.DatabaseComment;
98 import mircoders.storage.DatabaseContent;
99 import mircoders.storage.DatabaseContentToMedia;
100 import mircoders.storage.DatabaseContentToTopics;
101 import mircoders.storage.DatabaseImages;
102 import mircoders.storage.DatabaseLanguage;
103 import mircoders.storage.DatabaseTopics;
105 import org.apache.commons.fileupload.FileItem;
106 import org.apache.commons.net.smtp.SMTPClient;
107 import org.apache.commons.net.smtp.SMTPReply;
108 import org.apache.lucene.analysis.standard.StandardAnalyzer;
109 import org.apache.lucene.document.Document;
110 import org.apache.lucene.queryParser.QueryParser;
111 import org.apache.lucene.search.Hits;
112 import org.apache.lucene.search.IndexSearcher;
113 import org.apache.lucene.search.Query;
114 import org.apache.lucene.search.Searcher;
115 import org.apache.struts.util.MessageResources;
118 * ServletModuleOpenIndy -
119 * is the open-access-servlet, which is responsible for
120 * adding comments to articles &
121 * open-postings to the newswire
123 * @author mir-coders group
124 * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.8 2003/10/23 14:55:25 rk Exp $
128 public class ServletModuleOpenIndy extends ServletModule
131 private String commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
132 private String postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
133 private String searchResultsTemplate;
134 private String prepareMailTemplate,sentMailTemplate,emailAnArticleTemplate;
135 private ModuleContent contentModule;
136 private ModuleComment commentModule;
137 private ModuleImages imageModule;
138 private ModuleTopics topicsModule;
139 private String directOp ="yes";
140 // Singelton / Kontruktor
141 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
142 public static ServletModule getInstance() { return instance; }
144 private ServletModuleOpenIndy() {
147 logger = new LoggerWrapper("ServletModule.OpenIndy");
149 commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
150 commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
151 commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
153 postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
154 postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
155 postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
157 searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
158 prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
159 emailAnArticleTemplate = configuration.getString("ServletModule.OpenIndy.MailableArticleTemplate");
160 sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
161 directOp = configuration.getString("DirectOpenposting").toLowerCase();
162 commentModule = new ModuleComment(DatabaseComment.getInstance());
163 mainModule = commentModule;
164 contentModule = new ModuleContent(DatabaseContent.getInstance());
165 topicsModule = new ModuleTopics(DatabaseTopics.getInstance());
166 imageModule = new ModuleImages(DatabaseImages.getInstance());
167 defaultAction="addposting";
169 catch (StorageObjectFailure e) {
170 logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
175 * Method to return an "apology" when open postings are disabled
179 * @throws ServletModuleExc
180 * @throws ServletModuleUserExc
181 * @throws ServletModuleFailure
183 public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
184 deliver(aRequest, aResponse, (Map) null, null,
185 configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
189 * Method for making a comment
192 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
193 if (MirGlobal.abuse().getOpenPostingDisabled()) {
194 openPostingDisabled(req, res);
199 String aid = req.getParameter("aid"); // the article id the comment will belong to
201 if (aid != null && !aid.equals("")) {
203 Map mergeData = new HashMap();
206 if (MirGlobal.abuse().getOpenPostingPassword()) {
207 String passwd = this.createOneTimePasswd();
208 HttpSession session = req.getSession(false);
209 session.setAttribute("passwd", passwd);
210 mergeData.put("passwd", passwd);
213 mergeData.put("passwd", (String)null);
215 mergeData.put("aid", aid);
217 Map extraInfo = new HashMap();
218 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
220 deliver(req, res, mergeData, extraInfo, commentFormTemplate);
222 catch (Throwable t) {
223 throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
227 throw new ServletModuleExc("aid not set!");
231 * Method for inserting a comment into the Database and delivering
232 * the commentDone Page
235 public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
236 if (MirGlobal.abuse().getOpenPostingDisabled()) {
237 openPostingDisabled(req, res);
242 String aid = req.getParameter("to_media"); // the article id the comment will belong to
243 if (aid != null && !aid.equals("")) {
244 // ok, collecting data from form
246 Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
248 //no html in comments(for now)
249 for (Iterator i = withValues.keySet().iterator(); i.hasNext(); ) {
250 String k = (String) i.next();
251 String v = (String) withValues.get(k);
253 withValues.put(k, StringUtil.removeHTMLTags(v));
255 withValues.put("is_published", "1");
256 withValues.put("to_comment_status", "1");
257 withValues.put("is_html", "0");
259 //checking the onetimepasswd
260 HttpSession session = req.getSession(false);
261 String sessionPasswd = (String) session.getAttribute("passwd");
262 if (sessionPasswd != null) {
263 String passwd = req.getParameter("passwd");
264 if (passwd == null || passwd.length() == 0) {
265 throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});
267 if (!sessionPasswd.equals(passwd)) {
268 throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});
270 session.invalidate();
273 String id = mainModule.add(withValues);
275 SimpleResponse response = new SimpleResponse();
276 response.setResponseGenerator(commentFormDoneTemplate);
279 deliver(req, res, (Map)null, null, commentFormDupeTemplate);
282 DatabaseContent.getInstance().setUnproduced("id=" + aid);
285 EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
286 MirGlobal.localizer().openPostings().afterCommentPosting(comment);
287 MirGlobal.abuse().checkComment(
288 comment, new HTTPAdapters.HTTPRequestAdapter(req), res);
290 catch (Throwable t) {
291 throw new ServletModuleExc(t.getMessage());
295 // redirecting to url
296 // should implement back to article
297 deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());
299 catch (Throwable e) {
300 throw new ServletModuleFailure(e);
304 throw new ServletModuleExc("aid not set!");
309 * Method for delivering the form-Page for open posting
312 public void addposting(HttpServletRequest req, HttpServletResponse res)
313 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
316 if (MirGlobal.abuse().getOpenPostingDisabled()) {
317 openPostingDisabled(req, res);
322 Map mergeData = new HashMap();
325 if (MirGlobal.abuse().getOpenPostingPassword()) {
326 String passwd = generateOnetimePassword();
327 HttpSession session = req.getSession(false);
328 session.setAttribute("passwd", passwd);
329 mergeData.put("passwd", passwd);
332 mergeData.put("passwd", (String)null);
335 String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
336 String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
337 String numOfMedia = req.getParameter("medianum");
339 if (numOfMedia == null || numOfMedia.equals("")) {
340 numOfMedia = defaultMedia;
342 else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
343 numOfMedia = maxMedia;
346 int mediaNum = Integer.parseInt(numOfMedia);
347 List mediaFields = new Vector();
348 for (int i = 0; i < mediaNum; i++) {
349 Integer mNum = new Integer(i + 1);
350 mediaFields.add(mNum.toString());
352 mergeData.put("medianum", numOfMedia);
353 mergeData.put("mediafields", mediaFields);
354 mergeData.put("to_topic", null);
356 Map extraInfo = new HashMap();
357 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
358 extraInfo.put("themenPopupData", DatabaseTopics.getInstance().getPopupData());
360 extraInfo.put("topics", topicsModule.getTopicsList());
361 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
363 catch (Throwable t) {
364 throw new ServletModuleFailure(t);
369 * Method for inserting an open posting into the Database and delivering
370 * the postingDone Page
373 public void insposting(HttpServletRequest aRequest, HttpServletResponse aResponse) throws
374 ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
375 if (MirGlobal.abuse().getOpenPostingDisabled()) {
376 openPostingDisabled(aRequest, aResponse);
382 HTTPParsedRequest parsedRequest = new HTTPParsedRequest(
384 configuration.getString("Mir.DefaultEncoding"),
385 configuration.getInt("MaxMediaUploadSize")*1024,
386 configuration.getString("TempDir"));
388 Map mergeData = new HashMap();
390 HttpSession session = aRequest.getSession(false);
391 String sessionPasswd = (String) session.getAttribute("passwd");
392 if (sessionPasswd != null) {
393 String passwd = (String) parsedRequest.getParameter("passwd");
395 if (passwd == null || passwd.length() == 0) {
396 throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});
398 if (!sessionPasswd.equals(passwd)) {
399 throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});
401 session.invalidate();
404 if ((((String) parsedRequest.getParameter("title")).length() == 0) ||
405 (((String) parsedRequest.getParameter("description")).length() == 0) ||
406 (((String) parsedRequest.getParameter("content_data")).length() == 0))
407 throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
409 List mediaList = new Vector();
410 Iterator i = parsedRequest.getFiles().iterator();
412 while (i.hasNext()) {
413 UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
414 Map mediaValues = new HashMap();
416 String suffix = file.getFieldName().substring(5); // media${m}
417 logger.debug("media_title" + suffix);
418 String title = parsedRequest.getParameter("media_title" + suffix);
420 mediaValues.put("title", StringUtil.removeHTMLTags(title));
421 mediaValues.put("creator", StringUtil.removeHTMLTags(parsedRequest.getParameter("creator")));
422 mediaValues.put("to_publisher", "0");
423 mediaValues.put("is_published", "1");
424 mediaValues.put("to_media_folder", "7");
426 mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
429 Map withValues = new HashMap();
430 i = DatabaseContent.getInstance().getFields().iterator();
431 while (i.hasNext()) {
432 String field = (String) i.next();
433 String value = parsedRequest.getParameter(field);
435 withValues.put(field, value);
439 for (i = withValues.keySet().iterator(); i.hasNext(); ) {
440 String k = (String) i.next();
441 String v = (String) withValues.get(k);
443 if (k.equals("content_data")) {
444 //this doesn't quite work yet, so for now, all html goes
445 //withValues.put(k,StringUtil.approveHTMLTags(v));
446 withValues.put(k, StringUtil.deleteForbiddenTags(v));
448 else if (k.equals("description")) {
449 String tmp = StringUtil.deleteForbiddenTags(v);
450 withValues.put(k, StringUtil.deleteHTMLTableTags(tmp));
453 withValues.put(k, StringUtil.removeHTMLTags(v));
457 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
458 withValues.put("publish_path",
459 StringUtil.webdbDate2path( (String) withValues.get("date")));
460 withValues.put("is_produced", "0");
461 withValues.put("is_published", "1");
462 if (directOp.equals("yes"))
463 withValues.put("to_article_type", "1");
465 withValues.put("to_publisher", "1");
467 // inserting content into database
468 String cid = contentModule.add(withValues);
469 logger.debug("id: " + cid);
470 //insert was not successfull
472 deliver(aRequest, aResponse, mergeData, null, postingFormDupeTemplate);
476 List topics = parsedRequest.getParameterList("to_topic");
477 if (topics.size() > 0) {
479 DatabaseContentToTopics.getInstance().setTopics(cid, topics);
481 catch (Throwable e) {
482 logger.error("setting content_x_topic failed");
483 contentModule.deleteById(cid);
484 throw new ServletModuleFailure(
485 "smod - openindy :: insposting: setting content_x_topic failed: " +
490 i = mediaList.iterator();
491 while (i.hasNext()) {
492 Entity mediaEnt = (Entity) i.next();
493 DatabaseContentToMedia.getInstance().addMedia(cid, mediaEnt.getId());
496 EntityContent article = (EntityContent) contentModule.getById(cid);
498 MirGlobal.abuse().checkArticle(
499 article, new HTTPAdapters.HTTPRequestAdapter(aRequest), aResponse);
500 MirGlobal.localizer().openPostings().afterContentPosting(article);
502 catch (Throwable t) {
503 logger.error("Error while post-processing article: " + t.getMessage());
505 deliver(aRequest, aResponse, mergeData, null, postingFormDoneTemplate);
507 catch (Throwable e) {
508 e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
509 Throwable cause = ExceptionFunctions.traceCauseException(e);
511 if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
512 throw new ServletModuleUserExc("media.unsupportedformat", new String[] {});
514 throw new ServletModuleFailure(e);
519 * Due to a serious shortcoming of Tomcat 3.3, an extra sessionid parameter is
520 * generated into open session urls. Tomcat 3.3 makes it impossible to
521 * distinguish between sessions that are identified using a url and those
522 * that are identified using cookies: if both a sessionid cookie and a sessionid
523 * url are available, tomcat 3.3 pretends the url wasn't there...
525 private static final String SESSION_REQUEST_KEY="sessionid";
528 * Selects the language for the response.
534 protected Locale getResponseLocale(HttpSession aSession, HttpServletRequest aRequest) {
535 String requestLanguage = aRequest.getParameter("language");
536 String sessionLanguage = (String) aSession.getAttribute("language");
537 String acceptLanguage = aRequest.getLocale().getLanguage();
538 String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
540 String language = requestLanguage;
543 language = sessionLanguage;
546 language = acceptLanguage;
549 language = defaultLanguage;
551 aSession.setAttribute("language", language);
553 return new Locale(language, "");
557 * Dispatch method for open sessions: a flexible extensible and customizable way
558 * for open access. Can be used for postings, but also for lots of other stuff.
562 * @throws ServletModuleExc
563 * @throws ServletModuleUserExc
564 * @throws ServletModuleFailure
567 public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse)
568 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
572 new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
573 configuration.getString("Mir.DefaultEncoding"),
574 configuration.getInt("MaxMediaUploadSize")*1024,
575 configuration.getString("TempDir")));
577 if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
578 !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
579 aRequest.getSession().invalidate();
581 Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
583 SimpleResponse response = new SimpleResponse(
584 ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getResponseLocale(aRequest.getSession(), aRequest), getFallbackLocale(aRequest)},
587 response.setResponseValue("actionURL", aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/OpenMir")+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
589 SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);
591 handler.processRequest(request, session, response);
592 ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
594 catch (Throwable t) {
595 logger.error(t.toString());
596 t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
598 throw new ServletModuleFailure(t);
603 * Method for preparing and sending a content as an email message
606 public void mail(HttpServletRequest req, HttpServletResponse res)
607 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
609 String aid = req.getParameter("mail_aid");
611 throw new ServletModuleExc("An article id must be specified in requests to email an article. Something therefore went badly wrong....");
614 String to = req.getParameter("mail_to");
615 String from = req.getParameter("mail_from");
616 String from_name = req.getParameter("mail_from_name");
617 String from_ip = req.getRemoteAddr();
618 String comment = req.getParameter("mail_comment");
619 String mail_language = req.getParameter("mail_language");
621 Map mergeData = new HashMap();
622 mergeData.put("mail_to",to);
623 mergeData.put("mail_from",from);
624 mergeData.put("mail_from_name",from_name);
625 mergeData.put("mail_comment",comment);
626 mergeData.put("mail_aid",aid);
627 mergeData.put("mail_language",mail_language);
630 if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
631 deliver(req, res, mergeData, null, prepareMailTemplate);
634 //run checks on to and from and mail_language to make sure no monkey business occurring
635 if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {
636 throw new ServletModuleExc("Invalid language");
638 if (to.indexOf('\n') != -1
639 || to.indexOf('\r') != -1
640 || to.indexOf(',') != -1) {
641 throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});
643 if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {
644 throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});
647 CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
650 if (MirGlobal.mruCache().hasObject(theCacheKey)){
651 logger.info("fetching email text for article "+aid+" from cache");
652 theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
655 EntityContent contentEnt;
657 contentEnt = (EntityContent) contentModule.getById(aid);
658 StringWriter theEMailTextWriter = new StringWriter();
659 PrintWriter dest = new PrintWriter(theEMailTextWriter);
660 Map articleData = new HashMap();
661 articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
662 articleData.put("languagecode", mail_language);
663 deliver(dest, req, res, articleData, null, emailAnArticleTemplate, mail_language);
664 theEmailText = theEMailTextWriter.toString();
665 MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
667 catch (Throwable e) {
668 throw new ServletModuleFailure("Couldn't get content for article " + aid + mail_language + ": " + e.getMessage(), e);
672 String content = theEmailText;
676 content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
677 // put in the comment where it should go
678 if (comment != null) {
679 String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
681 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
684 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
689 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
692 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
696 SMTPClient client=new SMTPClient();
699 client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
701 reply = client.getReplyCode();
703 if (!SMTPReply.isPositiveCompletion(reply)) {
705 throw new ServletModuleExc("SMTP server refused connection.");
708 client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
711 //mission accomplished
712 deliver(req, res, mergeData, null, sentMailTemplate);
714 catch(IOException e) {
715 if(client.isConnected()) {
718 } catch(IOException f) {
722 throw new ServletModuleFailure(e);
730 * Method for querying a lucene index
734 * @throws ServletModuleExc
735 * @throws ServletModuleUserExc
736 * @throws ServletModuleFailure
739 public void search(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
741 final String[] search_variables = {
742 "search_content", "search_boolean", "search_creator",
743 "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",
744 "search_submit", "search_back", "search_forward"};
745 HTTPRequestParser requestParser = new HTTPRequestParser(req);
749 HttpSession session = req.getSession(false);
751 String queryString = "";
753 Map mergeData = new HashMap();
755 KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted", "search_date", "webdb_create_formatted", "webdb_create_formatted", "webdb_create_formatted");
756 UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("", "", "", "where", "where");
757 TextSearchTerm creatorTerm = new TextSearchTerm("creator", "search_creator", "creator", "creator", "creator");
758 TextSearchTerm titleTerm = new TextSearchTerm("title", "search_content", "title", "title", "title");
759 TextSearchTerm descriptionTerm = new TextSearchTerm("description", "search_content", "description", "description", "description");
760 ContentSearchTerm contentTerm = new ContentSearchTerm("content_data", "search_content", "content", "", "");
761 TopicSearchTerm topicTerm = new TopicSearchTerm();
762 TopicMatrixSearchTerm topicMatrixTerm = new TopicMatrixSearchTerm();
763 ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
764 AudioSearchTerm audioTerm = new AudioSearchTerm();
765 VideoSearchTerm videoTerm = new VideoSearchTerm();
767 //make the query available to subsequent iterations
769 Iterator j = Arrays.asList(search_variables).iterator();
770 while (j.hasNext()) {
771 String variable = (String) j.next();
773 mergeData.put(variable, requestParser.getParameter(variable));
777 mergeData.put("topics", DatabaseTopics.getInstance().getPopupData());
779 catch (Throwable e) {
780 logger.debug("Can't get topics: " + e.toString());
783 String searchBackValue = req.getParameter("search_back");
784 String searchForwardValue = req.getParameter("search_forward");
786 if (searchBackValue != null) {
787 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
788 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() - increment;
791 if (newPosition >= totalHits)
792 newPosition = totalHits - 1;
793 session.setAttribute("positionInResults", new Integer(newPosition));
796 if (searchForwardValue != null) {
797 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
798 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() + increment;
801 if (newPosition >= totalHits)
802 newPosition = totalHits - 1;
804 session.setAttribute("positionInResults", new Integer(newPosition));
807 String indexPath = configuration.getString("IndexPath");
809 String creatorFragment = creatorTerm.makeTerm(req);
810 if (creatorFragment != null) {
811 queryString = queryString + " +" + creatorFragment;
814 // search title, description, and content for something
815 // the contentTerm uses param "search_boolean" to combine its terms
816 String contentFragment = contentTerm.makeTerm(req);
817 if (contentFragment != null) {
818 logger.debug("contentFragment: " + contentFragment);
819 queryString = queryString + " +" + contentFragment;
822 String topicFragment = topicTerm.makeTerm(req);
823 if (topicFragment != null) {
824 queryString = queryString + " +" + topicFragment;
827 String topicMatrixFragment = topicMatrixTerm.makeTerm(req);
828 if (topicMatrixFragment != null) {
829 queryString = queryString + " +" + topicMatrixFragment;
832 String imagesFragment = imagesTerm.makeTerm(req);
833 if (imagesFragment != null) {
834 queryString = queryString + " +" + imagesFragment;
837 String audioFragment = audioTerm.makeTerm(req);
838 if (audioFragment != null) {
839 queryString = queryString + " +" + audioFragment;
842 String videoFragment = videoTerm.makeTerm(req);
843 if (videoFragment != null) {
844 queryString = queryString + " +" + videoFragment;
847 if (queryString == null || queryString == "") {
852 Searcher searcher = null;
854 searcher = new IndexSearcher(indexPath);
856 catch (IOException e) {
857 logger.debug("Can't open indexPath: " + indexPath);
858 throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
863 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
865 catch (Exception e) {
867 logger.debug("Query don't parse: " + queryString);
868 throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
873 hits = searcher.search(query);
875 catch (IOException e) {
877 logger.debug("Can't get hits: " + e.toString());
878 throw new ServletModuleExc("Problem getting hits!");
882 int end = hits.length();
884 String sortBy = req.getParameter("search_sort");
885 if (sortBy == null || sortBy.equals("")) {
886 throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
889 // here is where the documents will go for storage across sessions
890 ArrayList theDocumentsSorted = new ArrayList();
892 if (sortBy.equals("score")) {
893 for (int i = start; i < end; i++) {
894 theDocumentsSorted.add(hits.doc(i));
898 // then we'll sort by date!
899 Map dateToPosition = new HashMap(end, 1.0F); //we know how big it will be
900 for (int i = start; i < end; i++) {
901 String creationDate = (hits.doc(i)).get("creationDate");
902 // do a little dance in case two contents created at the same second!
903 if (dateToPosition.containsKey(creationDate)) {
904 ( (ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
907 ArrayList thePositions = new ArrayList();
908 thePositions.add(new Integer(i));
909 dateToPosition.put(creationDate, thePositions);
912 Set keys = dateToPosition.keySet();
913 ArrayList keyList = new ArrayList(keys);
914 Collections.sort(keyList);
915 if (sortBy.equals("date_desc")) {
916 Collections.reverse(keyList);
919 if (!sortBy.equals("date_asc")) {
920 throw new ServletModuleExc("don't know how to sort by: " + sortBy);
923 ListIterator keyTraverser = keyList.listIterator();
924 while (keyTraverser.hasNext()) {
925 ArrayList positions = (ArrayList) dateToPosition.get( (keyTraverser.next()));
926 ListIterator positionsTraverser = positions.listIterator();
927 while (positionsTraverser.hasNext()) {
928 theDocumentsSorted.add(hits.doc( ( (Integer) (positionsTraverser.next())).intValue()));
936 catch (IOException e) {
937 logger.debug("Can't close searcher: " + e.toString());
938 throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
941 session.removeAttribute("numberOfHits");
942 session.removeAttribute("theDocumentsSorted");
943 session.removeAttribute("positionInResults");
945 session.setAttribute("numberOfHits", new Integer(end));
946 session.setAttribute("theDocumentsSorted", theDocumentsSorted);
947 session.setAttribute("positionInResults", new Integer(0));
950 catch (IOException e) {
951 logger.debug("Can't close searcher: " + e.toString());
952 throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
959 ArrayList theDocs = (ArrayList) session.getAttribute("theDocumentsSorted");
960 if (theDocs != null) {
962 mergeData.put("numberOfHits", ( (Integer) session.getAttribute("numberOfHits")).toString());
963 List theHits = new Vector();
964 int pIR = ( (Integer) session.getAttribute("positionInResults")).intValue();
966 int numHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
968 if (! (pIR + increment >= numHits)) {
969 mergeData.put("hasNext", "y");
972 mergeData.put("hasNext", null);
975 mergeData.put("hasPrevious", "y");
978 mergeData.put("hasPrevious", null);
981 if ( (pIR + increment) > numHits) {
985 terminus = pIR + increment;
987 for (int i = pIR; i < terminus; i++) {
988 Map h = new HashMap();
989 Document theHit = (Document) theDocs.get(i);
990 whereTerm.returnMeta(h, theHit);
991 creatorTerm.returnMeta(h, theHit);
992 titleTerm.returnMeta(h, theHit);
993 descriptionTerm.returnMeta(h, theHit);
994 dateTerm.returnMeta(h, theHit);
995 imagesTerm.returnMeta(h, theHit);
996 audioTerm.returnMeta(h, theHit);
997 videoTerm.returnMeta(h, theHit);
1000 mergeData.put("hits", theHits);
1003 catch (Throwable e) {
1004 logger.error("Can't iterate over hits: " + e.toString());
1006 throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
1009 mergeData.put("queryString", queryString);
1011 deliver(req, res, mergeData, null, searchResultsTemplate);
1013 catch (NullPointerException n) {
1014 throw new ServletModuleFailure("Null Pointer: " + n.toString(), n);
1019 * Method for dynamically generating a pdf using iText
1022 public void getpdf(HttpServletRequest req, HttpServletResponse res)
1023 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
1024 long starttime=System.currentTimeMillis();
1025 String ID_REQUEST_PARAM = "id";
1026 int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
1028 String idParam = req.getParameter(ID_REQUEST_PARAM);
1029 if (idParam != null) {
1032 RE re = new RE("[0-9]+");
1035 REMatch[] idMatches=re.getAllMatches(idParam);
1037 String cacheSelector="";
1039 for (int i = 0; i < idMatches.length; i++){
1040 cacheSelector= cacheSelector + "," + idMatches[i].toString();
1043 String cacheType="pdf";
1045 CacheKey theCacheKey = new CacheKey(cacheType,cacheSelector);
1049 if (MirGlobal.mruCache().hasObject(theCacheKey)){
1050 logger.info("fetching pdf from cache");
1051 thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
1054 logger.info("generating pdf and caching it");
1055 ByteArrayOutputStream out = new ByteArrayOutputStream();
1056 PDFGenerator pdfMaker = new PDFGenerator(out);
1058 if (idMatches.length > 1){
1060 for (int i = 0; i < idMatches.length && i < maxArticlesInNewsleter; i++){
1061 REMatch aMatch = idMatches[i];
1062 String id=aMatch.toString();
1063 EntityContent contentEnt = (EntityContent)contentModule.getById(id);
1064 pdfMaker.addIndexItem(contentEnt);
1068 for (int i = 0; i < idMatches.length; i++){
1069 REMatch aMatch = idMatches[i];
1070 String id=aMatch.toString();
1071 EntityContent contentEnt = (EntityContent)contentModule.getById(id);
1073 pdfMaker.add(contentEnt);
1077 thePDF = out.toByteArray();
1079 //and save all our hard work!
1080 MirGlobal.mruCache().storeObject(theCacheKey,thePDF);
1083 res.setContentType("application/pdf");
1084 res.setContentLength(thePDF.length);
1085 res.getOutputStream().write(thePDF);
1086 res.getOutputStream().flush();
1087 String elapsedtime=(new Long(System.currentTimeMillis()-starttime)).toString();
1088 logger.info("pdf retireval took "+elapsedtime + " milliseconds" );
1092 throw new ServletModuleExc("Missing id.");
1095 catch (Throwable t) {
1096 logger.error(t.toString());
1097 throw new ServletModuleFailure(t);
1103 public String generateOnetimePassword() {
1104 Random r = new Random();
1105 int random = r.nextInt();
1107 long l = System.currentTimeMillis();
1109 l = (l * l * l * l) / random;
1113 String returnString = "" + l;
1115 return returnString.substring(5);
1118 public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) throws ServletModuleFailure {
1120 deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);
1122 catch (Throwable t) {
1123 throw new ServletModuleFailure(t);
1127 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
1128 throws ServletModuleFailure {
1130 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open");
1131 responseData.put("data", aData);
1132 responseData.put("extra", anExtra);
1135 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1136 generator.generate(anOutputWriter, responseData, logger);
1138 anOutputWriter.close();
1140 catch (Throwable e) {
1141 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1143 throw new ServletModuleFailure(e);
1147 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator,String aLocaleString)
1148 throws ServletModuleFailure {
1150 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "bundles.open");
1151 responseData.put("data", aData);
1152 responseData.put("extra", anExtra);
1155 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1156 generator.generate(anOutputWriter, responseData, logger);
1158 anOutputWriter.close();
1160 catch (Throwable e) {
1161 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1163 throw new ServletModuleFailure(e);
1168 public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
1170 logger.error("error: " + anException);
1171 Map data = new HashMap();
1173 data.put("errorstring", anException.getMessage());
1174 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1176 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
1178 catch (Throwable e) {
1179 throw new ServletModuleFailure(e);
1183 public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
1184 PrintWriter out, ServletModuleUserExc anException) {
1186 logger.warn("user error: " + anException.getMessage());
1187 Map data = new HashMap();
1189 MessageResources messages = MessageResources.getMessageResources("bundles.open");
1190 data.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()));
1191 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1193 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
1195 catch (Throwable e) {
1196 throw new ServletModuleFailure(e);
1200 private String createOneTimePasswd() {