001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software GmbH & Co. KG, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.workplace.tools.workplace.broadcast;
029
030import org.opencms.file.CmsUser;
031import org.opencms.jsp.CmsJspActionElement;
032import org.opencms.main.CmsIllegalStateException;
033import org.opencms.main.CmsLog;
034import org.opencms.main.CmsSessionInfo;
035import org.opencms.main.OpenCms;
036import org.opencms.util.CmsStringUtil;
037import org.opencms.widgets.CmsDisplayWidget;
038import org.opencms.widgets.CmsInputWidget;
039import org.opencms.widgets.CmsTextareaWidget;
040import org.opencms.workplace.CmsWidgetDialogParameter;
041
042import java.util.ArrayList;
043import java.util.Collections;
044import java.util.Iterator;
045import java.util.List;
046
047import javax.servlet.http.HttpServletRequest;
048import javax.servlet.http.HttpServletResponse;
049import javax.servlet.jsp.PageContext;
050
051import org.apache.commons.logging.Log;
052
053/**
054 * Dialog to edit an email to send in the administration view.<p>
055 *
056 * @since 6.0.0
057 */
058public class CmsSendEmailDialog extends A_CmsMessageDialog {
059
060    /** localized messages Keys prefix. */
061    public static final String KEY_PREFIX = "email";
062
063    /** The static log object for this class. */
064    private static final Log LOG = CmsLog.getLog(CmsSendEmailDialog.class);
065
066    /** a warning about excluded users with no email. */
067    private String m_excludedUsers = "";
068
069    /**
070     * Public constructor with JSP action element.<p>
071     *
072     * @param jsp an initialized JSP action element
073     */
074    public CmsSendEmailDialog(CmsJspActionElement jsp) {
075
076        super(jsp);
077    }
078
079    /**
080     * Public constructor with JSP variables.<p>
081     *
082     * @param context the JSP page context
083     * @param req the JSP request
084     * @param res the JSP response
085     */
086    public CmsSendEmailDialog(PageContext context, HttpServletRequest req, HttpServletResponse res) {
087
088        this(new CmsJspActionElement(context, req, res));
089    }
090
091    /**
092     * Commits the edited project to the db.<p>
093     */
094    @Override
095    public void actionCommit() {
096
097        List<Throwable> errors = new ArrayList<Throwable>();
098
099        if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_msgInfo.getTo())) {
100            setCommitErrors(
101                Collections.singletonList((Throwable)new CmsIllegalStateException(
102                    Messages.get().container(Messages.ERR_NO_SELECTED_USER_WITH_EMAIL_0))));
103            return;
104        }
105        try {
106            m_msgInfo.setTo(getEmailAddresses());
107            m_msgInfo.sendEmail(getCms());
108        } catch (Throwable t) {
109            errors.add(t);
110        } finally {
111            m_msgInfo.setTo(getToNames());
112        }
113        // set the list of errors to display when saving failed
114        setCommitErrors(errors);
115    }
116
117    /**
118     * Returns a warning if users have been excluded.<p>
119     *
120     * @return a warning
121     */
122    public String getExcludedUsers() {
123
124        return m_excludedUsers;
125    }
126
127    /**
128     * Sets the warning message if users have been excluded.<p>
129     *
130     * @param excludedUsers the warning message
131     */
132    public void setExcludedUsers(String excludedUsers) {
133
134        m_excludedUsers = excludedUsers;
135    }
136
137    /**
138     * @see org.opencms.workplace.CmsWidgetDialog#createDialogHtml(java.lang.String)
139     */
140    @Override
141    protected String createDialogHtml(String dialog) {
142
143        StringBuffer result = new StringBuffer(1024);
144
145        result.append(createWidgetTableStart());
146        // show error header once if there were validation errors
147        result.append(createWidgetErrorHeader());
148
149        int n = 4;
150        getToNames(); // need it to fill the exclude users property
151        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getExcludedUsers())) {
152            n++;
153        }
154        if (dialog.equals(PAGES[0])) {
155            // create the widgets for the first dialog page
156            result.append(dialogBlockStart(key(Messages.GUI_MESSAGE_EDITOR_LABEL_HEADER_BLOCK_0)));
157            result.append(createWidgetTableStart());
158            result.append(createDialogRowsHtml(0, n - 1));
159            result.append(createWidgetTableEnd());
160            result.append(dialogBlockEnd());
161            result.append(dialogBlockStart(key(Messages.GUI_MESSAGE_EDITOR_LABEL_CONTENT_BLOCK_0)));
162            result.append(createWidgetTableStart());
163            result.append(createDialogRowsHtml(n, n));
164            result.append(createWidgetTableEnd());
165            result.append(dialogBlockEnd());
166        }
167
168        result.append(createWidgetTableEnd());
169        return result.toString();
170    }
171
172    /**
173     * Creates the list of widgets for this dialog.<p>
174     */
175    @Override
176    protected void defineWidgets() {
177
178        // initialize the project object to use for the dialog
179        initMessageObject();
180
181        setKeyPrefix(KEY_PREFIX);
182
183        addWidget(new CmsWidgetDialogParameter(m_msgInfo, "from", PAGES[0], new CmsDisplayWidget()));
184        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getExcludedUsers())) {
185            addWidget(new CmsWidgetDialogParameter(this, "excludedUsers", PAGES[0], new CmsDisplayWidget()));
186        }
187        addWidget(new CmsWidgetDialogParameter(m_msgInfo, "to", PAGES[0], new CmsDisplayWidget()));
188        addWidget(new CmsWidgetDialogParameter(m_msgInfo, "cc", PAGES[0], "", new CmsInputWidget(), 0, 1));
189        addWidget(new CmsWidgetDialogParameter(m_msgInfo, "subject", PAGES[0], new CmsInputWidget()));
190        addWidget(new CmsWidgetDialogParameter(m_msgInfo, "msg", PAGES[0], new CmsTextareaWidget(12)));
191    }
192
193    /**
194     * Returns a semicolon separated list of user names.<p>
195     *
196     * @return a semicolon separated list of user names
197     */
198    @Override
199    protected String getToNames() {
200
201        List<String> excluded = new ArrayList<String>();
202        List<String> users = new ArrayList<String>();
203        Iterator<String> itIds = idsList().iterator();
204        while (itIds.hasNext()) {
205            String id = itIds.next();
206            CmsSessionInfo session = OpenCms.getSessionManager().getSessionInfo(id);
207            if (session != null) {
208                try {
209                    CmsUser user = getCms().readUser(session.getUserId());
210                    String userName = user.getFullName();
211                    if (!users.contains(userName)) {
212                        String emailAddress = user.getEmail();
213                        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(emailAddress)) {
214                            users.add(userName);
215                        } else {
216                            excluded.add(userName);
217                        }
218                    }
219                } catch (Exception e) {
220                    LOG.error(e.getLocalizedMessage(), e);
221                }
222            }
223        }
224        if (!excluded.isEmpty()) {
225            StringBuffer text = new StringBuffer(500);
226            text.append(Messages.get().container(Messages.GUI_EXCLUDED_USERS_WARNING_0).key(getLocale()));
227            text.append("\n");
228            Iterator<String> it = excluded.iterator();
229            while (it.hasNext()) {
230                text.append("- ");
231                text.append(it.next());
232                text.append("\n");
233            }
234            setExcludedUsers(text.toString());
235        }
236        if (users.isEmpty()) {
237            setCommitErrors(
238                Collections.singletonList((Throwable)new CmsIllegalStateException(
239                    Messages.get().container(Messages.ERR_NO_SELECTED_USER_WITH_EMAIL_0))));
240            return "";
241        }
242        StringBuffer result = new StringBuffer(256);
243        Iterator<String> itUsers = users.iterator();
244        while (itUsers.hasNext()) {
245            result.append(itUsers.next().toString());
246            if (itUsers.hasNext()) {
247                result.append("; ");
248            }
249        }
250        return result.toString();
251    }
252
253    /**
254     * Returns a semicolon separated list of email addresses.<p>
255     *
256     * @return a semicolon separated list of email addresses
257     */
258    private String getEmailAddresses() {
259
260        List<String> emails = new ArrayList<String>();
261        Iterator<String> itIds = idsList().iterator();
262        while (itIds.hasNext()) {
263            String id = itIds.next();
264            CmsSessionInfo session = OpenCms.getSessionManager().getSessionInfo(id);
265            if (session != null) {
266                try {
267                    String emailAddress = getCms().readUser(session.getUserId()).getEmail();
268                    if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(emailAddress) && !emails.contains(emailAddress)) {
269                        emails.add(emailAddress);
270                    }
271                } catch (Exception e) {
272                    LOG.error(e.getLocalizedMessage(), e);
273                }
274            }
275        }
276        StringBuffer result = new StringBuffer(256);
277        Iterator<String> itEmails = emails.iterator();
278        while (itEmails.hasNext()) {
279            result.append(itEmails.next());
280            if (itEmails.hasNext()) {
281                result.append("; ");
282            }
283        }
284        return result.toString();
285    }
286}