1   /**
2    * Copyright (c) 2000-2007 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portlet.webform.action;
24  
25  import com.liferay.mail.service.MailServiceUtil;
26  import com.liferay.portal.captcha.CaptchaTextException;
27  import com.liferay.portal.captcha.CaptchaUtil;
28  import com.liferay.portal.kernel.mail.MailMessage;
29  import com.liferay.portal.kernel.util.GetterUtil;
30  import com.liferay.portal.kernel.util.StringMaker;
31  import com.liferay.portal.kernel.util.StringPool;
32  import com.liferay.portal.kernel.util.StringUtil;
33  import com.liferay.portal.kernel.util.Validator;
34  import com.liferay.portal.struts.PortletAction;
35  import com.liferay.portal.util.PropsUtil;
36  import com.liferay.portlet.PortletConfigImpl;
37  import com.liferay.portlet.PortletPreferencesFactoryUtil;
38  import com.liferay.util.FileUtil;
39  import com.liferay.util.servlet.SessionErrors;
40  import com.liferay.util.servlet.SessionMessages;
41  
42  import java.util.ArrayList;
43  import java.util.Iterator;
44  import java.util.List;
45  
46  import javax.mail.internet.InternetAddress;
47  
48  import javax.portlet.ActionRequest;
49  import javax.portlet.ActionResponse;
50  import javax.portlet.PortletConfig;
51  import javax.portlet.PortletPreferences;
52  import javax.portlet.RenderRequest;
53  import javax.portlet.RenderResponse;
54  
55  import org.apache.commons.logging.Log;
56  import org.apache.commons.logging.LogFactory;
57  import org.apache.struts.action.ActionForm;
58  import org.apache.struts.action.ActionForward;
59  import org.apache.struts.action.ActionMapping;
60  
61  /**
62   * <a href="ViewAction.java.html"><b><i>View Source</i></b></a>
63   *
64   * @author Daniel Weisser
65   * @author Jorge Ferrer
66   *
67   */
68  public class ViewAction extends PortletAction {
69  
70      public void processAction(
71              ActionMapping mapping, ActionForm form, PortletConfig config,
72              ActionRequest req, ActionResponse res)
73          throws Exception {
74  
75          PortletConfigImpl configImpl = (PortletConfigImpl)config;
76  
77          String portletId = configImpl.getPortletId();
78  
79          PortletPreferences prefs =
80              PortletPreferencesFactoryUtil.getPortletSetup(
81                  req, portletId, true, true);
82  
83          boolean requireCaptcha = GetterUtil.getBoolean(
84              prefs.getValue("requireCaptcha", StringPool.BLANK));
85          String successURL = GetterUtil.getString(
86              prefs.getValue("successURL", StringPool.BLANK));
87          boolean sendAsEmail = GetterUtil.getBoolean(
88              prefs.getValue("sendAsEmail", StringPool.BLANK), true);
89          boolean saveToFile = GetterUtil.getBoolean(
90              prefs.getValue("saveToFile", StringPool.BLANK));
91          String fileName = GetterUtil.getString(
92              prefs.getValue("fileName", StringPool.BLANK));
93  
94          if (requireCaptcha) {
95              try {
96                  CaptchaUtil.check(req);
97              }
98              catch (CaptchaTextException cte) {
99                  SessionErrors.add(req, CaptchaTextException.class.getName());
100             }
101         }
102 
103         List fieldValues = new ArrayList();
104 
105         for (int i = 1; i <= _MAX_FIELDS; i++) {
106             fieldValues.add(req.getParameter("field" + i));
107         }
108 
109         if (validate(fieldValues, prefs)) {
110             boolean emailSent = false;
111             boolean fileSaved = false;
112 
113             if (sendAsEmail) {
114                 emailSent = sendEmail(fieldValues, prefs);
115             }
116 
117             if (saveToFile) {
118                 fileSaved = saveFile(fieldValues, prefs, fileName);
119             }
120 
121             if ((sendAsEmail == emailSent) && (saveToFile == fileSaved)) {
122                 SessionMessages.add(req, "emailSent");
123             }
124             else {
125                 SessionErrors.add(req, "emailNotSent");
126             }
127         }
128         else {
129             SessionErrors.add(req, "allFieldsRequired");
130         }
131 
132         if (SessionErrors.isEmpty(req) && Validator.isNotNull(successURL)) {
133             res.sendRedirect(successURL);
134         }
135     }
136 
137     public ActionForward render(
138             ActionMapping mapping, ActionForm form, PortletConfig config,
139             RenderRequest req, RenderResponse res)
140         throws Exception {
141 
142         return mapping.findForward("portlet.web_form.view");
143     }
144 
145     protected String getMailBody(List fieldValues, PortletPreferences prefs) {
146         StringMaker sm = new StringMaker();
147 
148         Iterator itr = fieldValues.iterator();
149 
150         for (int i = 1; itr.hasNext(); i++) {
151             String fieldValue = (String)itr.next();
152             String fieldLabel = prefs.getValue(
153                 "fieldLabel" + i, StringPool.BLANK);
154 
155             if (Validator.isNotNull(fieldLabel)) {
156                 sm.append(fieldLabel);
157                 sm.append(" : ");
158                 sm.append(fieldValue);
159                 sm.append("\n");
160             }
161         }
162 
163         return sm.toString();
164     }
165 
166     protected boolean saveFile(
167         List fieldValues, PortletPreferences prefs, String fileName) {
168 
169         // Save the file as a standard Excel CSV format. Use ; as a delimiter,
170         // quote each entry with double quotes, and escape double quotes in
171         // values a two double quotes.
172 
173         StringMaker sm = new StringMaker();
174 
175         Iterator itr = fieldValues.iterator();
176 
177         for (int i = 1; itr.hasNext(); i++) {
178             String fieldValue = (String)itr.next();
179             String fieldLabel = prefs.getValue(
180                 "fieldLabel" + i, StringPool.BLANK);
181 
182             if (Validator.isNotNull(fieldLabel)) {
183                 sm.append("\"");
184                 sm.append(StringUtil.replace(fieldValue, "\"", "\"\""));
185                 sm.append("\";");
186             }
187         }
188 
189         String s = sm.substring(0, sm.length() - 1) + "\n";
190 
191         try {
192             FileUtil.append(fileName, s);
193 
194             return true;
195         }
196         catch (Exception e) {
197             _log.error("The web form email could not be saved", e);
198 
199             return false;
200         }
201     }
202 
203     protected boolean sendEmail(List fieldValues, PortletPreferences prefs) {
204         try {
205             String subject = prefs.getValue("subject", StringPool.BLANK);
206             String emailAddress = prefs.getValue(
207                 "emailAddress", StringPool.BLANK);
208 
209             if (Validator.isNull(emailAddress)) {
210                 _log.error(
211                     "The web form email cannot be sent because no email " +
212                         "address is configured");
213 
214                 return false;
215             }
216 
217             String body = getMailBody(fieldValues, prefs);
218 
219             InternetAddress fromAddress = new InternetAddress(emailAddress);
220             InternetAddress toAddress = new InternetAddress(emailAddress);
221 
222             MailMessage mailMessage = new MailMessage(
223                 fromAddress, toAddress, subject, body);
224 
225             MailServiceUtil.sendEmail(mailMessage);
226 
227             return true;
228         }
229         catch (Exception e) {
230             _log.error("The web form email could not be sent", e);
231 
232             return false;
233         }
234     }
235 
236     protected boolean validate(List fieldValues, PortletPreferences prefs) {
237         for (int i = 1; i < _MAX_FIELDS; i++) {
238             String fieldLabel = prefs.getValue(
239                 "fieldLabel" + i, StringPool.BLANK);
240             boolean fieldOptional = GetterUtil.getBoolean(
241                 prefs.getValue("fieldOptional" + i, StringPool.BLANK));
242             String fieldValue = (String)fieldValues.get(i - 1);
243 
244             if (!fieldOptional && Validator.isNotNull(fieldLabel) &&
245                 Validator.isNull(fieldValue)) {
246 
247                 return false;
248             }
249         }
250 
251         return true;
252     }
253 
254     private static final int _MAX_FIELDS = GetterUtil.getInteger(
255         PropsUtil.get(PropsUtil.WEB_FORM_PORTLET_MAX_FIELDS));
256 
257     private static Log _log = LogFactory.getLog(ViewAction.class);
258 
259 }