KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > plugin > comment > CommentPlugin


1 /**
2  * Copyright (c) 2003-2006, David A. Czarnecki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * Redistributions of source code must retain the above copyright notice, this list of conditions and the
9  * following disclaimer.
10  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
11  * following disclaimer in the documentation and/or other materials provided with the distribution.
12  * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
13  * endorse or promote products derived from this software without specific prior written permission.
14  * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
15  * without prior written permission of David A. Czarnecki.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */

31 package org.blojsom.plugin.comment;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.apache.commons.mail.Email;
36 import org.apache.commons.mail.EmailException;
37 import org.apache.commons.mail.HtmlEmail;
38 import org.blojsom.blog.Blog;
39 import org.blojsom.blog.Comment;
40 import org.blojsom.blog.Entry;
41 import org.blojsom.blog.User;
42 import org.blojsom.event.Event;
43 import org.blojsom.event.EventBroadcaster;
44 import org.blojsom.event.Listener;
45 import org.blojsom.fetcher.Fetcher;
46 import org.blojsom.fetcher.FetcherException;
47 import org.blojsom.plugin.PluginException;
48 import org.blojsom.plugin.comment.event.CommentAddedEvent;
49 import org.blojsom.plugin.comment.event.CommentResponseSubmissionEvent;
50 import org.blojsom.plugin.common.ResponseConstants;
51 import org.blojsom.plugin.email.EmailConstants;
52 import org.blojsom.plugin.velocity.StandaloneVelocityPlugin;
53 import org.blojsom.util.BlojsomConstants;
54 import org.blojsom.util.BlojsomUtils;
55 import org.blojsom.util.CookieUtils;
56
57 import javax.mail.Session JavaDoc;
58 import javax.naming.Context JavaDoc;
59 import javax.naming.InitialContext JavaDoc;
60 import javax.naming.NamingException JavaDoc;
61 import javax.servlet.http.Cookie JavaDoc;
62 import javax.servlet.http.HttpServletRequest JavaDoc;
63 import javax.servlet.http.HttpServletResponse JavaDoc;
64 import java.util.*;
65 import java.io.IOException JavaDoc;
66
67 /**
68  * CommentPlugin
69  *
70  * @author David Czarnecki
71  * @version $Id: CommentPlugin.java,v 1.11 2006/09/26 02:55:20 czarneckid Exp $
72  * @since blojsom 3.0
73  */

74 public class CommentPlugin extends StandaloneVelocityPlugin implements Listener {
75
76     private Log _logger = LogFactory.getLog(CommentPlugin.class);
77
78     /**
79      * Template for comment e-mails
80      */

81     public static final String JavaDoc COMMENT_PLUGIN_EMAIL_TEMPLATE_TEXT = "org/blojsom/plugin/comment/comment-plugin-email-template-text.vm";
82     public static final String JavaDoc COMMENT_PLUGIN_EMAIL_TEMPLATE_HTML = "org/blojsom/plugin/comment/comment-plugin-email-template-html.vm";
83
84     /**
85      * Default prefix for comment e-mail notification
86      */

87     public static final String JavaDoc DEFAULT_COMMENT_PREFIX = "[blojsom] Comment on: ";
88
89     /**
90      * Initialization parameter for e-mail prefix
91      */

92     public static final String JavaDoc COMMENT_PREFIX_IP = "plugin-comment-email-prefix";
93
94     /**
95      * Initialization parameter to do plugin autoformatting
96      */

97     public static final String JavaDoc COMMENT_AUTOFORMAT_IP = "plugin-comment-autoformat";
98
99     /**
100      * Initialization parameter for the duration of the "remember me" cookies
101      */

102     public static final String JavaDoc COMMENT_COOKIE_EXPIRATION_DURATION_IP = "plugin-comment-expiration-duration";
103
104     /**
105      * Initialization parameter for the throttling of comments from IP addresses
106      */

107     public static final String JavaDoc COMMENT_THROTTLE_MINUTES_IP = "plugin-comment-throttle";
108
109     /**
110      * Initialization parameter for disabling comments on entries after a certain number of days
111      */

112     public static final String JavaDoc COMMENT_DAYS_EXPIRATION_IP = "plugin-comment-days-expiration";
113
114     /**
115      * Default throttle value for comments from a particular IP address
116      */

117     private static final int COMMENT_THROTTLE_DEFAULT_MINUTES = 5;
118
119     /**
120      * Request parameter for the "comment"
121      */

122     public static final String JavaDoc COMMENT_PARAM = "comment";
123
124     /**
125      * Request parameter for the "author"
126      */

127     public static final String JavaDoc AUTHOR_PARAM = "author";
128
129     /**
130      * Request parameter for the "authorEmail"
131      */

132     public static final String JavaDoc AUTHOR_EMAIL_PARAM = "authorEmail";
133
134     /**
135      * Request parameter for the "authorURL"
136      */

137     public static final String JavaDoc AUTHOR_URL_PARAM = "authorURL";
138
139     /**
140      * Request parameter for the "commentText"
141      */

142     public static final String JavaDoc COMMENT_TEXT_PARAM = "commentText";
143
144     /**
145      * Request parameter to "remember" the poster
146      */

147     private static final String JavaDoc REMEMBER_ME_PARAM = "remember";
148
149     /**
150      * Comment "Remember Me" Cookie for the Authors Name
151      */

152     private static final String JavaDoc COOKIE_AUTHOR = "blojsom.cookie.author";
153
154     /**
155      * Comment "Remember Me" Cookie for the Authors Email
156      */

157     private static final String JavaDoc COOKIE_EMAIL = "blojsom.cookie.authorEmail";
158
159     /**
160      * Comment "Remember Me" Cookie for the Authors URL
161      */

162     private static final String JavaDoc COOKIE_URL = "blojsom.cookie.authorURL";
163
164     /**
165      * Comment "Remember Me" Cookie for the "Remember Me" checkbox
166      */

167     private static final String JavaDoc COOKIE_REMEMBER_ME = "blojsom.cookie.rememberme";
168
169     /**
170      * Expiration age for the cookie (1 week)
171      */

172     private static final int COOKIE_EXPIRATION_AGE = 604800;
173
174     /**
175      * Form item, comment parent ID
176      */

177     private static final String JavaDoc COMMENT_PARENT_ID = "comment_parent_id";
178
179     /**
180      * Key under which the indicator this plugin is "live" will be placed
181      * (example: on the request for the JSPDispatcher)
182      */

183     public static final String JavaDoc BLOJSOM_COMMENT_PLUGIN_ENABLED = "BLOJSOM_COMMENT_PLUGIN_ENABLED";
184
185     /**
186      * Key under which the author from the "remember me" cookie will be placed
187      * (example: on the request for the JSPDispatcher)
188      */

189     public static final String JavaDoc BLOJSOM_COMMENT_PLUGIN_AUTHOR = "BLOJSOM_COMMENT_PLUGIN_AUTHOR";
190
191     /**
192      * Key under which the author's e-mail from the "remember me" cookie will be placed
193      * (example: on the request for the JSPDispatcher)
194      */

195     public static final String JavaDoc BLOJSOM_COMMENT_PLUGIN_AUTHOR_EMAIL = "BLOJSOM_COMMENT_PLUGIN_AUTHOR_EMAIL";
196
197     /**
198      * Key under which the author's URL from the "remember me" cookie will be placed
199      * (example: on the request for the JSPDispatcher)
200      */

201     public static final String JavaDoc BLOJSOM_COMMENT_PLUGIN_AUTHOR_URL = "BLOJSOM_COMMENT_PLUGIN_AUTHOR_URL";
202
203     /**
204      * Key under which the "remember me" checkbox from the "remember me" cookie will be placed
205      * (example: on the request for the JSPDispatcher)
206      */

207     public static final String JavaDoc BLOJSOM_COMMENT_PLUGIN_REMEMBER_ME = "BLOJSOM_COMMENT_PLUGIN_REMEMBER_ME";
208
209     /**
210      * IP address meta-data
211      */

212     public static final String JavaDoc BLOJSOM_COMMENT_PLUGIN_METADATA_IP = "BLOJSOM_COMMENT_PLUGIN_METADATA_IP";
213
214     /**
215      * Key under which the blog entry will be placed for merging the comment e-mail
216      */

217     public static final String JavaDoc BLOJSOM_COMMENT_PLUGIN_BLOG_ENTRY = "BLOJSOM_COMMENT_PLUGIN_BLOG_ENTRY";
218
219     /**
220      * Key under which the blog comment will be placed for merging the comment e-mail
221      */

222     public static final String JavaDoc BLOJSOM_COMMENT_PLUGIN_BLOG_COMMENT = "BLOJSOM_COMMENT_PLUGIN_BLOG_COMMENT";
223
224     public static final String JavaDoc BLOJSOM_PLUGIN_COMMENT_METADATA = "BLOJSOM_PLUGIN_COMMENT_METADATA";
225     public static final String JavaDoc BLOJSOM_PLUGIN_COMMENT_METADATA_DESTROY = "BLOJSOM_PLUGIN_COMMENT_METADATA_DESTROY";
226
227     private Map _ipAddressCommentTimes;
228     private String JavaDoc _mailServer;
229     private String JavaDoc _mailServerUsername;
230     private String JavaDoc _mailServerPassword;
231     private Session JavaDoc _session;
232     private Fetcher _fetcher;
233     protected EventBroadcaster _eventBroadcaster;
234
235     /**
236      * Set the {@link EventBroadcaster} event broadcaster
237      *
238      * @param eventBroadcaster {@link EventBroadcaster}
239      */

240     public void setEventBroadcaster(EventBroadcaster eventBroadcaster) {
241         _eventBroadcaster = eventBroadcaster;
242     }
243
244     /**
245      * Set the {@link Fetcher}
246      *
247      * @param fetcher {@link Fetcher}
248      */

249     public void setFetcher(Fetcher fetcher) {
250         _fetcher = fetcher;
251     }
252
253     /**
254      * Initialize this plugin. This method only called when the plugin is instantiated.
255      *
256      * @throws PluginException If there is an error initializing the plugin
257      */

258     public void init() throws PluginException {
259         super.init();
260
261         _mailServer = _servletConfig.getInitParameter(EmailConstants.SMTPSERVER_IP);
262
263         if (_mailServer != null) {
264             if (_mailServer.startsWith("java:comp/env")) {
265                 try {
266                     Context JavaDoc context = new InitialContext JavaDoc();
267                     _session = (Session JavaDoc) context.lookup(_mailServer);
268                 } catch (NamingException JavaDoc e) {
269                     if (_logger.isErrorEnabled()) {
270                         _logger.error(e);
271                     }
272
273                     throw new PluginException(e);
274                 }
275             } else {
276                 _mailServerUsername = _servletConfig.getInitParameter(EmailConstants.SMTPSERVER_USERNAME_IP);
277                 _mailServerPassword = _servletConfig.getInitParameter(EmailConstants.SMTPSERVER_PASSWORD_IP);
278             }
279         } else {
280             if (_logger.isErrorEnabled()) {
281                 _logger.error("Missing SMTP servername servlet initialization parameter: " + EmailConstants.SMTPSERVER_IP);
282             }
283         }
284
285         _ipAddressCommentTimes = new WeakHashMap();
286         _eventBroadcaster.addListener(this);
287     }
288
289     /**
290      * Process the blog entries
291      *
292      * @param httpServletRequest Request
293      * @param httpServletResponse Response
294      * @param blog {@link Blog} instance
295      * @param context Context
296      * @param entries Blog entries retrieved for the particular request
297      * @return Modified set of blog entries
298      * @throws PluginException If there is an error processing the blog entries
299      */

300     public Entry[] process(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map context, Entry[] entries) throws PluginException {
301         context.put(BLOJSOM_COMMENT_PLUGIN_ENABLED, blog.getBlogCommentsEnabled());
302         if (!blog.getBlogCommentsEnabled().booleanValue()) {
303             if (_logger.isDebugEnabled()) {
304                 _logger.debug("Comments not enabled for blog: " + blog.getBlogId());
305             }
306
307             return entries;
308         }
309
310         Boolean JavaDoc _blogCommentsEnabled;
311         _blogCommentsEnabled = blog.getBlogCommentsEnabled();
312
313         int _cookieExpiration;
314         String JavaDoc cookieExpiration = blog.getProperty(COMMENT_COOKIE_EXPIRATION_DURATION_IP);
315         if (BlojsomUtils.checkNullOrBlank(cookieExpiration)) {
316             _cookieExpiration = COOKIE_EXPIRATION_AGE;
317         } else {
318             try {
319                 _cookieExpiration = Integer.parseInt(cookieExpiration);
320             } catch (NumberFormatException JavaDoc e) {
321                 _cookieExpiration = COOKIE_EXPIRATION_AGE;
322             }
323         }
324
325         if (entries.length == 0) {
326             return entries;
327         }
328
329         String JavaDoc author = httpServletRequest.getParameter(AUTHOR_PARAM);
330         String JavaDoc authorEmail = httpServletRequest.getParameter(AUTHOR_EMAIL_PARAM);
331         String JavaDoc authorURL = httpServletRequest.getParameter(AUTHOR_URL_PARAM);
332         String JavaDoc rememberMe = httpServletRequest.getParameter(REMEMBER_ME_PARAM);
333
334         // Check to see if the person has requested they be "remembered" and if so
335
// extract their information from the appropriate cookies
336
Cookie JavaDoc authorCookie = CookieUtils.getCookie(httpServletRequest, COOKIE_AUTHOR);
337         if ((authorCookie != null) && BlojsomUtils.checkNullOrBlank(author)) {
338             author = authorCookie.getValue();
339             if (_logger.isDebugEnabled()) {
340                 _logger.debug("Pulling author from cookie: " + author);
341             }
342
343             if ("".equals(author)) {
344                 author = null;
345             } else {
346                 context.put(BLOJSOM_COMMENT_PLUGIN_AUTHOR, author);
347             }
348
349             Cookie JavaDoc authorEmailCookie = CookieUtils.getCookie(httpServletRequest, COOKIE_EMAIL);
350             if ((authorEmailCookie != null) && BlojsomUtils.checkNullOrBlank(authorEmail)) {
351                 authorEmail = authorEmailCookie.getValue();
352                 if (_logger.isDebugEnabled()) {
353                     _logger.debug("Pulling author email from cookie: " + authorEmail);
354                 }
355
356                 if (authorEmail == null) {
357                     authorEmail = "";
358                 } else {
359                     context.put(BLOJSOM_COMMENT_PLUGIN_AUTHOR_EMAIL, authorEmail);
360                 }
361             }
362
363             Cookie JavaDoc authorUrlCookie = CookieUtils.getCookie(httpServletRequest, COOKIE_URL);
364             if ((authorUrlCookie != null) && BlojsomUtils.checkNullOrBlank(authorURL)) {
365                 authorURL = authorUrlCookie.getValue();
366                 if (_logger.isDebugEnabled()) {
367                     _logger.debug("Pulling author URL from cookie: " + authorURL);
368                 }
369
370                 if (authorURL == null) {
371                     authorURL = "";
372                 } else {
373                     context.put(BLOJSOM_COMMENT_PLUGIN_AUTHOR_URL, authorURL);
374                 }
375             }
376
377             Cookie JavaDoc rememberMeCookie = CookieUtils.getCookie(httpServletRequest, COOKIE_REMEMBER_ME);
378             if ((rememberMeCookie != null) && ((rememberMe == null) || "".equals(rememberMe))) {
379                 rememberMe = rememberMeCookie.getValue();
380                 if (rememberMe != null) {
381                     context.put(BLOJSOM_COMMENT_PLUGIN_REMEMBER_ME, rememberMe);
382                 }
383             }
384         }
385
386         String JavaDoc remoteIPAddress = httpServletRequest.getRemoteAddr();
387
388         // Comment handling
389
if ("y".equalsIgnoreCase(httpServletRequest.getParameter(COMMENT_PARAM)) && _blogCommentsEnabled.booleanValue()) {
390             String JavaDoc commentText = httpServletRequest.getParameter(COMMENT_TEXT_PARAM);
391             String JavaDoc remember = httpServletRequest.getParameter(REMEMBER_ME_PARAM);
392
393             if (!BlojsomUtils.checkNullOrBlank(author) && !BlojsomUtils.checkNullOrBlank(commentText)) {
394                 // Check for comment throttling
395
String JavaDoc commentThrottleValue = blog.getProperty(COMMENT_THROTTLE_MINUTES_IP);
396                 if (!BlojsomUtils.checkNullOrBlank(commentThrottleValue)) {
397                     int commentThrottleMinutes;
398
399                     try {
400                         commentThrottleMinutes = Integer.parseInt(commentThrottleValue);
401                     } catch (NumberFormatException JavaDoc e) {
402                         commentThrottleMinutes = COMMENT_THROTTLE_DEFAULT_MINUTES;
403                     }
404                     if (_logger.isDebugEnabled()) {
405                         _logger.debug("Comment throttling enabled at: " + commentThrottleMinutes + " minutes");
406                     }
407
408                     if (_ipAddressCommentTimes.containsKey(remoteIPAddress)) {
409                         Calendar currentTime = Calendar.getInstance();
410                         Calendar timeOfLastComment = (Calendar) _ipAddressCommentTimes.get(remoteIPAddress);
411                         long timeDifference = currentTime.getTimeInMillis() - timeOfLastComment.getTimeInMillis();
412
413                         long differenceInMinutes = timeDifference / (60 * 1000);
414                         if (differenceInMinutes < commentThrottleMinutes) {
415                             if (_logger.isDebugEnabled()) {
416                                 _logger.debug("Comment throttle enabled. Comment from IP address: " + remoteIPAddress + " in less than " + commentThrottleMinutes + " minutes");
417                             }
418
419                             return entries;
420                         } else {
421                             if (_logger.isDebugEnabled()) {
422                                 _logger.debug("Comment throttle enabled. Resetting date of last comment to current time");
423                             }
424
425                             _ipAddressCommentTimes.put(remoteIPAddress, currentTime);
426                         }
427                     } else {
428                         Calendar calendar = Calendar.getInstance();
429                         _ipAddressCommentTimes.put(remoteIPAddress, calendar);
430                     }
431                 }
432
433                 author = author.trim();
434                 author = BlojsomUtils.escapeStringSimple(author);
435                 author = BlojsomUtils.stripLineTerminators(author, " ");
436
437                 commentText = commentText.trim();
438
439                 // Check if autoformatting of comment text should be done
440
boolean autoformatComments = Boolean.valueOf(blog.getProperty(COMMENT_AUTOFORMAT_IP)).booleanValue();
441                 if (autoformatComments) {
442                     commentText = BlojsomUtils.replace(commentText, "\n", "<br />");
443                 }
444
445                 if (authorEmail != null) {
446                     authorEmail = authorEmail.trim();
447                     authorEmail = BlojsomUtils.escapeStringSimple(authorEmail);
448                     authorEmail = BlojsomUtils.stripLineTerminators(authorEmail, " ");
449                 } else {
450                     authorEmail = "";
451                 }
452
453                 if (authorURL != null) {
454                     authorURL = authorURL.trim();
455                     authorURL = BlojsomUtils.escapeStringSimple(authorURL);
456                     authorURL = BlojsomUtils.stripLineTerminators(authorURL, " ");
457                 } else {
458                     authorURL = "";
459                 }
460
461                 if (!BlojsomUtils.checkNullOrBlank(authorURL) && !authorURL.toLowerCase().startsWith("http://")) {
462                     authorURL = "http://" + authorURL;
463                 }
464
465                 Entry entryForComment = _fetcher.newEntry();
466                 try {
467                     String JavaDoc blogEntryId = BlojsomUtils.getRequestValue("entry_id", httpServletRequest);
468                     Integer JavaDoc entryId;
469                     try {
470                         entryId = Integer.valueOf(blogEntryId);
471                     } catch (NumberFormatException JavaDoc e) {
472                         if (_logger.isErrorEnabled()) {
473                             _logger.error(e);
474                         }
475
476                         return entries;
477                     }
478
479                     entryForComment.setId(entryId);
480
481                     _fetcher.loadEntry(blog, entryForComment);
482                     if (_logger.isDebugEnabled()) {
483                         _logger.debug("Loaded entry for comment: " + entryId.toString());
484                     }
485
486                     if (entryForComment.allowsComments().booleanValue()) {
487                         // Check for a comment where the number of days between comment auto-expiration has passed
488
String JavaDoc commentDaysExpiration = blog.getProperty(COMMENT_DAYS_EXPIRATION_IP);
489                         if (!BlojsomUtils.checkNullOrBlank(commentDaysExpiration)) {
490                             try {
491                                 int daysExpiration = Integer.parseInt(commentDaysExpiration);
492                                 int daysBetweenDates = BlojsomUtils.daysBetweenDates(entryForComment.getDate(), new Date());
493                                 if ((daysExpiration > 0) && (daysBetweenDates >= daysExpiration)) {
494                                     if (_logger.isDebugEnabled()) {
495                                         _logger.debug("Comment period for this entry has expired. Expiration period set at " + daysExpiration + " days. Difference in days: " + daysBetweenDates);
496                                     }
497
498                                     return entries;
499                                 }
500                             } catch (NumberFormatException JavaDoc e) {
501                                 if (_logger.isErrorEnabled()) {
502                                     _logger.error("Error in parameter " + COMMENT_DAYS_EXPIRATION_IP + ": " + commentDaysExpiration);
503                                 }
504                             }
505                         }
506                     } else {
507                         if (_logger.isDebugEnabled()) {
508                             _logger.debug("Comments have been disabled for blog entry: " + entryForComment.getId());
509                         }
510
511                         return entries;
512                     }
513                 } catch (FetcherException e) {
514                     if (_logger.isErrorEnabled()) {
515                         _logger.error(e);
516                     }
517
518                     return entries;
519                 }
520
521                 Map commentMetaData = new HashMap();
522
523                 // Check to see if a previous plugin populated meta-data for the comment
524
if (context.containsKey(BLOJSOM_PLUGIN_COMMENT_METADATA)) {
525                     Map metaData = (Map) context.get(BLOJSOM_PLUGIN_COMMENT_METADATA);
526
527                     Iterator metaDataKeys = metaData.keySet().iterator();
528                     Object JavaDoc key;
529                     Object JavaDoc value;
530                     while (metaDataKeys.hasNext()) {
531                         key = metaDataKeys.next();
532                         value = metaData.get(key);
533                         commentMetaData.put(key, value);
534                     }
535                 }
536
537                 CommentResponseSubmissionEvent commentResponseSubmissionEvent = new CommentResponseSubmissionEvent(this, new Date(), blog, httpServletRequest, httpServletResponse, author, authorEmail, authorURL, commentText, entryForComment, commentMetaData);
538                 _eventBroadcaster.processEvent(commentResponseSubmissionEvent);
539                 author = commentResponseSubmissionEvent.getSubmitter();
540                 authorEmail = commentResponseSubmissionEvent.getSubmitterItem1();
541                 authorURL = commentResponseSubmissionEvent.getSubmitterItem2();
542                 commentText = commentResponseSubmissionEvent.getContent();
543
544                 // Check to see if the comment should be destroyed (not saved) automatically
545
if (!commentMetaData.containsKey(BLOJSOM_PLUGIN_COMMENT_METADATA_DESTROY)) {
546                     Comment comment = addBlogComment(author, authorEmail, authorURL, commentText, _blogCommentsEnabled.booleanValue(), commentMetaData, blog, entries[0], httpServletRequest);
547
548                     // For persisting the Last-Modified time
549
context.put(BlojsomConstants.BLOJSOM_LAST_MODIFIED, new Long JavaDoc(new Date().getTime()));
550
551                     if (comment != null) {
552                         try {
553                             _fetcher.loadEntry(blog, entries[0]);
554                             _fetcher.loadEntry(blog, entryForComment);
555                             _eventBroadcaster.broadcastEvent(new CommentAddedEvent(this, new Date(), comment, blog));
556                         } catch (FetcherException e) {
557                             if (_logger.isErrorEnabled()) {
558                                 _logger.error(e);
559                             }
560                         }
561                     }
562                 } else {
563                     if (_logger.isDebugEnabled()) {
564                         _logger.debug("Comment meta-data contained destroy key. Comment was not saved");
565                     }
566                 }
567
568                 // If we're asked to remember the person, then add the appropriate cookies
569
if ((remember != null) && (!"".equals(remember))) {
570                     CookieUtils.addCookie(httpServletResponse, _cookieExpiration, COOKIE_AUTHOR, author);
571                     context.put(BLOJSOM_COMMENT_PLUGIN_AUTHOR, author);
572                     CookieUtils.addCookie(httpServletResponse, _cookieExpiration, COOKIE_EMAIL, authorEmail);
573                     context.put(BLOJSOM_COMMENT_PLUGIN_AUTHOR_EMAIL, authorEmail);
574                     CookieUtils.addCookie(httpServletResponse, _cookieExpiration, COOKIE_URL, authorURL);
575                     context.put(BLOJSOM_COMMENT_PLUGIN_AUTHOR_URL, authorURL);
576                     CookieUtils.addCookie(httpServletResponse, _cookieExpiration, COOKIE_REMEMBER_ME, "true");
577                     context.put(BLOJSOM_COMMENT_PLUGIN_REMEMBER_ME, "true");
578                 }
579
580                 String JavaDoc redirectTo = BlojsomUtils.getRequestValue(BlojsomConstants.REDIRECT_TO_PARAM, httpServletRequest);
581                 if (!BlojsomUtils.checkNullOrBlank(redirectTo)) {
582                     try {
583                         httpServletResponse.sendRedirect(redirectTo);
584                     } catch (IOException JavaDoc e) {
585                     }
586                 }
587             }
588         }
589
590         return entries;
591     }
592
593     /**
594      * Add a comment to a particular blog entry
595      *
596      * @param author Comment author
597      * @param authorEmail Comment author e-mail
598      * @param authorURL Comment author URL
599      * @param userComment Comment
600      * @return BlogComment Entry
601      */

602     private Comment addBlogComment(String JavaDoc author, String JavaDoc authorEmail, String JavaDoc authorURL, String JavaDoc userComment, boolean blogCommentsEnabled, Map commentMetaData, Blog blog, Entry entry, HttpServletRequest JavaDoc httpServletRequest) {
603         Comment comment = null;
604
605         if (blogCommentsEnabled) {
606             try {
607                 comment = _fetcher.newComment();
608                 comment.setBlogEntryId(entry.getId());
609                 comment.setEntry(entry);
610                 comment.setAuthor(author);
611                 comment.setAuthorEmail(authorEmail);
612                 comment.setAuthorURL(authorURL);
613                 comment.setComment(userComment);
614                 comment.setCommentDate(new Date());
615                 comment.setBlogId(blog.getId());
616                 comment.setIp(httpServletRequest.getRemoteAddr());
617                 if (commentMetaData.containsKey(CommentModerationPlugin.BLOJSOM_COMMENT_MODERATION_PLUGIN_APPROVED) &&
618                         "true".equals(commentMetaData.get(CommentModerationPlugin.BLOJSOM_COMMENT_MODERATION_PLUGIN_APPROVED))) {
619                     comment.setStatus(ResponseConstants.APPROVED_STATUS);
620                 } else {
621                     if ("true".equals(blog.getProperty(CommentModerationPlugin.COMMENT_MODERATION_ENABLED))) {
622                         comment.setStatus(ResponseConstants.NEW_STATUS);
623                     } else {
624                         comment.setStatus(ResponseConstants.APPROVED_STATUS);
625                     }
626                 }
627                 comment.setMetaData(commentMetaData);
628
629                 String JavaDoc commentParentID = BlojsomUtils.getRequestValue(COMMENT_PARENT_ID, httpServletRequest);
630                 if (!BlojsomUtils.checkNullOrBlank(commentParentID)) {
631                     try {
632                         comment.setParentId(Integer.valueOf(commentParentID));
633                     } catch (NumberFormatException JavaDoc e) {
634                     }
635                 }
636
637                 _fetcher.saveComment(blog, comment);
638             } catch (FetcherException e) {
639                 if (_logger.isErrorEnabled()) {
640                     _logger.error(e);
641                 }
642
643                 comment = null;
644             }
645         }
646
647         return comment;
648     }
649
650     /**
651      * Perform any cleanup for the plugin. Called after {@link #process}.
652      *
653      * @throws PluginException If there is an error performing cleanup for this plugin
654      */

655     public void cleanup() throws PluginException {
656     }
657
658     /**
659      * Called when BlojsomServlet is taken out of service
660      *
661      * @throws PluginException If there is an error in finalizing this plugin
662      */

663     public void destroy() throws PluginException {
664     }
665
666     /**
667      * Setup the comment e-mail
668      *
669      * @param blog {@link Blog} information
670      * @param email Email message
671      * @throws EmailException If there is an error preparing the e-mail message
672      */

673     protected void setupEmail(Blog blog, Entry entry, Email email) throws EmailException {
674         email.setCharset(BlojsomConstants.UTF8);
675
676         // If we have a mail session for the environment, use that
677
if (_session != null) {
678             email.setMailSession(_session);
679         } else {
680             // Otherwise, if there is a username and password for the mail server, use that
681
if (!BlojsomUtils.checkNullOrBlank(_mailServerUsername) && !BlojsomUtils.checkNullOrBlank(_mailServerPassword)) {
682                 email.setHostName(_mailServer);
683                 email.setAuthentication(_mailServerUsername, _mailServerPassword);
684             } else {
685                 email.setHostName(_mailServer);
686             }
687         }
688
689         email.setFrom(blog.getBlogOwnerEmail(), "Blojsom Comment");
690
691         String JavaDoc author = entry.getAuthor();
692         if (BlojsomUtils.checkNullOrBlank(author)) {
693             author = blog.getBlogOwner();
694         }
695
696         String JavaDoc authorEmail = blog.getBlogOwnerEmail();
697
698         if (author != null) {
699             try {
700                 User user = _fetcher.loadUser(blog, author);
701
702                 if (user == null) {
703                     authorEmail = blog.getBlogOwnerEmail();
704                 } else {
705                     authorEmail = user.getUserEmail();
706                     if (BlojsomUtils.checkNullOrBlank(authorEmail)) {
707                         authorEmail = blog.getBlogOwnerEmail();
708                     }
709                 }
710             } catch (FetcherException e) {
711             }
712         }
713
714         email.addTo(authorEmail, author);
715         email.setSentDate(new Date());
716     }
717
718     /**
719      * Handle an event broadcast from another component
720      *
721      * @param event {@link org.blojsom.event.Event} to be handled
722      */

723     public void handleEvent(Event event) {
724         if (event instanceof CommentAddedEvent) {
725             HtmlEmail email = new HtmlEmail();
726             CommentAddedEvent commentAddedEvent = (CommentAddedEvent) event;
727
728             if (commentAddedEvent.getBlog().getBlogEmailEnabled().booleanValue() && _mailServer != null) {
729                 try {
730                     setupEmail(commentAddedEvent.getBlog(), commentAddedEvent.getEntry(), email);
731
732                     Map emailTemplateContext = new HashMap();
733                     emailTemplateContext.put(BlojsomConstants.BLOJSOM_BLOG, commentAddedEvent.getBlog());
734                     emailTemplateContext.put(BLOJSOM_COMMENT_PLUGIN_BLOG_COMMENT, commentAddedEvent.getComment());
735                     emailTemplateContext.put(BLOJSOM_COMMENT_PLUGIN_BLOG_ENTRY, commentAddedEvent.getEntry());
736
737                     String JavaDoc htmlText = mergeTemplate(COMMENT_PLUGIN_EMAIL_TEMPLATE_HTML, commentAddedEvent.getBlog(), emailTemplateContext);
738                     String JavaDoc plainText = mergeTemplate(COMMENT_PLUGIN_EMAIL_TEMPLATE_TEXT, commentAddedEvent.getBlog(), emailTemplateContext);
739
740                     email.setHtmlMsg(htmlText);
741                     email.setTextMsg(plainText);
742
743                     String JavaDoc emailPrefix = (String JavaDoc) commentAddedEvent.getBlog().getProperties().get(COMMENT_PREFIX_IP);
744                     if (BlojsomUtils.checkNullOrBlank(emailPrefix)) {
745                         emailPrefix = DEFAULT_COMMENT_PREFIX;
746                     }
747
748                     email = (HtmlEmail) email.setSubject(emailPrefix + commentAddedEvent.getEntry().getTitle());
749
750                     email.send();
751                 } catch (EmailException e) {
752                     if (_logger.isErrorEnabled()) {
753                         _logger.error(e);
754                     }
755                 }
756             } else {
757                 if (_logger.isErrorEnabled()) {
758                     _logger.error("Missing SMTP servername servlet initialization parameter: " + EmailConstants.SMTPSERVER_IP);
759                 }
760             }
761         }
762     }
763
764     /**
765      * Process an event from another component
766      *
767      * @param event {@link org.blojsom.event.Event} to be handled
768      */

769     public void processEvent(Event event) {
770     }
771 }
772
Popular Tags