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.f
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;
33 import java.io.ByteArrayOutputStream;
34 import java.io.IOException;
35 import java.io.PrintWriter;
36 import java.io.StringWriter;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Collections;
40 import java.util.GregorianCalendar;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.ListIterator;
45 import java.util.Locale;
47 import java.util.Random;
49 import java.util.Vector;
50 import javax.servlet.http.HttpServletRequest;
51 import javax.servlet.http.HttpServletResponse;
52 import javax.servlet.http.HttpSession;
55 import gnu.regexp.REMatch;
56 import mir.entity.Entity;
57 import mir.generator.Generator;
58 import mir.log.LoggerWrapper;
59 import mir.misc.StringUtil;
60 import mir.servlet.ServletModule;
61 import mir.servlet.ServletModuleExc;
62 import mir.servlet.ServletModuleFailure;
63 import mir.servlet.ServletModuleUserExc;
64 import mir.session.HTTPAdapters;
65 import mir.session.Request;
66 import mir.session.Session;
67 import mir.session.SessionHandler;
68 import mir.session.SimpleResponse;
69 import mir.session.UploadedFile;
70 import mir.storage.StorageObjectFailure;
71 import mir.util.ExceptionFunctions;
72 import mir.util.HTTPParsedRequest;
73 import mir.util.HTTPRequestParser;
74 import mir.util.StringRoutines;
75 import mircoders.entity.EntityComment;
76 import mircoders.entity.EntityContent;
77 import mircoders.global.CacheKey;
78 import mircoders.global.MirGlobal;
79 import mircoders.media.MediaUploadProcessor;
80 import mircoders.module.ModuleComment;
81 import mircoders.module.ModuleContent;
82 import mircoders.module.ModuleMediaType;
83 import mircoders.pdf.PDFGenerator;
84 import mircoders.search.AudioSearchTerm;
85 import mircoders.search.ContentSearchTerm;
86 import mircoders.search.ImagesSearchTerm;
87 import mircoders.search.KeywordSearchTerm;
88 import mircoders.search.TextSearchTerm;
89 import mircoders.search.TopicMatrixSearchTerm;
90 import mircoders.search.TopicSearchTerm;
91 import mircoders.search.UnIndexedSearchTerm;
92 import mircoders.search.VideoSearchTerm;
93 import mircoders.storage.DatabaseComment;
94 import mircoders.storage.DatabaseContent;
95 import mircoders.storage.DatabaseContentToMedia;
96 import mircoders.storage.DatabaseContentToTopics;
97 import mircoders.storage.DatabaseLanguage;
98 import mircoders.storage.DatabaseTopics;
99 import org.apache.commons.fileupload.FileItem;
100 import org.apache.commons.net.smtp.SMTPClient;
101 import org.apache.commons.net.smtp.SMTPReply;
102 import org.apache.lucene.analysis.standard.StandardAnalyzer;
103 import org.apache.lucene.document.Document;
104 import org.apache.lucene.queryParser.QueryParser;
105 import org.apache.lucene.search.Hits;
106 import org.apache.lucene.search.IndexSearcher;
107 import org.apache.lucene.search.Query;
108 import org.apache.lucene.search.Searcher;
109 import org.apache.struts.util.MessageResources;
112 * ServletModuleOpenIndy -
113 * is the open-access-servlet, which is responsible for
114 * adding comments to articles &
115 * open-postings to the newswire
117 * @author mir-coders group
118 * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.11 2004/02/08 21:05:03 zapata Exp $
122 public class ServletModuleOpenIndy extends ServletModule
125 private String commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
126 private String postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
127 private String searchResultsTemplate;
128 private String prepareMailTemplate,sentMailTemplate,emailAnArticleTemplate;
129 private ModuleContent contentModule;
130 private ModuleComment commentModule;
131 private String directOp ="yes";
132 // Singelton / Kontruktor
133 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
134 public static ServletModule getInstance() { return instance; }
136 private ServletModuleOpenIndy() {
139 logger = new LoggerWrapper("ServletModule.OpenIndy");
141 commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
142 commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
143 commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
145 postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
146 postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
147 postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
149 searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
150 prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
151 emailAnArticleTemplate = configuration.getString("ServletModule.OpenIndy.MailableArticleTemplate");
152 sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
153 directOp = configuration.getString("DirectOpenposting").toLowerCase();
154 commentModule = new ModuleComment(DatabaseComment.getInstance());
155 mainModule = commentModule;
156 contentModule = new ModuleContent(DatabaseContent.getInstance());
157 defaultAction = "defaultAction";
159 catch (StorageObjectFailure e) {
160 logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
165 * Perform the default open posting action
167 public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
168 opensession(aRequest, aResponse);
172 * Method to return an out of service notice when open postings are disabled
176 * @throws ServletModuleExc
177 * @throws ServletModuleUserExc
178 * @throws ServletModuleFailure
180 public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
181 deliver(aRequest, aResponse, null, null, configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
185 * Method for making a comment
187 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
188 if (MirGlobal.abuse().getOpenPostingDisabled()) {
189 openPostingDisabled(req, res);
194 String aid = req.getParameter("aid"); // the article id the comment will belong to
196 if (aid != null && !aid.equals("")) {
198 Map mergeData = new HashMap();
201 if (MirGlobal.abuse().getOpenPostingPassword()) {
202 String passwd = generateOnetimePassword();
203 HttpSession session = req.getSession(false);
204 session.setAttribute("passwd", passwd);
205 mergeData.put("passwd", passwd);
208 mergeData.put("passwd", null);
210 mergeData.put("aid", aid);
212 Map extraInfo = new HashMap();
213 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
215 deliver(req, res, mergeData, extraInfo, commentFormTemplate);
217 catch (Throwable t) {
218 throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
222 throw new ServletModuleExc("aid not set!");
226 * Method for inserting a comment into the Database and delivering
227 * the commentDone Page
230 public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
231 if (MirGlobal.abuse().getOpenPostingDisabled()) {
232 openPostingDisabled(req, res);
237 String aid = req.getParameter("to_media"); // the article id the comment will belong to
238 if (aid != null && !aid.equals("")) {
239 // ok, collecting data from form
241 Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
243 //no html in comments(for now)
244 for (Iterator i = withValues.keySet().iterator(); i.hasNext(); ) {
245 String k = (String) i.next();
246 String v = (String) withValues.get(k);
248 withValues.put(k, StringUtil.removeHTMLTags(v));
250 withValues.put("is_published", "1");
251 withValues.put("to_comment_status", "1");
252 withValues.put("is_html", "0");
254 //checking the onetimepasswd
255 HttpSession session = req.getSession(false);
256 String sessionPasswd = (String) session.getAttribute("passwd");
257 if (sessionPasswd != null) {
258 String passwd = req.getParameter("passwd");
259 if (passwd == null || passwd.length() == 0) {
260 throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});
262 if (!sessionPasswd.equals(passwd)) {
263 throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});
265 session.invalidate();
268 String id = mainModule.add(withValues);
270 SimpleResponse response = new SimpleResponse();
271 response.setResponseGenerator(commentFormDoneTemplate);
274 deliver(req, res, null, null, commentFormDupeTemplate);
277 DatabaseContent.getInstance().setUnproduced("id=" + aid);
280 EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
281 MirGlobal.localizer().openPostings().afterCommentPosting(comment);
282 MirGlobal.abuse().checkComment(
283 comment, new HTTPAdapters.HTTPRequestAdapter(req), res);
285 catch (Throwable t) {
286 throw new ServletModuleExc(t.getMessage());
290 // redirecting to url
291 // should implement back to article
292 deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());
294 catch (Throwable e) {
295 throw new ServletModuleFailure(e);
299 throw new ServletModuleExc("aid not set!");
304 * Method for delivering the form-Page for open posting
307 public void addposting(HttpServletRequest req, HttpServletResponse res)
308 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
310 if (MirGlobal.abuse().getOpenPostingDisabled()) {
311 openPostingDisabled(req, res);
316 Map mergeData = new HashMap();
319 if (MirGlobal.abuse().getOpenPostingPassword()) {
320 String passwd = generateOnetimePassword();
321 HttpSession session = req.getSession(false);
322 session.setAttribute("passwd", passwd);
323 mergeData.put("passwd", passwd);
326 mergeData.put("passwd", null);
329 String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
330 String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
331 String numOfMedia = req.getParameter("medianum");
333 if (numOfMedia == null || numOfMedia.equals("")) {
334 numOfMedia = defaultMedia;
336 else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
337 numOfMedia = maxMedia;
340 int mediaNum = Integer.parseInt(numOfMedia);
341 List mediaFields = new Vector();
342 for (int i = 0; i < mediaNum; i++) {
343 Integer mNum = new Integer(i + 1);
344 mediaFields.add(mNum.toString());
346 mergeData.put("medianum", numOfMedia);
347 mergeData.put("mediafields", mediaFields);
348 mergeData.put("to_topic", null);
350 Map extraInfo = new HashMap();
351 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
352 extraInfo.put("themenPopupData", DatabaseTopics.getInstance().getPopupData());
354 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
356 catch (Throwable t) {
357 throw new ServletModuleFailure(t);
362 * Method for inserting an open posting into the Database and delivering
363 * the postingDone Page
366 public void insposting(HttpServletRequest aRequest, HttpServletResponse aResponse) throws
367 ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
368 if (MirGlobal.abuse().getOpenPostingDisabled()) {
369 openPostingDisabled(aRequest, aResponse);
375 HTTPParsedRequest parsedRequest = new HTTPParsedRequest(
377 configuration.getString("Mir.DefaultEncoding"),
378 configuration.getInt("MaxMediaUploadSize")*1024,
379 configuration.getString("TempDir"));
381 Map mergeData = new HashMap();
383 HttpSession session = aRequest.getSession(false);
384 String sessionPasswd = (String) session.getAttribute("passwd");
385 if (sessionPasswd != null) {
386 String passwd = parsedRequest.getParameter("passwd");
388 if (passwd == null || passwd.length() == 0) {
389 throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});
391 if (!sessionPasswd.equals(passwd)) {
392 throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});
394 session.invalidate();
397 if (((parsedRequest.getParameter("title")).length() == 0) ||
398 ((parsedRequest.getParameter("description")).length() == 0) ||
399 ((parsedRequest.getParameter("content_data")).length() == 0))
400 throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
402 List mediaList = new Vector();
403 Iterator i = parsedRequest.getFiles().iterator();
405 while (i.hasNext()) {
406 UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
407 Map mediaValues = new HashMap();
409 String suffix = file.getFieldName().substring(5); // media${m}
410 logger.debug("media_title" + suffix);
411 String title = parsedRequest.getParameter("media_title" + suffix);
413 mediaValues.put("title", StringUtil.removeHTMLTags(title));
414 mediaValues.put("creator", StringUtil.removeHTMLTags(parsedRequest.getParameter("creator")));
415 mediaValues.put("to_publisher", "0");
416 mediaValues.put("is_published", "1");
417 mediaValues.put("to_media_folder", "7");
419 mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
422 Map withValues = new HashMap();
423 i = DatabaseContent.getInstance().getFields().iterator();
424 while (i.hasNext()) {
425 String field = (String) i.next();
426 String value = parsedRequest.getParameter(field);
428 withValues.put(field, value);
432 for (i = withValues.keySet().iterator(); i.hasNext(); ) {
433 String k = (String) i.next();
434 String v = (String) withValues.get(k);
436 if (k.equals("content_data")) {
437 //this doesn't quite work yet, so for now, all html goes
438 //withValues.put(k,StringUtil.approveHTMLTags(v));
439 withValues.put(k, StringUtil.deleteForbiddenTags(v));
441 else if (k.equals("description")) {
442 String tmp = StringUtil.deleteForbiddenTags(v);
443 withValues.put(k, StringUtil.deleteHTMLTableTags(tmp));
446 withValues.put(k, StringUtil.removeHTMLTags(v));
450 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
451 withValues.put("publish_path",
452 StringUtil.webdbDate2path( (String) withValues.get("date")));
453 withValues.put("is_produced", "0");
454 withValues.put("is_published", "1");
455 if (directOp.equals("yes"))
456 withValues.put("to_article_type", "1");
458 withValues.put("to_publisher", "1");
460 // inserting content into database
461 String cid = contentModule.add(withValues);
462 logger.debug("id: " + cid);
463 //insert was not successfull
465 deliver(aRequest, aResponse, mergeData, null, postingFormDupeTemplate);
469 List topics = parsedRequest.getParameterList("to_topic");
470 if (topics.size() > 0) {
472 DatabaseContentToTopics.getInstance().setTopics(cid, topics);
474 catch (Throwable e) {
475 logger.error("setting content_x_topic failed");
476 contentModule.deleteById(cid);
477 throw new ServletModuleFailure(
478 "smod - openindy :: insposting: setting content_x_topic failed: " +
483 i = mediaList.iterator();
484 while (i.hasNext()) {
485 Entity mediaEnt = (Entity) i.next();
486 DatabaseContentToMedia.getInstance().addMedia(cid, mediaEnt.getId());
489 EntityContent article = (EntityContent) contentModule.getById(cid);
491 MirGlobal.abuse().checkArticle(
492 article, new HTTPAdapters.HTTPRequestAdapter(aRequest), aResponse);
493 MirGlobal.localizer().openPostings().afterContentPosting(article);
495 catch (Throwable t) {
496 logger.error("Error while post-processing article: " + t.getMessage());
498 deliver(aRequest, aResponse, mergeData, null, postingFormDoneTemplate);
500 catch (Throwable e) {
501 e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
502 Throwable cause = ExceptionFunctions.traceCauseException(e);
504 if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
505 throw new ServletModuleUserExc("media.unsupportedformat", new String[] {});
507 throw new ServletModuleFailure(e);
512 * Due to a serious shortcoming of Tomcat 3.3, an extra sessionid parameter is
513 * generated into open session urls. Tomcat 3.3 makes it impossible to
514 * distinguish between sessions that are identified using a url and those
515 * that are identified using cookies: if both a sessionid cookie and a sessionid
516 * url are available, tomcat 3.3 pretends the url wasn't there...
518 private static final String SESSION_REQUEST_KEY="sessionid";
521 * Determines the Locale to be used for the current session
523 protected Locale getResponseLocale(HttpSession aSession, HttpServletRequest aRequest) {
524 String requestLanguage = aRequest.getParameter("language");
525 String sessionLanguage = (String) aSession.getAttribute("language");
526 String acceptLanguage = aRequest.getLocale().getLanguage();
527 String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
529 String language = requestLanguage;
532 language = sessionLanguage;
535 language = acceptLanguage;
538 language = defaultLanguage;
540 aSession.setAttribute("language", language);
542 return new Locale(language, "");
546 * Dispatch method for open sessions: a flexible extensible and customizable way
547 * for open access. Can be used for postings, but also for lots of other stuff.
551 * @throws ServletModuleExc
552 * @throws ServletModuleUserExc
553 * @throws ServletModuleFailure
555 public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse)
556 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
560 new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
561 configuration.getString("Mir.DefaultEncoding"),
562 configuration.getInt("MaxMediaUploadSize")*1024,
563 configuration.getString("TempDir")));
565 if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
566 !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
567 aRequest.getSession().invalidate();
569 Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
571 SimpleResponse response = new SimpleResponse(
572 ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getResponseLocale(aRequest.getSession(), aRequest), getFallbackLocale(aRequest)},
575 response.setResponseValue("actionURL", aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/OpenMir")+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
577 SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);
579 handler.processRequest(request, session, response);
580 ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
582 catch (Throwable t) {
583 logger.error(t.toString());
584 t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
586 throw new ServletModuleFailure(t);
591 * Method for preparing and sending a content as an email message
593 public void mail(HttpServletRequest req, HttpServletResponse res)
594 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
596 String aid = req.getParameter("mail_aid");
598 throw new ServletModuleExc("An article id must be specified in requests to email an article. Something therefore went badly wrong....");
601 String to = req.getParameter("mail_to");
602 String from = req.getParameter("mail_from");
603 String from_name = req.getParameter("mail_from_name");
604 String from_ip = req.getRemoteAddr();
605 String comment = req.getParameter("mail_comment");
606 String mail_language = req.getParameter("mail_language");
608 Map mergeData = new HashMap();
609 mergeData.put("mail_to",to);
610 mergeData.put("mail_from",from);
611 mergeData.put("mail_from_name",from_name);
612 mergeData.put("mail_comment",comment);
613 mergeData.put("mail_aid",aid);
614 mergeData.put("mail_language",mail_language);
617 if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
618 deliver(req, res, mergeData, null, prepareMailTemplate);
621 //run checks on to and from and mail_language to make sure no monkey business occurring
622 if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {
623 throw new ServletModuleExc("Invalid language");
625 if (to.indexOf('\n') != -1
626 || to.indexOf('\r') != -1
627 || to.indexOf(',') != -1) {
628 throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});
630 if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {
631 throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});
634 CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
637 if (MirGlobal.mruCache().hasObject(theCacheKey)){
638 logger.info("fetching email text for article "+aid+" from cache");
639 theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
642 EntityContent contentEnt;
644 contentEnt = (EntityContent) contentModule.getById(aid);
645 StringWriter theEMailTextWriter = new StringWriter();
646 PrintWriter dest = new PrintWriter(theEMailTextWriter);
647 Map articleData = new HashMap();
648 articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
649 articleData.put("languagecode", mail_language);
650 deliver(dest, req, res, articleData, null, emailAnArticleTemplate, mail_language);
651 theEmailText = theEMailTextWriter.toString();
652 MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
654 catch (Throwable e) {
655 throw new ServletModuleFailure("Couldn't get content for article " + aid + mail_language + ": " + e.getMessage(), e);
659 String content = theEmailText;
663 content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
664 // put in the comment where it should go
665 if (comment != null) {
666 String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
668 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
671 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
676 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
679 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
683 SMTPClient client=new SMTPClient();
686 client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
688 reply = client.getReplyCode();
690 if (!SMTPReply.isPositiveCompletion(reply)) {
692 throw new ServletModuleExc("SMTP server refused connection.");
695 client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
698 //mission accomplished
699 deliver(req, res, mergeData, null, sentMailTemplate);
701 catch(IOException e) {
702 if(client.isConnected()) {
705 } catch(IOException f) {
709 throw new ServletModuleFailure(e);
717 * Method for querying a lucene index
721 * @throws ServletModuleExc
722 * @throws ServletModuleUserExc
723 * @throws ServletModuleFailure
726 public void search(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
728 final String[] search_variables = {
729 "search_content", "search_boolean", "search_creator",
730 "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",
731 "search_submit", "search_back", "search_forward"};
732 HTTPRequestParser requestParser = new HTTPRequestParser(req);
736 HttpSession session = req.getSession(false);
738 String queryString = "";
740 Map mergeData = new HashMap();
742 KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted", "search_date", "webdb_create_formatted", "webdb_create_formatted", "webdb_create_formatted");
743 UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("", "", "", "where", "where");
744 TextSearchTerm creatorTerm = new TextSearchTerm("creator", "search_creator", "creator", "creator", "creator");
745 TextSearchTerm titleTerm = new TextSearchTerm("title", "search_content", "title", "title", "title");
746 TextSearchTerm descriptionTerm = new TextSearchTerm("description", "search_content", "description", "description", "description");
747 ContentSearchTerm contentTerm = new ContentSearchTerm("content_data", "search_content", "content", "", "");
748 TopicSearchTerm topicTerm = new TopicSearchTerm();
749 TopicMatrixSearchTerm topicMatrixTerm = new TopicMatrixSearchTerm();
750 ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
751 AudioSearchTerm audioTerm = new AudioSearchTerm();
752 VideoSearchTerm videoTerm = new VideoSearchTerm();
754 //make the query available to subsequent iterations
756 Iterator j = Arrays.asList(search_variables).iterator();
757 while (j.hasNext()) {
758 String variable = (String) j.next();
760 mergeData.put(variable, requestParser.getParameter(variable));
764 mergeData.put("topics", DatabaseTopics.getInstance().getPopupData());
766 catch (Throwable e) {
767 logger.debug("Can't get topics: " + e.toString());
770 String searchBackValue = req.getParameter("search_back");
771 String searchForwardValue = req.getParameter("search_forward");
773 if (searchBackValue != null) {
774 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
775 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() - increment;
778 if (newPosition >= totalHits)
779 newPosition = totalHits - 1;
780 session.setAttribute("positionInResults", new Integer(newPosition));
783 if (searchForwardValue != null) {
784 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
785 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() + increment;
788 if (newPosition >= totalHits)
789 newPosition = totalHits - 1;
791 session.setAttribute("positionInResults", new Integer(newPosition));
794 String indexPath = configuration.getString("IndexPath");
796 String creatorFragment = creatorTerm.makeTerm(req);
797 if (creatorFragment != null) {
798 queryString = queryString + " +" + creatorFragment;
801 // search title, description, and content for something
802 // the contentTerm uses param "search_boolean" to combine its terms
803 String contentFragment = contentTerm.makeTerm(req);
804 if (contentFragment != null) {
805 logger.debug("contentFragment: " + contentFragment);
806 queryString = queryString + " +" + contentFragment;
809 String topicFragment = topicTerm.makeTerm(req);
810 if (topicFragment != null) {
811 queryString = queryString + " +" + topicFragment;
814 String topicMatrixFragment = topicMatrixTerm.makeTerm(req);
815 if (topicMatrixFragment != null) {
816 queryString = queryString + " +" + topicMatrixFragment;
819 String imagesFragment = imagesTerm.makeTerm(req);
820 if (imagesFragment != null) {
821 queryString = queryString + " +" + imagesFragment;
824 String audioFragment = audioTerm.makeTerm(req);
825 if (audioFragment != null) {
826 queryString = queryString + " +" + audioFragment;
829 String videoFragment = videoTerm.makeTerm(req);
830 if (videoFragment != null) {
831 queryString = queryString + " +" + videoFragment;
834 if (queryString == null || queryString.length()==0) {
839 Searcher searcher = null;
841 searcher = new IndexSearcher(indexPath);
843 catch (IOException e) {
844 logger.debug("Can't open indexPath: " + indexPath);
845 throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
850 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
852 catch (Exception e) {
854 logger.debug("Query don't parse: " + queryString);
855 throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
860 hits = searcher.search(query);
862 catch (IOException e) {
864 logger.debug("Can't get hits: " + e.toString());
865 throw new ServletModuleExc("Problem getting hits!");
869 int end = hits.length();
871 String sortBy = req.getParameter("search_sort");
872 if (sortBy == null || sortBy.equals("")) {
873 throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
876 // here is where the documents will go for storage across sessions
877 ArrayList theDocumentsSorted = new ArrayList();
879 if (sortBy.equals("score")) {
880 for (int i = start; i < end; i++) {
881 theDocumentsSorted.add(hits.doc(i));
885 // then we'll sort by date!
886 Map dateToPosition = new HashMap(end, 1.0F); //we know how big it will be
887 for (int i = start; i < end; i++) {
888 String creationDate = (hits.doc(i)).get("creationDate");
889 // do a little dance in case two contents created at the same second!
890 if (dateToPosition.containsKey(creationDate)) {
891 ( (ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
894 ArrayList thePositions = new ArrayList();
895 thePositions.add(new Integer(i));
896 dateToPosition.put(creationDate, thePositions);
899 Set keys = dateToPosition.keySet();
900 ArrayList keyList = new ArrayList(keys);
901 Collections.sort(keyList);
902 if (sortBy.equals("date_desc")) {
903 Collections.reverse(keyList);
906 if (!sortBy.equals("date_asc")) {
907 throw new ServletModuleExc("don't know how to sort by: " + sortBy);
910 ListIterator keyTraverser = keyList.listIterator();
911 while (keyTraverser.hasNext()) {
912 ArrayList positions = (ArrayList) dateToPosition.get( (keyTraverser.next()));
913 ListIterator positionsTraverser = positions.listIterator();
914 while (positionsTraverser.hasNext()) {
915 theDocumentsSorted.add(hits.doc( ( (Integer) (positionsTraverser.next())).intValue()));
923 catch (IOException e) {
924 logger.debug("Can't close searcher: " + e.toString());
925 throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
928 session.removeAttribute("numberOfHits");
929 session.removeAttribute("theDocumentsSorted");
930 session.removeAttribute("positionInResults");
932 session.setAttribute("numberOfHits", new Integer(end));
933 session.setAttribute("theDocumentsSorted", theDocumentsSorted);
934 session.setAttribute("positionInResults", new Integer(0));
937 catch (IOException e) {
938 logger.debug("Can't close searcher: " + e.toString());
939 throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
946 ArrayList theDocs = (ArrayList) session.getAttribute("theDocumentsSorted");
947 if (theDocs != null) {
949 mergeData.put("numberOfHits", (session.getAttribute("numberOfHits")).toString());
950 List theHits = new Vector();
951 int pIR = ( (Integer) session.getAttribute("positionInResults")).intValue();
953 int numHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
955 if (! (pIR + increment >= numHits)) {
956 mergeData.put("hasNext", "y");
959 mergeData.put("hasNext", null);
962 mergeData.put("hasPrevious", "y");
965 mergeData.put("hasPrevious", null);
968 if ( (pIR + increment) > numHits) {
972 terminus = pIR + increment;
974 for (int i = pIR; i < terminus; i++) {
975 Map h = new HashMap();
976 Document theHit = (Document) theDocs.get(i);
977 whereTerm.returnMeta(h, theHit);
978 creatorTerm.returnMeta(h, theHit);
979 titleTerm.returnMeta(h, theHit);
980 descriptionTerm.returnMeta(h, theHit);
981 dateTerm.returnMeta(h, theHit);
982 imagesTerm.returnMeta(h, theHit);
983 audioTerm.returnMeta(h, theHit);
984 videoTerm.returnMeta(h, theHit);
987 mergeData.put("hits", theHits);
990 catch (Throwable e) {
991 logger.error("Can't iterate over hits: " + e.toString());
993 throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
996 mergeData.put("queryString", queryString);
998 deliver(req, res, mergeData, null, searchResultsTemplate);
1000 catch (NullPointerException n) {
1001 throw new ServletModuleFailure("Null Pointer: " + n.toString(), n);
1006 * Method for dynamically generating a pdf using iText
1009 public void getpdf(HttpServletRequest req, HttpServletResponse res)
1010 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
1011 long starttime = System.currentTimeMillis();
1012 String ID_REQUEST_PARAM = "id";
1013 int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
1015 String idParam = req.getParameter(ID_REQUEST_PARAM);
1016 if (idParam != null) {
1018 RE re = new RE("[0-9]+");
1020 REMatch[] idMatches = re.getAllMatches(idParam);
1022 String cacheSelector = "";
1024 for (int i = 0; i < idMatches.length; i++) {
1025 cacheSelector = cacheSelector + "," + idMatches[i].toString();
1028 String cacheType = "pdf";
1030 CacheKey theCacheKey = new CacheKey(cacheType, cacheSelector);
1034 if (MirGlobal.mruCache().hasObject(theCacheKey)) {
1035 logger.info("fetching pdf from cache");
1036 thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
1039 logger.info("generating pdf and caching it");
1040 ByteArrayOutputStream out = new ByteArrayOutputStream();
1041 PDFGenerator pdfMaker = new PDFGenerator(out);
1043 if (idMatches.length > 1) {
1045 for (int i = 0; i < idMatches.length && i < maxArticlesInNewsleter; i++) {
1046 REMatch aMatch = idMatches[i];
1047 String id = aMatch.toString();
1048 EntityContent contentEnt = (EntityContent) contentModule.getById(id);
1049 pdfMaker.addIndexItem(contentEnt);
1053 for (int i = 0; i < idMatches.length; i++) {
1054 REMatch aMatch = idMatches[i];
1055 String id = aMatch.toString();
1056 EntityContent contentEnt = (EntityContent) contentModule.getById(id);
1058 pdfMaker.add(contentEnt);
1062 thePDF = out.toByteArray();
1064 //and save all our hard work!
1065 MirGlobal.mruCache().storeObject(theCacheKey, thePDF);
1068 res.setContentType("application/pdf");
1069 res.setContentLength(thePDF.length);
1070 res.getOutputStream().write(thePDF);
1071 res.getOutputStream().flush();
1072 String elapsedtime = (new Long(System.currentTimeMillis() - starttime)).toString();
1073 logger.info("pdf retireval took " + elapsedtime + " milliseconds");
1077 throw new ServletModuleExc("Missing id.");
1080 catch (Throwable t) {
1081 logger.error(t.toString());
1082 throw new ServletModuleFailure(t);
1087 public String generateOnetimePassword() {
1088 Random r = new Random();
1089 int random = r.nextInt();
1091 long l = System.currentTimeMillis();
1093 l = (l * l * l * l) / random;
1097 String returnString = "" + l;
1099 return returnString.substring(5);
1102 public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) throws ServletModuleFailure {
1104 deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);
1106 catch (Throwable t) {
1107 throw new ServletModuleFailure(t);
1111 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
1112 throws ServletModuleFailure {
1114 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open");
1115 responseData.put("data", aData);
1116 responseData.put("extra", anExtra);
1119 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1120 generator.generate(anOutputWriter, responseData, logger);
1122 anOutputWriter.close();
1124 catch (Throwable e) {
1125 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1127 throw new ServletModuleFailure(e);
1131 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator,String aLocaleString)
1132 throws ServletModuleFailure {
1134 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "bundles.open");
1135 responseData.put("data", aData);
1136 responseData.put("extra", anExtra);
1139 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1140 generator.generate(anOutputWriter, responseData, logger);
1142 anOutputWriter.close();
1144 catch (Throwable e) {
1145 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1147 throw new ServletModuleFailure(e);
1152 public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
1154 logger.error("error: " + anException);
1155 Map data = new HashMap();
1157 data.put("errorstring", anException.getMessage());
1158 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1160 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
1162 catch (Throwable e) {
1163 throw new ServletModuleFailure(e);
1167 public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
1168 PrintWriter out, ServletModuleUserExc anException) {
1170 logger.warn("user error: " + anException.getMessage());
1171 Map data = new HashMap();
1173 MessageResources messages = MessageResources.getMessageResources("bundles.open");
1174 data.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()));
1175 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1177 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
1179 catch (Throwable e) {
1180 throw new ServletModuleFailure(e);