2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
6 * Mir is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * Mir is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Mir; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * In addition, as a special exception, The Mir-coders gives permission to link
21 * the code of this program with any library licensed under the Apache Software License,
22 * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23 * (or with modified versions of the above that use the same license as the above),
24 * and distribute linked combinations including the two. You must obey the
25 * GNU General Public License in all respects for all of the code used other than
26 * the above mentioned libraries. If you modify this file, you may extend this
27 * exception to your version of the file, but you are not obligated to do so.
28 * If you do not wish to do so, delete this exception statement from your version.
31 package mircoders.servlet;
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;
53 import javax.servlet.http.HttpUtils;
55 import org.apache.commons.fileupload.FileItem;
56 import org.apache.commons.net.smtp.SMTPClient;
57 import org.apache.commons.net.smtp.SMTPReply;
58 import org.apache.lucene.analysis.standard.StandardAnalyzer;
59 import org.apache.lucene.document.Document;
60 import org.apache.lucene.queryParser.QueryParser;
61 import org.apache.lucene.search.Hits;
62 import org.apache.lucene.search.IndexSearcher;
63 import org.apache.lucene.search.Query;
64 import org.apache.lucene.search.Searcher;
65 import org.apache.struts.util.MessageResources;
67 import gnu.regexp.REMatch;
69 import mir.entity.Entity;
70 import mir.generator.Generator;
71 import mir.log.LoggerWrapper;
72 import mir.misc.StringUtil;
73 import mir.servlet.ServletModule;
74 import mir.servlet.ServletModuleExc;
75 import mir.servlet.ServletModuleFailure;
76 import mir.servlet.ServletModuleUserExc;
77 import mir.session.HTTPAdapters;
78 import mir.session.Request;
79 import mir.session.Session;
80 import mir.session.SessionHandler;
81 import mir.session.SimpleResponse;
82 import mir.session.UploadedFile;
83 import mir.storage.StorageObjectFailure;
84 import mir.util.ExceptionFunctions;
85 import mir.util.HTTPParsedRequest;
86 import mir.util.HTTPRequestParser;
87 import mir.util.StringRoutines;
88 import mircoders.entity.EntityComment;
89 import mircoders.entity.EntityContent;
90 import mircoders.global.CacheKey;
91 import mircoders.global.MirGlobal;
92 import mircoders.media.MediaUploadProcessor;
93 import mircoders.module.ModuleComment;
94 import mircoders.module.ModuleContent;
95 import mircoders.module.ModuleImages;
96 import mircoders.module.ModuleMediaType;
97 import mircoders.module.ModuleTopics;
98 import mircoders.pdf.PDFGenerator;
99 import mircoders.search.AudioSearchTerm;
100 import mircoders.search.ContentSearchTerm;
101 import mircoders.search.ImagesSearchTerm;
102 import mircoders.search.KeywordSearchTerm;
103 import mircoders.search.TextSearchTerm;
104 import mircoders.search.TopicSearchTerm;
105 import mircoders.search.TopicMatrixSearchTerm;
106 import mircoders.search.UnIndexedSearchTerm;
107 import mircoders.search.VideoSearchTerm;
108 import mircoders.storage.DatabaseComment;
109 import mircoders.storage.DatabaseContent;
110 import mircoders.storage.DatabaseContentToMedia;
111 import mircoders.storage.DatabaseContentToTopics;
112 import mircoders.storage.DatabaseImages;
113 import mircoders.storage.DatabaseLanguage;
114 import mircoders.storage.DatabaseTopics;
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.2 2003/06/03 20:58:30 john 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 ModuleImages imageModule;
137 private ModuleTopics topicsModule;
138 private String directOp ="yes";
139 // Singelton / Kontruktor
140 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
141 public static ServletModule getInstance() { return instance; }
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(DatabaseComment.getInstance());
162 mainModule = commentModule;
163 contentModule = new ModuleContent(DatabaseContent.getInstance());
164 topicsModule = new ModuleTopics(DatabaseTopics.getInstance());
165 imageModule = new ModuleImages(DatabaseImages.getInstance());
166 defaultAction="addposting";
168 catch (StorageObjectFailure e) {
169 logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
174 * Method to return an "apology" when open postings are disabled
178 * @throws ServletModuleExc
179 * @throws ServletModuleUserExc
180 * @throws ServletModuleFailure
182 public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
183 deliver(aRequest, aResponse, (Map) null, null,
184 configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
188 * Method for making a comment
191 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
192 if (MirGlobal.abuse().getOpenPostingDisabled()) {
193 openPostingDisabled(req, res);
198 String aid = req.getParameter("aid"); // the article id the comment will belong to
200 if (aid != null && !aid.equals("")) {
202 Map mergeData = new HashMap();
205 if (MirGlobal.abuse().getOpenPostingPassword()) {
206 String passwd = this.createOneTimePasswd();
207 HttpSession session = req.getSession(false);
208 session.setAttribute("passwd", passwd);
209 mergeData.put("passwd", passwd);
212 mergeData.put("passwd", (String)null);
214 mergeData.put("aid", aid);
216 Map extraInfo = new HashMap();
217 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
219 deliver(req, res, mergeData, extraInfo, commentFormTemplate);
221 catch (Throwable t) {
222 throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
226 throw new ServletModuleExc("aid not set!");
230 * Method for inserting a comment into the Database and delivering
231 * the commentDone Page
234 public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
235 if (MirGlobal.abuse().getOpenPostingDisabled()) {
236 openPostingDisabled(req, res);
241 String aid = req.getParameter("to_media"); // the article id the comment will belong to
242 if (aid != null && !aid.equals("")) {
243 // ok, collecting data from form
245 Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
247 //no html in comments(for now)
248 for (Iterator i = withValues.keySet().iterator(); i.hasNext(); ) {
249 String k = (String) i.next();
250 String v = (String) withValues.get(k);
252 withValues.put(k, StringUtil.removeHTMLTags(v));
254 withValues.put("is_published", "1");
255 withValues.put("to_comment_status", "1");
256 withValues.put("is_html", "0");
258 //checking the onetimepasswd
259 HttpSession session = req.getSession(false);
260 String sessionPasswd = (String) session.getAttribute("passwd");
261 if (sessionPasswd != null) {
262 String passwd = req.getParameter("passwd");
263 if (passwd == null || passwd.length() == 0) {
264 throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});
266 if (!sessionPasswd.equals(passwd)) {
267 throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});
269 session.invalidate();
272 String id = mainModule.add(withValues);
274 SimpleResponse response = new SimpleResponse();
275 response.setResponseGenerator(commentFormDoneTemplate);
278 deliver(req, res, (Map)null, null, commentFormDupeTemplate);
281 DatabaseContent.getInstance().setUnproduced("id=" + aid);
284 EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
285 MirGlobal.localizer().openPostings().afterCommentPosting(comment);
286 MirGlobal.abuse().checkComment(
287 comment, new HTTPAdapters.HTTPRequestAdapter(req), res);
289 catch (Throwable t) {
290 throw new ServletModuleExc(t.getMessage());
294 // redirecting to url
295 // should implement back to article
296 deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());
298 catch (Throwable e) {
299 throw new ServletModuleFailure(e);
303 throw new ServletModuleExc("aid not set!");
308 * Method for delivering the form-Page for open posting
311 public void addposting(HttpServletRequest req, HttpServletResponse res)
312 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
315 if (MirGlobal.abuse().getOpenPostingDisabled()) {
316 openPostingDisabled(req, res);
321 Map mergeData = new HashMap();
324 if (MirGlobal.abuse().getOpenPostingPassword()) {
325 String passwd = generateOnetimePassword();
326 HttpSession session = req.getSession(false);
327 session.setAttribute("passwd", passwd);
328 mergeData.put("passwd", passwd);
331 mergeData.put("passwd", (String)null);
334 String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
335 String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
336 String numOfMedia = req.getParameter("medianum");
338 if (numOfMedia == null || numOfMedia.equals("")) {
339 numOfMedia = defaultMedia;
341 else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
342 numOfMedia = maxMedia;
345 int mediaNum = Integer.parseInt(numOfMedia);
346 List mediaFields = new Vector();
347 for (int i = 0; i < mediaNum; i++) {
348 Integer mNum = new Integer(i + 1);
349 mediaFields.add(mNum.toString());
351 mergeData.put("medianum", numOfMedia);
352 mergeData.put("mediafields", mediaFields);
353 mergeData.put("to_topic", null);
355 Map extraInfo = new HashMap();
356 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
357 extraInfo.put("themenPopupData", topicsModule.getTopicsAsSimpleList());
359 extraInfo.put("topics", topicsModule.getTopicsList());
360 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
362 catch (Throwable t) {
363 throw new ServletModuleFailure(t);
368 * Method for inserting an open posting into the Database and delivering
369 * the postingDone Page
372 public void insposting(HttpServletRequest aRequest, HttpServletResponse aResponse) throws
373 ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
374 if (MirGlobal.abuse().getOpenPostingDisabled()) {
375 openPostingDisabled(aRequest, aResponse);
381 HTTPParsedRequest parsedRequest = new HTTPParsedRequest(
383 configuration.getString("Mir.DefaultEncoding"),
384 configuration.getInt("MaxMediaUploadSize")*1024,
385 configuration.getString("TempDir"));
387 Map mergeData = new HashMap();
389 HttpSession session = aRequest.getSession(false);
390 String sessionPasswd = (String) session.getAttribute("passwd");
391 if (sessionPasswd != null) {
392 String passwd = (String) parsedRequest.getParameter("passwd");
394 if (passwd == null || passwd.length() == 0) {
395 throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});
397 if (!sessionPasswd.equals(passwd)) {
398 throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});
400 session.invalidate();
403 if ((((String) parsedRequest.getParameter("title")).length() == 0) ||
404 (((String) parsedRequest.getParameter("description")).length() == 0) ||
405 (((String) parsedRequest.getParameter("content_data")).length() == 0))
406 throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
408 List mediaList = new Vector();
409 Iterator i = parsedRequest.getFiles().iterator();
411 while (i.hasNext()) {
412 UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
413 Map mediaValues = new HashMap();
415 String suffix = file.getFieldName().substring(5); // media${m}
416 logger.debug("media_title" + suffix);
417 String title = parsedRequest.getParameter("media_title" + suffix);
419 mediaValues.put("title", StringUtil.removeHTMLTags(title));
420 mediaValues.put("creator", StringUtil.removeHTMLTags(parsedRequest.getParameter("creator")));
421 mediaValues.put("to_publisher", "0");
422 mediaValues.put("is_published", "1");
423 mediaValues.put("to_media_folder", "7");
425 mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
428 Map withValues = new HashMap();
429 i = DatabaseContent.getInstance().getFields().iterator();
430 while (i.hasNext()) {
431 String field = (String) i.next();
432 String value = parsedRequest.getParameter(field);
434 withValues.put(field, value);
438 for (i = withValues.keySet().iterator(); i.hasNext(); ) {
439 String k = (String) i.next();
440 String v = (String) withValues.get(k);
442 if (k.equals("content_data")) {
443 //this doesn't quite work yet, so for now, all html goes
444 //withValues.put(k,StringUtil.approveHTMLTags(v));
445 withValues.put(k, StringUtil.deleteForbiddenTags(v));
447 else if (k.equals("description")) {
448 String tmp = StringUtil.deleteForbiddenTags(v);
449 withValues.put(k, StringUtil.deleteHTMLTableTags(tmp));
452 withValues.put(k, StringUtil.removeHTMLTags(v));
456 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
457 withValues.put("publish_path",
458 StringUtil.webdbDate2path( (String) withValues.get("date")));
459 withValues.put("is_produced", "0");
460 withValues.put("is_published", "1");
461 if (directOp.equals("yes"))
462 withValues.put("to_article_type", "1");
464 withValues.put("to_publisher", "1");
466 // inserting content into database
467 String cid = contentModule.add(withValues);
468 logger.debug("id: " + cid);
469 //insert was not successfull
471 deliver(aRequest, aResponse, mergeData, null, postingFormDupeTemplate);
475 List topics = parsedRequest.getParameterList("to_topic");
476 if (topics.size() > 0) {
478 DatabaseContentToTopics.getInstance().setTopics(cid, topics);
480 catch (Throwable e) {
481 logger.error("setting content_x_topic failed");
482 contentModule.deleteById(cid);
483 throw new ServletModuleFailure(
484 "smod - openindy :: insposting: setting content_x_topic failed: " +
489 i = mediaList.iterator();
490 while (i.hasNext()) {
491 Entity mediaEnt = (Entity) i.next();
492 DatabaseContentToMedia.getInstance().addMedia(cid, mediaEnt.getId());
495 EntityContent article = (EntityContent) contentModule.getById(cid);
497 MirGlobal.abuse().checkArticle(
498 article, new HTTPAdapters.HTTPRequestAdapter(aRequest), aResponse);
499 MirGlobal.localizer().openPostings().afterContentPosting(article);
501 catch (Throwable t) {
502 logger.error("Error while post-processing article: " + t.getMessage());
504 deliver(aRequest, aResponse, mergeData, null, postingFormDoneTemplate);
506 catch (Throwable e) {
507 e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
508 Throwable cause = ExceptionFunctions.traceCauseException(e);
510 if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
511 throw new ServletModuleUserExc("media.unsupportedformat", new String[] {});
513 throw new ServletModuleFailure(e);
518 * Due to a serious shortcoming of Tomcat 3.3, an extra sessionid parameter is
519 * generated into open session urls. Tomcat 3.3 makes it impossible to
520 * distinguish between sessions that are identified using a url and those
521 * that are identified using cookies: if both a sessionid cookie and a sessionid
522 * url are available, tomcat 3.3 pretends the url wasn't there...
524 private static final String SESSION_REQUEST_KEY="sessionid";
527 * Dispatch method for open sessions: a flexible extensible and customizable way
528 * for open access. Can be used for postings, but also for lots of other stuff.
532 * @throws ServletModuleExc
533 * @throws ServletModuleUserExc
534 * @throws ServletModuleFailure
537 public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse)
538 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
542 new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
543 configuration.getString("Mir.DefaultEncoding"),
544 configuration.getInt("MaxMediaUploadSize")*1024,
545 configuration.getString("TempDir")));
547 if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
548 !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
549 aRequest.getSession().invalidate();
551 Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
553 SimpleResponse response = new SimpleResponse(
554 ServletHelper.makeGenerationData(aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)},
557 response.setResponseValue("actionURL", aResponse.encodeURL(HttpUtils.getRequestURL(aRequest).toString())+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
559 SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);
561 handler.processRequest(request, session, response);
562 ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
564 catch (Throwable t) {
565 logger.error(t.toString());
566 t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
568 throw new ServletModuleFailure(t);
573 * Method for preparing and sending a content as an email message
576 public void mail(HttpServletRequest req, HttpServletResponse res)
577 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
579 String aid = req.getParameter("mail_aid");
581 throw new ServletModuleExc("An article id must be specified in requests to email an article. Something therefore went badly wrong....");
584 String to = req.getParameter("mail_to");
585 String from = req.getParameter("mail_from");
586 String from_name = req.getParameter("mail_from_name");
587 String from_ip = req.getRemoteAddr();
588 String comment = req.getParameter("mail_comment");
589 String mail_language = req.getParameter("mail_language");
591 Map mergeData = new HashMap();
592 mergeData.put("mail_to",to);
593 mergeData.put("mail_from",from);
594 mergeData.put("mail_from_name",from_name);
595 mergeData.put("mail_comment",comment);
596 mergeData.put("mail_aid",aid);
597 mergeData.put("mail_language",mail_language);
600 if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
601 deliver(req, res, mergeData, null, prepareMailTemplate);
604 //run checks on to and from and mail_language to make sure no monkey business occurring
605 if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {
606 throw new ServletModuleExc("Invalid language");
608 if (to.indexOf('\n') != -1
609 || to.indexOf('\r') != -1
610 || to.indexOf(',') != -1) {
611 throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});
613 if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {
614 throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});
617 CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
620 if (MirGlobal.mruCache().hasObject(theCacheKey)){
621 logger.info("fetching email text for article "+aid+" from cache");
622 theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
625 EntityContent contentEnt;
627 contentEnt = (EntityContent) contentModule.getById(aid);
628 StringWriter theEMailTextWriter = new StringWriter();
629 PrintWriter dest = new PrintWriter(theEMailTextWriter);
630 Map articleData = new HashMap();
631 articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
632 articleData.put("languagecode", mail_language);
633 deliver(dest, req, res, articleData, null, emailAnArticleTemplate, mail_language);
634 theEmailText = theEMailTextWriter.toString();
635 MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
637 catch (Throwable e) {
638 throw new ServletModuleFailure("Couldn't get content for article " + aid + mail_language + ": " + e.getMessage(), e);
642 String content = theEmailText;
646 content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
647 // put in the comment where it should go
648 if (comment != null) {
649 String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
651 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
654 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
659 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
662 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
666 SMTPClient client=new SMTPClient();
669 client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
671 reply = client.getReplyCode();
673 if (!SMTPReply.isPositiveCompletion(reply)) {
675 throw new ServletModuleExc("SMTP server refused connection.");
678 client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
681 //mission accomplished
682 deliver(req, res, mergeData, null, sentMailTemplate);
684 catch(IOException e) {
685 if(client.isConnected()) {
688 } catch(IOException f) {
692 throw new ServletModuleFailure(e);
700 * Method for querying a lucene index
704 * @throws ServletModuleExc
705 * @throws ServletModuleUserExc
706 * @throws ServletModuleFailure
709 public void search(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
711 final String[] search_variables = {
712 "search_content", "search_boolean", "search_creator",
713 "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",
714 "search_submit", "search_back", "search_forward"};
715 HTTPRequestParser requestParser = new HTTPRequestParser(req);
719 HttpSession session = req.getSession(false);
721 String queryString = "";
723 Map mergeData = new HashMap();
725 KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted", "search_date", "webdb_create_formatted", "webdb_create_formatted", "webdb_create_formatted");
726 UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("", "", "", "where", "where");
727 TextSearchTerm creatorTerm = new TextSearchTerm("creator", "search_creator", "creator", "creator", "creator");
728 TextSearchTerm titleTerm = new TextSearchTerm("title", "search_content", "title", "title", "title");
729 TextSearchTerm descriptionTerm = new TextSearchTerm("description", "search_content", "description", "description", "description");
730 ContentSearchTerm contentTerm = new ContentSearchTerm("content_data", "search_content", "content", "", "");
731 TopicSearchTerm topicTerm = new TopicSearchTerm();
732 TopicMatrixSearchTerm topicMatrixTerm = new TopicMatrixSearchTerm();
733 ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
734 AudioSearchTerm audioTerm = new AudioSearchTerm();
735 VideoSearchTerm videoTerm = new VideoSearchTerm();
737 //make the query available to subsequent iterations
739 Iterator j = Arrays.asList(search_variables).iterator();
740 while (j.hasNext()) {
741 String variable = (String) j.next();
743 mergeData.put(variable, requestParser.getParameter(variable));
747 mergeData.put("topics", topicsModule.getTopicsAsSimpleList());
749 catch (Throwable e) {
750 logger.debug("Can't get topics: " + e.toString());
753 String searchBackValue = req.getParameter("search_back");
754 String searchForwardValue = req.getParameter("search_forward");
756 if (searchBackValue != null) {
757 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
758 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() - increment;
761 if (newPosition >= totalHits)
762 newPosition = totalHits - 1;
763 session.setAttribute("positionInResults", new Integer(newPosition));
766 if (searchForwardValue != null) {
767 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
768 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() + increment;
771 if (newPosition >= totalHits)
772 newPosition = totalHits - 1;
774 session.setAttribute("positionInResults", new Integer(newPosition));
777 String indexPath = configuration.getString("IndexPath");
779 String creatorFragment = creatorTerm.makeTerm(req);
780 if (creatorFragment != null) {
781 queryString = queryString + " +" + creatorFragment;
784 // search title, description, and content for something
785 // the contentTerm uses param "search_boolean" to combine its terms
786 String contentFragment = contentTerm.makeTerm(req);
787 if (contentFragment != null) {
788 logger.debug("contentFragment: " + contentFragment);
789 queryString = queryString + " +" + contentFragment;
792 String topicFragment = topicTerm.makeTerm(req);
793 if (topicFragment != null) {
794 queryString = queryString + " +" + topicFragment;
797 String topicMatrixFragment = topicMatrixTerm.makeTerm(req);
798 if (topicMatrixFragment != null) {
799 queryString = queryString + " +" + topicMatrixFragment;
802 String imagesFragment = imagesTerm.makeTerm(req);
803 if (imagesFragment != null) {
804 queryString = queryString + " +" + imagesFragment;
807 String audioFragment = audioTerm.makeTerm(req);
808 if (audioFragment != null) {
809 queryString = queryString + " +" + audioFragment;
812 String videoFragment = videoTerm.makeTerm(req);
813 if (videoFragment != null) {
814 queryString = queryString + " +" + videoFragment;
817 if (queryString == null || queryString == "") {
822 Searcher searcher = null;
824 searcher = new IndexSearcher(indexPath);
826 catch (IOException e) {
827 logger.debug("Can't open indexPath: " + indexPath);
828 throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
833 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
835 catch (Exception e) {
837 logger.debug("Query don't parse: " + queryString);
838 throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
843 hits = searcher.search(query);
845 catch (IOException e) {
847 logger.debug("Can't get hits: " + e.toString());
848 throw new ServletModuleExc("Problem getting hits!");
852 int end = hits.length();
854 String sortBy = req.getParameter("search_sort");
855 if (sortBy == null || sortBy.equals("")) {
856 throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
859 // here is where the documents will go for storage across sessions
860 ArrayList theDocumentsSorted = new ArrayList();
862 if (sortBy.equals("score")) {
863 for (int i = start; i < end; i++) {
864 theDocumentsSorted.add(hits.doc(i));
868 // then we'll sort by date!
869 Map dateToPosition = new HashMap(end, 1.0F); //we know how big it will be
870 for (int i = start; i < end; i++) {
871 String creationDate = (hits.doc(i)).get("creationDate");
872 // do a little dance in case two contents created at the same second!
873 if (dateToPosition.containsKey(creationDate)) {
874 ( (ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
877 ArrayList thePositions = new ArrayList();
878 thePositions.add(new Integer(i));
879 dateToPosition.put(creationDate, thePositions);
882 Set keys = dateToPosition.keySet();
883 ArrayList keyList = new ArrayList(keys);
884 Collections.sort(keyList);
885 if (sortBy.equals("date_desc")) {
886 Collections.reverse(keyList);
889 if (!sortBy.equals("date_asc")) {
890 throw new ServletModuleExc("don't know how to sort by: " + sortBy);
893 ListIterator keyTraverser = keyList.listIterator();
894 while (keyTraverser.hasNext()) {
895 ArrayList positions = (ArrayList) dateToPosition.get( (keyTraverser.next()));
896 ListIterator positionsTraverser = positions.listIterator();
897 while (positionsTraverser.hasNext()) {
898 theDocumentsSorted.add(hits.doc( ( (Integer) (positionsTraverser.next())).intValue()));
906 catch (IOException e) {
907 logger.debug("Can't close searcher: " + e.toString());
908 throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
911 session.removeAttribute("numberOfHits");
912 session.removeAttribute("theDocumentsSorted");
913 session.removeAttribute("positionInResults");
915 session.setAttribute("numberOfHits", new Integer(end));
916 session.setAttribute("theDocumentsSorted", theDocumentsSorted);
917 session.setAttribute("positionInResults", new Integer(0));
920 catch (IOException e) {
921 logger.debug("Can't close searcher: " + e.toString());
922 throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
929 ArrayList theDocs = (ArrayList) session.getAttribute("theDocumentsSorted");
930 if (theDocs != null) {
932 mergeData.put("numberOfHits", ( (Integer) session.getAttribute("numberOfHits")).toString());
933 List theHits = new Vector();
934 int pIR = ( (Integer) session.getAttribute("positionInResults")).intValue();
936 int numHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
938 if (! (pIR + increment >= numHits)) {
939 mergeData.put("hasNext", "y");
942 mergeData.put("hasNext", null);
945 mergeData.put("hasPrevious", "y");
948 mergeData.put("hasPrevious", null);
951 if ( (pIR + increment) > numHits) {
955 terminus = pIR + increment;
957 for (int i = pIR; i < terminus; i++) {
958 Map h = new HashMap();
959 Document theHit = (Document) theDocs.get(i);
960 whereTerm.returnMeta(h, theHit);
961 creatorTerm.returnMeta(h, theHit);
962 titleTerm.returnMeta(h, theHit);
963 descriptionTerm.returnMeta(h, theHit);
964 dateTerm.returnMeta(h, theHit);
965 imagesTerm.returnMeta(h, theHit);
966 audioTerm.returnMeta(h, theHit);
967 videoTerm.returnMeta(h, theHit);
970 mergeData.put("hits", theHits);
973 catch (Throwable e) {
974 logger.error("Can't iterate over hits: " + e.toString());
976 throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
979 mergeData.put("queryString", queryString);
981 deliver(req, res, mergeData, null, searchResultsTemplate);
983 catch (NullPointerException n) {
984 throw new ServletModuleFailure("Null Pointer: " + n.toString(), n);
989 * Method for dynamically generating a pdf using iText
992 public void getpdf(HttpServletRequest req, HttpServletResponse res)
993 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
994 long starttime=System.currentTimeMillis();
995 String ID_REQUEST_PARAM = "id";
996 int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
998 String idParam = req.getParameter(ID_REQUEST_PARAM);
999 if (idParam != null) {
1002 RE re = new RE("[0-9]+");
1005 REMatch[] idMatches=re.getAllMatches(idParam);
1007 String cacheSelector="";
1009 for (int i = 0; i < idMatches.length; i++){
1010 cacheSelector= cacheSelector + "," + idMatches[i].toString();
1013 String cacheType="pdf";
1015 CacheKey theCacheKey = new CacheKey(cacheType,cacheSelector);
1019 if (MirGlobal.mruCache().hasObject(theCacheKey)){
1020 logger.info("fetching pdf from cache");
1021 thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
1024 logger.info("generating pdf and caching it");
1025 ByteArrayOutputStream out = new ByteArrayOutputStream();
1026 PDFGenerator pdfMaker = new PDFGenerator(out);
1028 if (idMatches.length > 1){
1030 for (int i = 0; i < idMatches.length && i < maxArticlesInNewsleter; i++){
1031 REMatch aMatch = idMatches[i];
1032 String id=aMatch.toString();
1033 EntityContent contentEnt = (EntityContent)contentModule.getById(id);
1034 pdfMaker.addIndexItem(contentEnt);
1038 for (int i = 0; i < idMatches.length; i++){
1039 REMatch aMatch = idMatches[i];
1040 String id=aMatch.toString();
1041 EntityContent contentEnt = (EntityContent)contentModule.getById(id);
1043 pdfMaker.add(contentEnt);
1047 thePDF = out.toByteArray();
1049 //and save all our hard work!
1050 MirGlobal.mruCache().storeObject(theCacheKey,thePDF);
1053 res.setContentType("application/pdf");
1054 res.setContentLength(thePDF.length);
1055 res.getOutputStream().write(thePDF);
1056 res.getOutputStream().flush();
1057 String elapsedtime=(new Long(System.currentTimeMillis()-starttime)).toString();
1058 logger.info("pdf retireval took "+elapsedtime + " milliseconds" );
1062 throw new ServletModuleExc("Missing id.");
1065 catch (Throwable t) {
1066 logger.error(t.toString());
1067 throw new ServletModuleFailure(t);
1073 public String generateOnetimePassword() {
1074 Random r = new Random();
1075 int random = r.nextInt();
1077 long l = System.currentTimeMillis();
1079 l = (l * l * l * l) / random;
1083 String returnString = "" + l;
1085 return returnString.substring(5);
1088 public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) throws ServletModuleFailure {
1090 deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);
1092 catch (Throwable t) {
1093 throw new ServletModuleFailure(t);
1097 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
1098 throws ServletModuleFailure {
1100 Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open");
1101 responseData.put("data", aData);
1102 responseData.put("extra", anExtra);
1105 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1106 generator.generate(anOutputWriter, responseData, logger);
1108 anOutputWriter.close();
1110 catch (Throwable e) {
1111 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1113 throw new ServletModuleFailure(e);
1117 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator,String aLocaleString)
1118 throws ServletModuleFailure {
1120 Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "bundles.open");
1121 responseData.put("data", aData);
1122 responseData.put("extra", anExtra);
1125 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1126 generator.generate(anOutputWriter, responseData, logger);
1128 anOutputWriter.close();
1130 catch (Throwable e) {
1131 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1133 throw new ServletModuleFailure(e);
1138 public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
1140 logger.error("error: " + anException);
1141 Map data = new HashMap();
1143 data.put("errorstring", anException.getMessage());
1144 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1146 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
1148 catch (Throwable e) {
1149 throw new ServletModuleFailure(e);
1153 public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
1154 PrintWriter out, ServletModuleUserExc anException) {
1156 logger.warn("user error: " + anException.getMessage());
1157 Map data = new HashMap();
1159 MessageResources messages = MessageResources.getMessageResources("bundles.open");
1160 data.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()));
1161 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1163 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
1165 catch (Throwable e) {
1166 throw new ServletModuleFailure(e);
1170 private String createOneTimePasswd() {