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.DatabaseFailure;
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.store.FSDirectory;
111 import org.apache.lucene.queryParser.QueryParser;
112 import org.apache.lucene.search.Hits;
113 import org.apache.lucene.search.IndexSearcher;
114 import org.apache.lucene.search.Query;
115 import org.apache.lucene.search.Searcher;
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.17 2005/03/26 11:26:27 zapata 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 String directOp ="yes";
138 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
140 public static ServletModule getInstance() {
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();
163 mainModule = commentModule;
164 contentModule = new ModuleContent();
165 defaultAction = "defaultAction";
167 catch (DatabaseFailure e) {
168 logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
173 * Perform the default open posting action
175 public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
176 opensession(aRequest, aResponse);
180 * Method to return an out of service notice when open postings are disabled
184 * @throws ServletModuleExc
185 * @throws ServletModuleUserExc
186 * @throws ServletModuleFailure
188 public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
189 deliver(aRequest, aResponse, null, null, configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
193 * Method for making a comment
195 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
196 if (MirGlobal.abuse().getOpenPostingDisabled()) {
197 openPostingDisabled(req, res);
202 String aid = req.getParameter("aid"); // the article id the comment will belong to
204 if (aid != null && !aid.equals("")) {
206 Map mergeData = new HashMap();
209 if (MirGlobal.abuse().getOpenPostingPassword()) {
210 String passwd = generateOnetimePassword();
211 HttpSession session = req.getSession(false);
212 session.setAttribute("passwd", passwd);
213 mergeData.put("passwd", passwd);
216 mergeData.put("passwd", null);
218 mergeData.put("aid", aid);
220 Map extraInfo = new HashMap();
221 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
223 deliver(req, res, mergeData, extraInfo, commentFormTemplate);
225 catch (Throwable t) {
226 throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
230 throw new ServletModuleExc("aid not set!");
234 * Method for inserting a comment into the Database and delivering
235 * the commentDone Page
238 public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
239 if (MirGlobal.abuse().getOpenPostingDisabled()) {
240 openPostingDisabled(req, res);
245 String aid = req.getParameter("to_media"); // the article id the comment will belong to
246 if (aid != null && !aid.equals("")) {
247 // ok, collecting data from form
249 Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
251 //no html in comments(for now)
252 for (Iterator i = withValues.keySet().iterator(); i.hasNext(); ) {
253 String k = (String) i.next();
254 String v = (String) withValues.get(k);
256 withValues.put(k, StringUtil.removeHTMLTags(v));
258 withValues.put("is_published", "1");
259 withValues.put("to_comment_status", "1");
260 withValues.put("is_html", "0");
262 //checking the onetimepasswd
263 HttpSession session = req.getSession(false);
264 String sessionPasswd = (String) session.getAttribute("passwd");
265 if (sessionPasswd != null) {
266 String passwd = req.getParameter("passwd");
267 if (passwd == null || passwd.length() == 0) {
268 throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});
270 if (!sessionPasswd.equals(passwd)) {
271 throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});
273 session.invalidate();
276 String id = mainModule.add(withValues);
278 SimpleResponse response = new SimpleResponse();
279 response.setResponseGenerator(commentFormDoneTemplate);
282 deliver(req, res, null, null, commentFormDupeTemplate);
285 DatabaseContent.getInstance().setUnproduced("id=" + aid);
288 EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
289 MirGlobal.localizer().openPostings().afterCommentPosting(comment);
290 MirGlobal.abuse().checkComment(
291 comment, new HTTPAdapters.HTTPRequestAdapter(req), res);
293 catch (Throwable t) {
294 throw new ServletModuleExc(t.getMessage());
298 // redirecting to url
299 // should implement back to article
300 deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());
302 catch (Throwable e) {
303 throw new ServletModuleFailure(e);
307 throw new ServletModuleExc("aid not set!");
312 * Method for delivering the form-Page for open posting
315 public void addposting(HttpServletRequest req, HttpServletResponse res)
316 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
318 if (MirGlobal.abuse().getOpenPostingDisabled()) {
319 openPostingDisabled(req, res);
324 Map mergeData = new HashMap();
327 if (MirGlobal.abuse().getOpenPostingPassword()) {
328 String passwd = generateOnetimePassword();
329 HttpSession session = req.getSession(false);
330 session.setAttribute("passwd", passwd);
331 mergeData.put("passwd", passwd);
334 mergeData.put("passwd", null);
337 String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
338 String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
339 String numOfMedia = req.getParameter("medianum");
341 if (numOfMedia == null || numOfMedia.equals("")) {
342 numOfMedia = defaultMedia;
344 else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
345 numOfMedia = maxMedia;
348 int mediaNum = Integer.parseInt(numOfMedia);
349 List mediaFields = new ArrayList();
350 for (int i = 0; i < mediaNum; i++) {
351 Integer mNum = new Integer(i + 1);
352 mediaFields.add(mNum.toString());
354 mergeData.put("medianum", numOfMedia);
355 mergeData.put("mediafields", mediaFields);
356 mergeData.put("to_topic", null);
358 Map extraInfo = new HashMap();
359 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
360 extraInfo.put("themenPopupData", DatabaseTopics.getInstance().getPopupData());
362 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
364 catch (Throwable t) {
365 throw new ServletModuleFailure(t);
370 * Method for inserting an open posting into the Database and delivering
371 * the postingDone Page
374 public void insposting(HttpServletRequest aRequest, HttpServletResponse aResponse) throws
375 ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
376 if (MirGlobal.abuse().getOpenPostingDisabled()) {
377 openPostingDisabled(aRequest, aResponse);
383 HTTPParsedRequest parsedRequest = new HTTPParsedRequest(
385 configuration.getString("Mir.DefaultEncoding"),
386 configuration.getInt("MaxMediaUploadSize")*1024,
387 configuration.getString("TempDir"));
389 Map mergeData = new HashMap();
391 HttpSession session = aRequest.getSession(false);
392 String sessionPasswd = (String) session.getAttribute("passwd");
393 if (sessionPasswd != null) {
394 String passwd = parsedRequest.getParameter("passwd");
396 if (passwd == null || passwd.length() == 0) {
397 throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});
399 if (!sessionPasswd.equals(passwd)) {
400 throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});
402 session.invalidate();
405 if (((parsedRequest.getParameter("title")).length() == 0) ||
406 ((parsedRequest.getParameter("description")).length() == 0) ||
407 ((parsedRequest.getParameter("content_data")).length() == 0))
408 throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
410 List mediaList = new ArrayList();
411 Iterator i = parsedRequest.getFiles().iterator();
413 while (i.hasNext()) {
414 UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
415 Map mediaValues = new HashMap();
417 String suffix = file.getFieldName().substring(5); // media${m}
418 logger.debug("media_title" + suffix);
419 String title = parsedRequest.getParameter("media_title" + suffix);
421 mediaValues.put("title", StringUtil.removeHTMLTags(title));
422 mediaValues.put("creator", StringUtil.removeHTMLTags(parsedRequest.getParameter("creator")));
423 mediaValues.put("to_publisher", "0");
424 mediaValues.put("is_published", "1");
425 mediaValues.put("to_media_folder", "7");
427 mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
430 Map withValues = new HashMap();
431 i = DatabaseContent.getInstance().getFieldNames().iterator();
432 while (i.hasNext()) {
433 String field = (String) i.next();
434 String value = parsedRequest.getParameter(field);
436 withValues.put(field, value);
440 for (i = withValues.keySet().iterator(); i.hasNext(); ) {
441 String k = (String) i.next();
442 String v = (String) withValues.get(k);
444 if (k.equals("content_data")) {
445 //this doesn't quite work yet, so for now, all html goes
446 //withValues.put(k,StringUtil.approveHTMLTags(v));
447 withValues.put(k, StringUtil.deleteForbiddenTags(v));
449 else if (k.equals("description")) {
450 String tmp = StringUtil.deleteForbiddenTags(v);
451 withValues.put(k, StringUtil.deleteHTMLTableTags(tmp));
454 withValues.put(k, StringUtil.removeHTMLTags(v));
458 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
459 withValues.put("publish_path",
460 StringUtil.webdbDate2path( (String) withValues.get("date")));
461 withValues.put("is_produced", "0");
462 withValues.put("is_published", "1");
463 if (directOp.equals("yes"))
464 withValues.put("to_article_type", "1");
466 withValues.put("to_publisher", "1");
468 // inserting content into database
469 String cid = contentModule.add(withValues);
470 logger.debug("id: " + cid);
471 //insert was not successfull
473 deliver(aRequest, aResponse, mergeData, null, postingFormDupeTemplate);
477 List topics = parsedRequest.getParameterList("to_topic");
478 if (topics.size() > 0) {
480 DatabaseContentToTopics.getInstance().setTopics(cid, topics);
482 catch (Throwable e) {
483 logger.error("setting content_x_topic failed");
484 contentModule.deleteById(cid);
485 throw new ServletModuleFailure(
486 "smod - openindy :: insposting: setting content_x_topic failed: " +
491 i = mediaList.iterator();
492 while (i.hasNext()) {
493 Entity mediaEnt = (Entity) i.next();
494 DatabaseContentToMedia.getInstance().addMedia(cid, mediaEnt.getId());
497 EntityContent article = (EntityContent) contentModule.getById(cid);
499 MirGlobal.abuse().checkArticle(
500 article, new HTTPAdapters.HTTPRequestAdapter(aRequest), aResponse);
501 MirGlobal.localizer().openPostings().afterContentPosting(article);
503 catch (Throwable t) {
504 logger.error("Error while post-processing article: " + t.getMessage());
506 deliver(aRequest, aResponse, mergeData, null, postingFormDoneTemplate);
508 catch (Throwable e) {
509 e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
510 Throwable cause = ExceptionFunctions.traceCauseException(e);
512 if (cause instanceof UnsupportedMediaTypeExc) {
513 throw new ServletModuleUserExc("media.unsupportedformat", new String[] {});
515 throw new ServletModuleFailure(e);
520 * Due to a serious shortcoming of Tomcat 3.3, an extra sessionid parameter is
521 * generated into open session urls. Tomcat 3.3 makes it impossible to
522 * distinguish between sessions that are identified using a url and those
523 * that are identified using cookies: if both a sessionid cookie and a sessionid
524 * url are available, tomcat 3.3 pretends the url wasn't there...
526 private static final String SESSION_REQUEST_KEY="sessionid";
529 * Determines the Locale to be used for the current session
531 protected Locale getResponseLocale(HttpSession aSession, HttpServletRequest aRequest) {
532 String requestLanguage = aRequest.getParameter("language");
533 String sessionLanguage = (String) aSession.getAttribute("language");
534 String acceptLanguage = aRequest.getLocale().getLanguage();
535 String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
537 String language = requestLanguage;
540 language = sessionLanguage;
543 language = acceptLanguage;
546 language = defaultLanguage;
548 aSession.setAttribute("language", language);
550 return new Locale(language, "");
554 * Dispatch method for open sessions: a flexible extensible and customizable way
555 * for open access. Can be used for postings, but also for lots of other stuff.
559 * @throws ServletModuleExc
560 * @throws ServletModuleUserExc
561 * @throws ServletModuleFailure
563 public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse)
564 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
568 new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
569 configuration.getString("Mir.DefaultEncoding"),
570 configuration.getInt("MaxMediaUploadSize")*1024,
571 configuration.getString("TempDir")));
573 if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
574 !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
575 aRequest.getSession().invalidate();
577 Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
579 SimpleResponse response = new SimpleResponse(
580 ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getResponseLocale(aRequest.getSession(), aRequest), getFallbackLocale(aRequest)},
581 "etc/bundles/open"));
583 response.setResponseValue("actionURL", aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/OpenMir")+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
585 SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);
587 handler.processRequest(request, session, response);
588 ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
590 catch (Throwable t) {
591 logger.error(t.toString());
592 t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
594 throw new ServletModuleFailure(t);
599 * Method for preparing and sending a content as an email message
601 public void mail(HttpServletRequest req, HttpServletResponse res)
602 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
604 String aid = req.getParameter("mail_aid");
606 throw new ServletModuleExc("An article id must be specified in requests to email an article. Something therefore went badly wrong....");
609 String to = req.getParameter("mail_to");
610 String from = req.getParameter("mail_from");
611 String from_name = req.getParameter("mail_from_name");
612 String from_ip = req.getRemoteAddr();
613 String comment = req.getParameter("mail_comment");
614 String mail_language = req.getParameter("mail_language");
616 Map mergeData = new HashMap();
617 mergeData.put("mail_to",to);
618 mergeData.put("mail_from",from);
619 mergeData.put("mail_from_name",from_name);
620 mergeData.put("mail_comment",comment);
621 mergeData.put("mail_aid",aid);
622 mergeData.put("mail_language",mail_language);
625 if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
626 deliver(req, res, mergeData, null, prepareMailTemplate);
629 //run checks on to and from and mail_language to make sure no monkey business occurring
630 if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {
631 throw new ServletModuleExc("Invalid language");
633 if (to.indexOf('\n') != -1
634 || to.indexOf('\r') != -1
635 || to.indexOf(',') != -1) {
636 throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});
638 if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {
639 throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});
642 CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
645 if (MirGlobal.mruCache().hasObject(theCacheKey)){
646 logger.info("fetching email text for article "+aid+" from cache");
647 theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
650 EntityContent contentEnt;
652 contentEnt = (EntityContent) contentModule.getById(aid);
653 StringWriter theEMailTextWriter = new StringWriter();
654 PrintWriter dest = new PrintWriter(theEMailTextWriter);
655 Map articleData = new HashMap();
656 articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
657 articleData.put("languagecode", mail_language);
658 deliver(dest, req, res, articleData, null, emailAnArticleTemplate, mail_language);
659 theEmailText = theEMailTextWriter.toString();
660 MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
662 catch (Throwable e) {
663 throw new ServletModuleFailure("Couldn't get content for article " + aid + mail_language + ": " + e.getMessage(), e);
667 String content = theEmailText;
671 content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
672 // put in the comment where it should go
673 if (comment != null) {
674 String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
676 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
679 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
684 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
687 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
691 SMTPClient client=new SMTPClient();
694 client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
696 reply = client.getReplyCode();
698 if (!SMTPReply.isPositiveCompletion(reply)) {
700 throw new ServletModuleExc("SMTP server refused connection.");
703 client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
706 //mission accomplished
707 deliver(req, res, mergeData, null, sentMailTemplate);
709 catch(IOException e) {
710 if(client.isConnected()) {
713 } catch(IOException f) {
717 throw new ServletModuleFailure(e);
725 * Method for querying a lucene index
729 * @throws ServletModuleExc
730 * @throws ServletModuleUserExc
731 * @throws ServletModuleFailure
734 public void search(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
736 final String[] search_variables = {
737 "search_content", "search_boolean", "search_creator",
738 "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",
739 "search_submit", "search_back", "search_forward"};
740 HTTPRequestParser requestParser = new HTTPRequestParser(req);
744 HttpSession session = req.getSession(false);
746 String queryString = "";
748 Map mergeData = new HashMap();
750 KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted", "search_date", "webdb_create_formatted", "webdb_create_formatted", "webdb_create_formatted");
751 UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("", "", "", "where", "where");
752 TextSearchTerm creatorTerm = new TextSearchTerm("creator", "search_creator", "creator", "creator", "creator");
753 TextSearchTerm titleTerm = new TextSearchTerm("title", "search_content", "title", "title", "title");
754 TextSearchTerm descriptionTerm = new TextSearchTerm("description", "search_content", "description", "description", "description");
755 ContentSearchTerm contentTerm = new ContentSearchTerm("content_data", "search_content", "content", "", "");
756 TopicSearchTerm topicTerm = new TopicSearchTerm();
757 TopicMatrixSearchTerm topicMatrixTerm = new TopicMatrixSearchTerm();
758 ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
759 AudioSearchTerm audioTerm = new AudioSearchTerm();
760 VideoSearchTerm videoTerm = new VideoSearchTerm();
762 //make the query available to subsequent iterations
764 Iterator j = Arrays.asList(search_variables).iterator();
765 while (j.hasNext()) {
766 String variable = (String) j.next();
768 mergeData.put(variable, requestParser.getParameter(variable));
772 mergeData.put("topics", DatabaseTopics.getInstance().getPopupData());
774 catch (Throwable e) {
775 logger.debug("Can't get topics: " + e.toString());
778 String searchBackValue = req.getParameter("search_back");
779 String searchForwardValue = req.getParameter("search_forward");
781 if (searchBackValue != null) {
782 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
783 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() - increment;
786 if (newPosition >= totalHits)
787 newPosition = totalHits - 1;
788 session.setAttribute("positionInResults", new Integer(newPosition));
791 if (searchForwardValue != null) {
792 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
793 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() + increment;
796 if (newPosition >= totalHits)
797 newPosition = totalHits - 1;
799 session.setAttribute("positionInResults", new Integer(newPosition));
802 File indexFile = FileFunctions.getAbsoluteOrRelativeFile(configuration.getHome(), configuration.getString("IndexPath"));
804 String creatorFragment = creatorTerm.makeTerm(req);
805 if (creatorFragment != null) {
806 queryString = queryString + " +" + creatorFragment;
809 // search title, description, and content for something
810 // the contentTerm uses param "search_boolean" to combine its terms
811 String contentFragment = contentTerm.makeTerm(req);
812 if (contentFragment != null) {
813 logger.debug("contentFragment: " + contentFragment);
814 queryString = queryString + " +" + contentFragment;
817 String topicFragment = topicTerm.makeTerm(req);
818 if (topicFragment != null) {
819 queryString = queryString + " +" + topicFragment;
822 String topicMatrixFragment = topicMatrixTerm.makeTerm(req);
823 if (topicMatrixFragment != null) {
824 queryString = queryString + " +" + topicMatrixFragment;
827 String imagesFragment = imagesTerm.makeTerm(req);
828 if (imagesFragment != null) {
829 queryString = queryString + " +" + imagesFragment;
832 String audioFragment = audioTerm.makeTerm(req);
833 if (audioFragment != null) {
834 queryString = queryString + " +" + audioFragment;
837 String videoFragment = videoTerm.makeTerm(req);
838 if (videoFragment != null) {
839 queryString = queryString + " +" + videoFragment;
842 if (queryString == null || queryString.length()==0) {
847 Searcher searcher = null;
850 searcher = new IndexSearcher(FSDirectory.getDirectory(indexFile,false));
852 catch (IOException e) {
853 logger.debug("Can't open indexPath: " + indexFile.getAbsolutePath());
854 throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
859 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
861 catch (Exception e) {
863 logger.debug("Query don't parse: " + queryString);
864 throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
869 hits = searcher.search(query);
871 catch (IOException e) {
873 logger.debug("Can't get hits: " + e.toString());
874 throw new ServletModuleExc("Problem getting hits!");
878 int end = hits.length();
880 String sortBy = req.getParameter("search_sort");
881 if (sortBy == null || sortBy.equals("")) {
882 throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
885 // here is where the documents will go for database across sessions
886 ArrayList theDocumentsSorted = new ArrayList();
888 if (sortBy.equals("score")) {
889 for (int i = start; i < end; i++) {
890 theDocumentsSorted.add(hits.doc(i));
894 // then we'll sort by date!
895 Map dateToPosition = new HashMap(end, 1.0F); //we know how big it will be
896 for (int i = start; i < end; i++) {
897 String creationDate = (hits.doc(i)).get("creationDate");
898 // do a little dance in case two contents created at the same second!
899 if (dateToPosition.containsKey(creationDate)) {
900 ( (ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
903 ArrayList thePositions = new ArrayList();
904 thePositions.add(new Integer(i));
905 dateToPosition.put(creationDate, thePositions);
908 Set keys = dateToPosition.keySet();
909 ArrayList keyList = new ArrayList(keys);
910 Collections.sort(keyList);
911 if (sortBy.equals("date_desc")) {
912 Collections.reverse(keyList);
915 if (!sortBy.equals("date_asc")) {
916 throw new ServletModuleExc("don't know how to sort by: " + sortBy);
919 ListIterator keyTraverser = keyList.listIterator();
920 while (keyTraverser.hasNext()) {
921 ArrayList positions = (ArrayList) dateToPosition.get( (keyTraverser.next()));
922 ListIterator positionsTraverser = positions.listIterator();
923 while (positionsTraverser.hasNext()) {
924 theDocumentsSorted.add(hits.doc( ( (Integer) (positionsTraverser.next())).intValue()));
932 catch (IOException e) {
933 logger.debug("Can't close searcher: " + e.toString());
934 throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
937 session.removeAttribute("numberOfHits");
938 session.removeAttribute("theDocumentsSorted");
939 session.removeAttribute("positionInResults");
941 session.setAttribute("numberOfHits", new Integer(end));
942 session.setAttribute("theDocumentsSorted", theDocumentsSorted);
943 session.setAttribute("positionInResults", new Integer(0));
946 catch (IOException e) {
947 logger.debug("Can't close searcher: " + e.toString());
948 throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
955 ArrayList theDocs = (ArrayList) session.getAttribute("theDocumentsSorted");
956 if (theDocs != null) {
958 mergeData.put("numberOfHits", (session.getAttribute("numberOfHits")).toString());
959 List theHits = new ArrayList();
960 int pIR = ( (Integer) session.getAttribute("positionInResults")).intValue();
962 int numHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
964 if (! (pIR + increment >= numHits)) {
965 mergeData.put("hasNext", "y");
968 mergeData.put("hasNext", null);
971 mergeData.put("hasPrevious", "y");
974 mergeData.put("hasPrevious", null);
977 if ( (pIR + increment) > numHits) {
981 terminus = pIR + increment;
983 for (int i = pIR; i < terminus; i++) {
984 Map h = new HashMap();
985 Document theHit = (Document) theDocs.get(i);
986 whereTerm.returnMeta(h, theHit);
987 creatorTerm.returnMeta(h, theHit);
988 titleTerm.returnMeta(h, theHit);
989 descriptionTerm.returnMeta(h, theHit);
990 dateTerm.returnMeta(h, theHit);
991 imagesTerm.returnMeta(h, theHit);
992 audioTerm.returnMeta(h, theHit);
993 videoTerm.returnMeta(h, theHit);
996 mergeData.put("hits", theHits);
999 catch (Throwable e) {
1000 logger.error("Can't iterate over hits: " + e.toString());
1002 throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
1005 mergeData.put("queryString", queryString);
1007 deliver(req, res, mergeData, null, searchResultsTemplate);
1009 catch (NullPointerException n) {
1010 throw new ServletModuleFailure("Null Pointer: " + n.toString(), n);
1015 * Method for dynamically generating a pdf using iText
1018 public void getpdf(HttpServletRequest req, HttpServletResponse res)
1019 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
1020 long starttime = System.currentTimeMillis();
1021 String ID_REQUEST_PARAM = "id";
1022 int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
1024 String idParam = req.getParameter(ID_REQUEST_PARAM);
1025 if (idParam != null) {
1027 RE re = new RE("[0-9]+");
1029 REMatch[] idMatches = re.getAllMatches(idParam);
1031 String cacheSelector = "";
1033 for (int i = 0; i < idMatches.length; i++) {
1034 cacheSelector = cacheSelector + "," + idMatches[i].toString();
1037 String cacheType = "pdf";
1039 CacheKey theCacheKey = new CacheKey(cacheType, cacheSelector);
1043 if (MirGlobal.mruCache().hasObject(theCacheKey)) {
1044 logger.info("fetching pdf from cache");
1045 thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
1048 logger.info("generating pdf and caching it");
1049 ByteArrayOutputStream out = new ByteArrayOutputStream();
1050 PDFGenerator pdfMaker = new PDFGenerator(out);
1052 if (idMatches.length > 1) {
1054 for (int i = 0; i < idMatches.length && i < maxArticlesInNewsleter; i++) {
1055 REMatch aMatch = idMatches[i];
1056 String id = aMatch.toString();
1057 EntityContent contentEnt = (EntityContent) contentModule.getById(id);
1058 pdfMaker.addIndexItem(contentEnt);
1062 for (int i = 0; i < idMatches.length; i++) {
1063 REMatch aMatch = idMatches[i];
1064 String id = aMatch.toString();
1065 EntityContent contentEnt = (EntityContent) contentModule.getById(id);
1067 pdfMaker.add(contentEnt);
1071 thePDF = out.toByteArray();
1073 //and save all our hard work!
1074 MirGlobal.mruCache().storeObject(theCacheKey, thePDF);
1077 res.setContentType("application/pdf");
1078 res.setContentLength(thePDF.length);
1079 res.getOutputStream().write(thePDF);
1080 res.getOutputStream().flush();
1081 String elapsedtime = (new Long(System.currentTimeMillis() - starttime)).toString();
1082 logger.info("pdf retireval took " + elapsedtime + " milliseconds");
1086 throw new ServletModuleExc("Missing id.");
1089 catch (Throwable t) {
1090 logger.error(t.toString());
1091 throw new ServletModuleFailure(t);
1096 public String generateOnetimePassword() {
1097 Random r = new Random();
1098 int random = r.nextInt();
1100 long l = System.currentTimeMillis();
1102 l = (l * l * l * l) / random;
1106 String returnString = "" + l;
1108 return returnString.substring(5);
1111 public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) throws ServletModuleFailure {
1113 deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);
1115 catch (Throwable t) {
1116 throw new ServletModuleFailure(t);
1120 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
1121 throws ServletModuleFailure {
1123 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "etc/bundles/open");
1124 responseData.put("data", aData);
1125 responseData.put("extra", anExtra);
1128 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1129 generator.generate(anOutputWriter, responseData, logger);
1131 anOutputWriter.close();
1133 catch (Throwable e) {
1134 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1136 throw new ServletModuleFailure(e);
1140 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator,String aLocaleString)
1141 throws ServletModuleFailure {
1143 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "etc/bundles/open");
1144 responseData.put("data", aData);
1145 responseData.put("extra", anExtra);
1148 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1149 generator.generate(anOutputWriter, responseData, logger);
1151 anOutputWriter.close();
1153 catch (Throwable e) {
1154 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1156 throw new ServletModuleFailure(e);
1161 public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
1163 logger.error("error: " + anException);
1164 Map data = new HashMap();
1166 data.put("errorstring", anException.getMessage());
1167 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1169 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
1171 catch (Throwable e) {
1172 throw new ServletModuleFailure(e);
1176 public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
1177 PrintWriter out, ServletModuleUserExc anException) {
1179 logger.warn("user error: " + anException.getMessage());
1180 Map data = new HashMap();
1183 MirGlobal.getBundleFactory().getBundle("etc/bundles/open", new
1184 String[] { getLocale(aRequest).getLanguage() });
1185 data.put("errorstring", bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters())));
1186 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1188 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
1190 catch (Throwable e) {
1191 throw new ServletModuleFailure(e);