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;
34 import gnu.regexp.REMatch;
36 import java.io.ByteArrayOutputStream;
38 import java.io.IOException;
39 import java.io.PrintWriter;
40 import java.io.StringWriter;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Collections;
44 import java.util.GregorianCalendar;
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.List;
48 import java.util.ListIterator;
49 import java.util.Locale;
51 import java.util.Random;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.servlet.http.HttpServletResponse;
56 import javax.servlet.http.HttpSession;
58 import mir.bundle.Bundle;
59 import mir.entity.Entity;
60 import mir.generator.Generator;
61 import mir.log.LoggerWrapper;
62 import mir.misc.StringUtil;
63 import mir.servlet.ServletModule;
64 import mir.servlet.ServletModuleExc;
65 import mir.servlet.ServletModuleFailure;
66 import mir.servlet.ServletModuleUserExc;
67 import mir.session.HTTPAdapters;
68 import mir.session.Request;
69 import mir.session.Session;
70 import mir.session.SessionHandler;
71 import mir.session.SimpleResponse;
72 import mir.session.UploadedFile;
73 import mir.storage.StorageObjectFailure;
74 import mir.util.ExceptionFunctions;
75 import mir.util.FileFunctions;
76 import mir.util.HTTPParsedRequest;
77 import mir.util.HTTPRequestParser;
78 import mir.util.StringRoutines;
79 import mircoders.entity.EntityComment;
80 import mircoders.entity.EntityContent;
81 import mircoders.global.CacheKey;
82 import mircoders.global.MirGlobal;
83 import mircoders.media.MediaUploadProcessor;
84 import mircoders.media.UnsupportedMediaTypeExc;
85 import mircoders.module.ModuleComment;
86 import mircoders.module.ModuleContent;
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.DatabaseLanguage;
102 import mircoders.storage.DatabaseTopics;
104 import org.apache.commons.fileupload.FileItem;
105 import org.apache.commons.net.smtp.SMTPClient;
106 import org.apache.commons.net.smtp.SMTPReply;
107 import org.apache.lucene.analysis.standard.StandardAnalyzer;
108 import org.apache.lucene.document.Document;
109 import org.apache.lucene.index.IndexReader;
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;
117 * ServletModuleOpenIndy -
118 * is the open-access-servlet, which is responsible for
119 * adding comments to articles &
120 * open-postings to the newswire
122 * @author mir-coders group
123 * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.15 2005/02/10 16:22:27 rhindes Exp $
127 public class ServletModuleOpenIndy extends ServletModule
130 private String commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
131 private String postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
132 private String searchResultsTemplate;
133 private String prepareMailTemplate,sentMailTemplate,emailAnArticleTemplate;
134 private ModuleContent contentModule;
135 private ModuleComment commentModule;
136 private String directOp ="yes";
137 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
139 public static ServletModule getInstance() {
143 private ServletModuleOpenIndy() {
146 logger = new LoggerWrapper("ServletModule.OpenIndy");
148 commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
149 commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
150 commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
152 postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
153 postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
154 postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
156 searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
157 prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
158 emailAnArticleTemplate = configuration.getString("ServletModule.OpenIndy.MailableArticleTemplate");
159 sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
160 directOp = configuration.getString("DirectOpenposting").toLowerCase();
161 commentModule = new ModuleComment();
162 mainModule = commentModule;
163 contentModule = new ModuleContent();
164 defaultAction = "defaultAction";
166 catch (StorageObjectFailure e) {
167 logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
172 * Perform the default open posting action
174 public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
175 opensession(aRequest, aResponse);
179 * Method to return an out of service notice when open postings are disabled
183 * @throws ServletModuleExc
184 * @throws ServletModuleUserExc
185 * @throws ServletModuleFailure
187 public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
188 deliver(aRequest, aResponse, null, null, configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
192 * Method for making a comment
194 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
195 if (MirGlobal.abuse().getOpenPostingDisabled()) {
196 openPostingDisabled(req, res);
201 String aid = req.getParameter("aid"); // the article id the comment will belong to
203 if (aid != null && !aid.equals("")) {
205 Map mergeData = new HashMap();
208 if (MirGlobal.abuse().getOpenPostingPassword()) {
209 String passwd = generateOnetimePassword();
210 HttpSession session = req.getSession(false);
211 session.setAttribute("passwd", passwd);
212 mergeData.put("passwd", passwd);
215 mergeData.put("passwd", null);
217 mergeData.put("aid", aid);
219 Map extraInfo = new HashMap();
220 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
222 deliver(req, res, mergeData, extraInfo, commentFormTemplate);
224 catch (Throwable t) {
225 throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
229 throw new ServletModuleExc("aid not set!");
233 * Method for inserting a comment into the Database and delivering
234 * the commentDone Page
237 public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
238 if (MirGlobal.abuse().getOpenPostingDisabled()) {
239 openPostingDisabled(req, res);
244 String aid = req.getParameter("to_media"); // the article id the comment will belong to
245 if (aid != null && !aid.equals("")) {
246 // ok, collecting data from form
248 Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
250 //no html in comments(for now)
251 for (Iterator i = withValues.keySet().iterator(); i.hasNext(); ) {
252 String k = (String) i.next();
253 String v = (String) withValues.get(k);
255 withValues.put(k, StringUtil.removeHTMLTags(v));
257 withValues.put("is_published", "1");
258 withValues.put("to_comment_status", "1");
259 withValues.put("is_html", "0");
261 //checking the onetimepasswd
262 HttpSession session = req.getSession(false);
263 String sessionPasswd = (String) session.getAttribute("passwd");
264 if (sessionPasswd != null) {
265 String passwd = req.getParameter("passwd");
266 if (passwd == null || passwd.length() == 0) {
267 throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});
269 if (!sessionPasswd.equals(passwd)) {
270 throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});
272 session.invalidate();
275 String id = mainModule.add(withValues);
277 SimpleResponse response = new SimpleResponse();
278 response.setResponseGenerator(commentFormDoneTemplate);
281 deliver(req, res, null, null, commentFormDupeTemplate);
284 DatabaseContent.getInstance().setUnproduced("id=" + aid);
287 EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
288 MirGlobal.localizer().openPostings().afterCommentPosting(comment);
289 MirGlobal.abuse().checkComment(
290 comment, new HTTPAdapters.HTTPRequestAdapter(req), res);
292 catch (Throwable t) {
293 throw new ServletModuleExc(t.getMessage());
297 // redirecting to url
298 // should implement back to article
299 deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());
301 catch (Throwable e) {
302 throw new ServletModuleFailure(e);
306 throw new ServletModuleExc("aid not set!");
311 * Method for delivering the form-Page for open posting
314 public void addposting(HttpServletRequest req, HttpServletResponse res)
315 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
317 if (MirGlobal.abuse().getOpenPostingDisabled()) {
318 openPostingDisabled(req, res);
323 Map mergeData = new HashMap();
326 if (MirGlobal.abuse().getOpenPostingPassword()) {
327 String passwd = generateOnetimePassword();
328 HttpSession session = req.getSession(false);
329 session.setAttribute("passwd", passwd);
330 mergeData.put("passwd", passwd);
333 mergeData.put("passwd", null);
336 String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
337 String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
338 String numOfMedia = req.getParameter("medianum");
340 if (numOfMedia == null || numOfMedia.equals("")) {
341 numOfMedia = defaultMedia;
343 else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
344 numOfMedia = maxMedia;
347 int mediaNum = Integer.parseInt(numOfMedia);
348 List mediaFields = new ArrayList();
349 for (int i = 0; i < mediaNum; i++) {
350 Integer mNum = new Integer(i + 1);
351 mediaFields.add(mNum.toString());
353 mergeData.put("medianum", numOfMedia);
354 mergeData.put("mediafields", mediaFields);
355 mergeData.put("to_topic", null);
357 Map extraInfo = new HashMap();
358 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
359 extraInfo.put("themenPopupData", DatabaseTopics.getInstance().getPopupData());
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 = 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 (((parsedRequest.getParameter("title")).length() == 0) ||
405 ((parsedRequest.getParameter("description")).length() == 0) ||
406 ((parsedRequest.getParameter("content_data")).length() == 0))
407 throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
409 List mediaList = new ArrayList();
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().getFieldNames().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 UnsupportedMediaTypeExc) {
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 * Determines the Locale to be used for the current session
530 protected Locale getResponseLocale(HttpSession aSession, HttpServletRequest aRequest) {
531 String requestLanguage = aRequest.getParameter("language");
532 String sessionLanguage = (String) aSession.getAttribute("language");
533 String acceptLanguage = aRequest.getLocale().getLanguage();
534 String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
536 String language = requestLanguage;
539 language = sessionLanguage;
542 language = acceptLanguage;
545 language = defaultLanguage;
547 aSession.setAttribute("language", language);
549 return new Locale(language, "");
553 * Dispatch method for open sessions: a flexible extensible and customizable way
554 * for open access. Can be used for postings, but also for lots of other stuff.
558 * @throws ServletModuleExc
559 * @throws ServletModuleUserExc
560 * @throws ServletModuleFailure
562 public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse)
563 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
567 new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
568 configuration.getString("Mir.DefaultEncoding"),
569 configuration.getInt("MaxMediaUploadSize")*1024,
570 configuration.getString("TempDir")));
572 if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
573 !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
574 aRequest.getSession().invalidate();
576 Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
578 SimpleResponse response = new SimpleResponse(
579 ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getResponseLocale(aRequest.getSession(), aRequest), getFallbackLocale(aRequest)},
580 "etc/bundles/open"));
582 response.setResponseValue("actionURL", aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/OpenMir")+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
584 SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);
586 handler.processRequest(request, session, response);
587 ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
589 catch (Throwable t) {
590 logger.error(t.toString());
591 t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
593 throw new ServletModuleFailure(t);
598 * Method for preparing and sending a content as an email message
600 public void mail(HttpServletRequest req, HttpServletResponse res)
601 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
603 String aid = req.getParameter("mail_aid");
605 throw new ServletModuleExc("An article id must be specified in requests to email an article. Something therefore went badly wrong....");
608 String to = req.getParameter("mail_to");
609 String from = req.getParameter("mail_from");
610 String from_name = req.getParameter("mail_from_name");
611 String from_ip = req.getRemoteAddr();
612 String comment = req.getParameter("mail_comment");
613 String mail_language = req.getParameter("mail_language");
615 Map mergeData = new HashMap();
616 mergeData.put("mail_to",to);
617 mergeData.put("mail_from",from);
618 mergeData.put("mail_from_name",from_name);
619 mergeData.put("mail_comment",comment);
620 mergeData.put("mail_aid",aid);
621 mergeData.put("mail_language",mail_language);
624 if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
625 deliver(req, res, mergeData, null, prepareMailTemplate);
628 //run checks on to and from and mail_language to make sure no monkey business occurring
629 if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {
630 throw new ServletModuleExc("Invalid language");
632 if (to.indexOf('\n') != -1
633 || to.indexOf('\r') != -1
634 || to.indexOf(',') != -1) {
635 throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});
637 if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {
638 throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});
641 CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
644 if (MirGlobal.mruCache().hasObject(theCacheKey)){
645 logger.info("fetching email text for article "+aid+" from cache");
646 theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
649 EntityContent contentEnt;
651 contentEnt = (EntityContent) contentModule.getById(aid);
652 StringWriter theEMailTextWriter = new StringWriter();
653 PrintWriter dest = new PrintWriter(theEMailTextWriter);
654 Map articleData = new HashMap();
655 articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
656 articleData.put("languagecode", mail_language);
657 deliver(dest, req, res, articleData, null, emailAnArticleTemplate, mail_language);
658 theEmailText = theEMailTextWriter.toString();
659 MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
661 catch (Throwable e) {
662 throw new ServletModuleFailure("Couldn't get content for article " + aid + mail_language + ": " + e.getMessage(), e);
666 String content = theEmailText;
670 content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
671 // put in the comment where it should go
672 if (comment != null) {
673 String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
675 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
678 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
683 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
686 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
690 SMTPClient client=new SMTPClient();
693 client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
695 reply = client.getReplyCode();
697 if (!SMTPReply.isPositiveCompletion(reply)) {
699 throw new ServletModuleExc("SMTP server refused connection.");
702 client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
705 //mission accomplished
706 deliver(req, res, mergeData, null, sentMailTemplate);
708 catch(IOException e) {
709 if(client.isConnected()) {
712 } catch(IOException f) {
716 throw new ServletModuleFailure(e);
724 * Method for querying a lucene index
728 * @throws ServletModuleExc
729 * @throws ServletModuleUserExc
730 * @throws ServletModuleFailure
733 public void search(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
735 final String[] search_variables = {
736 "search_content", "search_boolean", "search_creator",
737 "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",
738 "search_submit", "search_back", "search_forward"};
739 HTTPRequestParser requestParser = new HTTPRequestParser(req);
743 HttpSession session = req.getSession(false);
745 String queryString = "";
747 Map mergeData = new HashMap();
749 KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted", "search_date", "webdb_create_formatted", "webdb_create_formatted", "webdb_create_formatted");
750 UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("", "", "", "where", "where");
751 TextSearchTerm creatorTerm = new TextSearchTerm("creator", "search_creator", "creator", "creator", "creator");
752 TextSearchTerm titleTerm = new TextSearchTerm("title", "search_content", "title", "title", "title");
753 TextSearchTerm descriptionTerm = new TextSearchTerm("description", "search_content", "description", "description", "description");
754 ContentSearchTerm contentTerm = new ContentSearchTerm("content_data", "search_content", "content", "", "");
755 TopicSearchTerm topicTerm = new TopicSearchTerm();
756 TopicMatrixSearchTerm topicMatrixTerm = new TopicMatrixSearchTerm();
757 ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
758 AudioSearchTerm audioTerm = new AudioSearchTerm();
759 VideoSearchTerm videoTerm = new VideoSearchTerm();
761 //make the query available to subsequent iterations
763 Iterator j = Arrays.asList(search_variables).iterator();
764 while (j.hasNext()) {
765 String variable = (String) j.next();
767 mergeData.put(variable, requestParser.getParameter(variable));
771 mergeData.put("topics", DatabaseTopics.getInstance().getPopupData());
773 catch (Throwable e) {
774 logger.debug("Can't get topics: " + e.toString());
777 String searchBackValue = req.getParameter("search_back");
778 String searchForwardValue = req.getParameter("search_forward");
780 if (searchBackValue != null) {
781 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
782 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() - increment;
785 if (newPosition >= totalHits)
786 newPosition = totalHits - 1;
787 session.setAttribute("positionInResults", new Integer(newPosition));
790 if (searchForwardValue != null) {
791 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
792 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() + increment;
795 if (newPosition >= totalHits)
796 newPosition = totalHits - 1;
798 session.setAttribute("positionInResults", new Integer(newPosition));
801 File indexFile = FileFunctions.getAbsoluteOrRelativeFile(configuration.getHome(), configuration.getString("IndexPath"));
803 String creatorFragment = creatorTerm.makeTerm(req);
804 if (creatorFragment != null) {
805 queryString = queryString + " +" + creatorFragment;
808 // search title, description, and content for something
809 // the contentTerm uses param "search_boolean" to combine its terms
810 String contentFragment = contentTerm.makeTerm(req);
811 if (contentFragment != null) {
812 logger.debug("contentFragment: " + contentFragment);
813 queryString = queryString + " +" + contentFragment;
816 String topicFragment = topicTerm.makeTerm(req);
817 if (topicFragment != null) {
818 queryString = queryString + " +" + topicFragment;
821 String topicMatrixFragment = topicMatrixTerm.makeTerm(req);
822 if (topicMatrixFragment != null) {
823 queryString = queryString + " +" + topicMatrixFragment;
826 String imagesFragment = imagesTerm.makeTerm(req);
827 if (imagesFragment != null) {
828 queryString = queryString + " +" + imagesFragment;
831 String audioFragment = audioTerm.makeTerm(req);
832 if (audioFragment != null) {
833 queryString = queryString + " +" + audioFragment;
836 String videoFragment = videoTerm.makeTerm(req);
837 if (videoFragment != null) {
838 queryString = queryString + " +" + videoFragment;
841 if (queryString == null || queryString.length()==0) {
846 Searcher searcher = null;
848 searcher = new IndexSearcher(IndexReader.open(indexFile));
850 catch (IOException e) {
851 logger.debug("Can't open indexPath: " + indexFile.getAbsolutePath());
852 throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
857 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
859 catch (Exception e) {
861 logger.debug("Query don't parse: " + queryString);
862 throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
867 hits = searcher.search(query);
869 catch (IOException e) {
871 logger.debug("Can't get hits: " + e.toString());
872 throw new ServletModuleExc("Problem getting hits!");
876 int end = hits.length();
878 String sortBy = req.getParameter("search_sort");
879 if (sortBy == null || sortBy.equals("")) {
880 throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
883 // here is where the documents will go for database across sessions
884 ArrayList theDocumentsSorted = new ArrayList();
886 if (sortBy.equals("score")) {
887 for (int i = start; i < end; i++) {
888 theDocumentsSorted.add(hits.doc(i));
892 // then we'll sort by date!
893 Map dateToPosition = new HashMap(end, 1.0F); //we know how big it will be
894 for (int i = start; i < end; i++) {
895 String creationDate = (hits.doc(i)).get("creationDate");
896 // do a little dance in case two contents created at the same second!
897 if (dateToPosition.containsKey(creationDate)) {
898 ( (ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
901 ArrayList thePositions = new ArrayList();
902 thePositions.add(new Integer(i));
903 dateToPosition.put(creationDate, thePositions);
906 Set keys = dateToPosition.keySet();
907 ArrayList keyList = new ArrayList(keys);
908 Collections.sort(keyList);
909 if (sortBy.equals("date_desc")) {
910 Collections.reverse(keyList);
913 if (!sortBy.equals("date_asc")) {
914 throw new ServletModuleExc("don't know how to sort by: " + sortBy);
917 ListIterator keyTraverser = keyList.listIterator();
918 while (keyTraverser.hasNext()) {
919 ArrayList positions = (ArrayList) dateToPosition.get( (keyTraverser.next()));
920 ListIterator positionsTraverser = positions.listIterator();
921 while (positionsTraverser.hasNext()) {
922 theDocumentsSorted.add(hits.doc( ( (Integer) (positionsTraverser.next())).intValue()));
930 catch (IOException e) {
931 logger.debug("Can't close searcher: " + e.toString());
932 throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
935 session.removeAttribute("numberOfHits");
936 session.removeAttribute("theDocumentsSorted");
937 session.removeAttribute("positionInResults");
939 session.setAttribute("numberOfHits", new Integer(end));
940 session.setAttribute("theDocumentsSorted", theDocumentsSorted);
941 session.setAttribute("positionInResults", new Integer(0));
944 catch (IOException e) {
945 logger.debug("Can't close searcher: " + e.toString());
946 throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
953 ArrayList theDocs = (ArrayList) session.getAttribute("theDocumentsSorted");
954 if (theDocs != null) {
956 mergeData.put("numberOfHits", (session.getAttribute("numberOfHits")).toString());
957 List theHits = new ArrayList();
958 int pIR = ( (Integer) session.getAttribute("positionInResults")).intValue();
960 int numHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
962 if (! (pIR + increment >= numHits)) {
963 mergeData.put("hasNext", "y");
966 mergeData.put("hasNext", null);
969 mergeData.put("hasPrevious", "y");
972 mergeData.put("hasPrevious", null);
975 if ( (pIR + increment) > numHits) {
979 terminus = pIR + increment;
981 for (int i = pIR; i < terminus; i++) {
982 Map h = new HashMap();
983 Document theHit = (Document) theDocs.get(i);
984 whereTerm.returnMeta(h, theHit);
985 creatorTerm.returnMeta(h, theHit);
986 titleTerm.returnMeta(h, theHit);
987 descriptionTerm.returnMeta(h, theHit);
988 dateTerm.returnMeta(h, theHit);
989 imagesTerm.returnMeta(h, theHit);
990 audioTerm.returnMeta(h, theHit);
991 videoTerm.returnMeta(h, theHit);
994 mergeData.put("hits", theHits);
997 catch (Throwable e) {
998 logger.error("Can't iterate over hits: " + e.toString());
1000 throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
1003 mergeData.put("queryString", queryString);
1005 deliver(req, res, mergeData, null, searchResultsTemplate);
1007 catch (NullPointerException n) {
1008 throw new ServletModuleFailure("Null Pointer: " + n.toString(), n);
1013 * Method for dynamically generating a pdf using iText
1016 public void getpdf(HttpServletRequest req, HttpServletResponse res)
1017 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
1018 long starttime = System.currentTimeMillis();
1019 String ID_REQUEST_PARAM = "id";
1020 int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
1022 String idParam = req.getParameter(ID_REQUEST_PARAM);
1023 if (idParam != null) {
1025 RE re = new RE("[0-9]+");
1027 REMatch[] idMatches = re.getAllMatches(idParam);
1029 String cacheSelector = "";
1031 for (int i = 0; i < idMatches.length; i++) {
1032 cacheSelector = cacheSelector + "," + idMatches[i].toString();
1035 String cacheType = "pdf";
1037 CacheKey theCacheKey = new CacheKey(cacheType, cacheSelector);
1041 if (MirGlobal.mruCache().hasObject(theCacheKey)) {
1042 logger.info("fetching pdf from cache");
1043 thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
1046 logger.info("generating pdf and caching it");
1047 ByteArrayOutputStream out = new ByteArrayOutputStream();
1048 PDFGenerator pdfMaker = new PDFGenerator(out);
1050 if (idMatches.length > 1) {
1052 for (int i = 0; i < idMatches.length && i < maxArticlesInNewsleter; i++) {
1053 REMatch aMatch = idMatches[i];
1054 String id = aMatch.toString();
1055 EntityContent contentEnt = (EntityContent) contentModule.getById(id);
1056 pdfMaker.addIndexItem(contentEnt);
1060 for (int i = 0; i < idMatches.length; i++) {
1061 REMatch aMatch = idMatches[i];
1062 String id = aMatch.toString();
1063 EntityContent contentEnt = (EntityContent) contentModule.getById(id);
1065 pdfMaker.add(contentEnt);
1069 thePDF = out.toByteArray();
1071 //and save all our hard work!
1072 MirGlobal.mruCache().storeObject(theCacheKey, thePDF);
1075 res.setContentType("application/pdf");
1076 res.setContentLength(thePDF.length);
1077 res.getOutputStream().write(thePDF);
1078 res.getOutputStream().flush();
1079 String elapsedtime = (new Long(System.currentTimeMillis() - starttime)).toString();
1080 logger.info("pdf retireval took " + elapsedtime + " milliseconds");
1084 throw new ServletModuleExc("Missing id.");
1087 catch (Throwable t) {
1088 logger.error(t.toString());
1089 throw new ServletModuleFailure(t);
1094 public String generateOnetimePassword() {
1095 Random r = new Random();
1096 int random = r.nextInt();
1098 long l = System.currentTimeMillis();
1100 l = (l * l * l * l) / random;
1104 String returnString = "" + l;
1106 return returnString.substring(5);
1109 public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) throws ServletModuleFailure {
1111 deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);
1113 catch (Throwable t) {
1114 throw new ServletModuleFailure(t);
1118 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
1119 throws ServletModuleFailure {
1121 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "etc/bundles/open");
1122 responseData.put("data", aData);
1123 responseData.put("extra", anExtra);
1126 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1127 generator.generate(anOutputWriter, responseData, logger);
1129 anOutputWriter.close();
1131 catch (Throwable e) {
1132 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1134 throw new ServletModuleFailure(e);
1138 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator,String aLocaleString)
1139 throws ServletModuleFailure {
1141 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "etc/bundles/open");
1142 responseData.put("data", aData);
1143 responseData.put("extra", anExtra);
1146 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1147 generator.generate(anOutputWriter, responseData, logger);
1149 anOutputWriter.close();
1151 catch (Throwable e) {
1152 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1154 throw new ServletModuleFailure(e);
1159 public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
1161 logger.error("error: " + anException);
1162 Map data = new HashMap();
1164 data.put("errorstring", anException.getMessage());
1165 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1167 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
1169 catch (Throwable e) {
1170 throw new ServletModuleFailure(e);
1174 public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
1175 PrintWriter out, ServletModuleUserExc anException) {
1177 logger.warn("user error: " + anException.getMessage());
1178 Map data = new HashMap();
1181 MirGlobal.getBundleFactory().getBundle("etc/bundles/open", new
1182 String[] { getLocale(aRequest).getLanguage() });
1183 data.put("errorstring", bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters())));
1184 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1186 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
1188 catch (Throwable e) {
1189 throw new ServletModuleFailure(e);