View Javadoc
1   /**
2    * This file Copyright (c) 2003-2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.mail.util;
35  
36  import info.magnolia.cms.beans.runtime.Document;
37  import info.magnolia.cms.beans.runtime.MultipartForm;
38  import info.magnolia.cms.security.Security;
39  import info.magnolia.cms.security.User;
40  import info.magnolia.cms.security.UserManager;
41  import info.magnolia.context.MgnlContext;
42  import info.magnolia.module.mail.MailConstants;
43  import info.magnolia.module.mail.handlers.LoggingLevel;
44  import info.magnolia.module.mail.templates.MailAttachment;
45  
46  import java.io.ByteArrayInputStream;
47  import java.io.IOException;
48  import java.net.MalformedURLException;
49  import java.net.URL;
50  import java.util.ArrayList;
51  import java.util.Collection;
52  import java.util.HashMap;
53  import java.util.Iterator;
54  import java.util.List;
55  import java.util.Map;
56  import java.util.Map.Entry;
57  import java.util.Properties;
58  
59  import javax.jcr.RepositoryException;
60  
61  import org.apache.commons.lang3.StringUtils;
62  import org.apache.logging.log4j.LogManager;
63  import org.slf4j.Logger;
64  import org.slf4j.LoggerFactory;
65  
66  /**
67   * Provides static utility methods to work with emails in Magnolia.
68   *
69   */
70  public class MailUtil {
71  
72      public static Logger log = LoggerFactory.getLogger(MailUtil.class);
73  
74      /**
75       * Transforms a string name=value\r\nname=value.. into a hashmap
76       */
77      public static Map<String, String> convertToMap(String parameters) throws IOException {
78          Map<String, String> map = new HashMap<>();
79          ByteArrayInputStream string = new ByteArrayInputStream(parameters.getBytes());
80          Properties props = new Properties();
81          props.load(string);
82  
83          for (Object o : props.keySet()) {
84              String key = (String) o;
85              map.put(key, (String) props.get(key));
86          }
87  
88          return map;
89      }
90  
91      /**
92       * Creates a list with the documents uploaded in the form.
93       */
94      public static List<MailAttachment> createAttachmentList() {
95          List<MailAttachment> attachments = new ArrayList<>();
96          try {
97              // get any possible attachment
98              if (MgnlContext.getPostedForm() != null) {
99                  MultipartForm form = MgnlContext.getPostedForm();
100                 Map<String, Document> docs = form.getDocuments();
101 
102                 for (Entry<String, Document> entry : docs.entrySet()) {
103                     Document doc = entry.getValue();
104 
105                     if (doc != null) {
106                         attachments.add(new MailAttachment(doc.getFile().toURL(), entry.getKey()));
107                     }
108                 }
109             }
110 
111         } catch (Exception e) {
112 
113         }
114         return attachments;
115     }
116 
117     public static List<MailAttachment> createAttachmentList(Map parameters) {
118         List<MailAttachment> attachments = new ArrayList<>();
119         if (parameters.containsKey("attachments")) {
120             for (Object o : ((List) parameters.get("attachments"))) {
121                 String name = (String) o;
122                 try {
123                     attachments.add(new MailAttachment(new URL(name), name));
124                 } catch (MalformedURLException e) {
125                     log.error("sending attachment" + name, e);
126                 }
127             }
128 
129         } else {
130             //find if there are in the form
131             return createAttachmentList();
132         }
133         return attachments;
134     }
135 
136 
137     /**
138      * convert email address mapping<br>.
139      * <code>user-</code> will be replace by the email address of the user as stored in the user repository
140      * <code>group-</code> will
141      */
142     public static String convertEmailList(String mailTo) {
143         final UserManager manager = Security.getUserManager();
144         StringBuffer ret = new StringBuffer();
145         if (StringUtils.isEmpty(mailTo)) {
146             return "";
147         }
148 
149         String[] list = mailTo.split(";");
150         for (int i = 0; i < list.length; i++) { // for each item
151             final String token = list[i];
152             if (i != 0) {
153                 ret.append("\n");
154             }
155             if (token.startsWith(MailConstants.PREFIX_USER)) {
156                 final String userName = StringUtils.removeStart(token, MailConstants.PREFIX_USER);
157                 log.debug("username = {}", userName);
158                 User user = manager.getUser(userName);
159                 ret.append(getUserMail(user));
160             } else if (token.startsWith(MailConstants.PREFIX_GROUP)) {
161                 final String groupName = StringUtils.removeStart(token, MailConstants.PREFIX_GROUP);
162                 getGroupMembersMails(manager, ret, groupName);
163             } else if (token.startsWith(MailConstants.PREFIX_ROLE)) {
164                 final String roleName = StringUtils.removeStart(token, MailConstants.PREFIX_ROLE);
165                 try {
166                     Collection<User> users = getAllUserNodes(manager);
167                     for (User user : users) {
168                         if (user.getRoles().contains(roleName)) {
169                             ret.append(getUserMail(user));
170                             ret.append("\n");
171                         }
172                     }
173                 } catch (Exception e) {
174                     log.error("can not get user email info.");
175                 }
176             } else {
177                 // none of the above, just add the mail to the list
178                 ret.append(token);
179             }
180         }
181         return ret.toString();
182     }
183 
184     protected static void getGroupMembersMails(final UserManager manager, StringBuffer ret, final String groupName) {
185         log.debug("group = {}", groupName);
186         try {
187             Collection<User> users = getAllUserNodes(manager);
188             for (User user : users) {
189                 if (user.getAllGroups().contains(groupName)) {
190                     String mail = getUserMail(user);
191                     log.debug("user {} will be notified using mail address {}.", user.getName(), mail);
192                     if (mail != null) {
193                         ret.append(mail);
194                         ret.append("\n");
195                     }
196                 }
197             }
198         } catch (Exception e) {
199             log.error("can not get user email info.", e);
200         }
201         log.debug("found:" + ret.toString());
202     }
203 
204     /**
205      * @return Collection<User>
206      * @throws RepositoryException
207      */
208     protected static Collection<User> getAllUserNodes(UserManager manager) throws RepositoryException {
209         return manager.getAllUsers();
210     }
211 
212     protected static String getUserMail(User user) {
213         return user.getProperty("email");
214     }
215 
216     public static Object getParameter(Map<String, Object> param, String name, String defaultValue) {
217 
218         if (param != null && param.containsKey(name)) {
219             return param.get(name);
220         } else {
221             return defaultValue;
222         }
223     }
224 
225     public static void logMail(Map params, String loggerName) {
226         Iterator i = params.entrySet().iterator();
227         StringBuffer buf = new StringBuffer();
228         while (i.hasNext()) {
229             Entry pairs = (Entry) i.next();
230             buf.append(" " + pairs.getKey() + " : " + pairs.getValue()
231                     + ",");
232         }
233         LogManager.getLogger(loggerName).log(LoggingLevel.MAIL_TRAIL,
234                 StringUtils.remove(StringUtils.removeEnd(buf.toString(), ","), System.getProperty("line.separator")));
235     }
236 
237 }