View Javadoc

1   /**
2    * This file Copyright (c) 2003-2010 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.config.ContentRepository;
37  import info.magnolia.cms.beans.runtime.Document;
38  import info.magnolia.cms.beans.runtime.MultipartForm;
39  import info.magnolia.cms.core.Content;
40  import info.magnolia.cms.core.HierarchyManager;
41  import info.magnolia.cms.core.ItemType;
42  import info.magnolia.cms.security.Realm;
43  import info.magnolia.cms.security.Security;
44  import info.magnolia.cms.security.User;
45  import info.magnolia.cms.security.UserManager;
46  import info.magnolia.context.MgnlContext;
47  import info.magnolia.module.mail.MailConstants;
48  import info.magnolia.module.mail.handlers.LoggingLevel;
49  import info.magnolia.module.mail.templates.MailAttachment;
50  
51  import java.io.ByteArrayInputStream;
52  import java.io.IOException;
53  import java.net.MalformedURLException;
54  import java.net.URL;
55  import java.util.ArrayList;
56  import java.util.Collection;
57  import java.util.HashMap;
58  import java.util.Iterator;
59  import java.util.List;
60  import java.util.Map;
61  import java.util.Properties;
62  import java.util.Map.Entry;
63  
64  import javax.jcr.RepositoryException;
65  
66  import org.apache.commons.lang.StringUtils;
67  import org.slf4j.Logger;
68  import org.slf4j.LoggerFactory;
69  
70  public class MailUtil {
71  
72      public static Logger log = LoggerFactory.getLogger(MailUtil.class);
73      /**
74       * Transforms a string name=value\r\nname=value.. into a hashmap
75       */
76      public static Map<String, String> convertToMap(String parameters) throws IOException {
77          Map<String, String> map = new HashMap<String, String>();
78          ByteArrayInputStream string = new ByteArrayInputStream(parameters.getBytes());
79          Properties props = new Properties();
80          props.load(string);
81  
82          Iterator iter = props.keySet().iterator();
83          while (iter.hasNext()) {
84              String key = (String) iter.next();
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       * @return
94       */
95      public static List<MailAttachment> createAttachmentList() {
96          List<MailAttachment> attachments = new ArrayList<MailAttachment>();
97           try {
98               // get any possible attachment
99               if(MgnlContext.getPostedForm() != null) {
100                  MultipartForm form = MgnlContext.getPostedForm();
101                  Map<String, Document> docs = form.getDocuments();
102 
103                  for (Entry<String, Document> entry : docs.entrySet()) {
104                      Document doc = entry.getValue();
105 
106                      if (doc != null) {
107                          attachments.add(new MailAttachment(doc.getFile().toURL(), entry.getKey()));
108                      }
109                  }
110              }
111 
112          } catch (Exception e) {
113 
114          }
115          return attachments;
116      }
117 
118     public static List<MailAttachment> createAttachmentList(Map parameters) {
119         List<MailAttachment> attachments = new ArrayList<MailAttachment>();
120         if(parameters.containsKey("attachments")) {
121             Iterator iterator = ((List)parameters.get("attachments")).iterator();
122             while(iterator.hasNext()) {
123                 String name = (String)iterator.next();
124                 try {
125                     attachments.add(new MailAttachment(new URL(name), name));
126                 } catch (MalformedURLException e) {
127                     log.error("sending attachment" + name, e);
128                 }
129             }
130 
131         } else {
132             //find if there are in the form
133             return createAttachmentList();
134         }
135         return attachments;
136     }
137 
138 
139     /**
140      * convert email address mapping<br>
141      * <code>user-</code> will be replace by the email address of the user as stored in the user repository
142      * <code>group-</code> will
143      */
144     public static String convertEmailList(String mailTo) {
145         final UserManager manager = Security.getUserManager();
146         StringBuffer ret = new StringBuffer();
147         if(StringUtils.isEmpty(mailTo)){
148             return "";
149         }
150 
151         String[] list = mailTo.split(";");
152         if (list == null) {
153             return "";
154         }
155         for (int i = 0; i < list.length; i++) { // for each item
156             final String token = list[i];
157             if (i != 0) {
158                 ret.append("\n");
159             }
160             if (token.startsWith(MailConstants.PREFIX_USER)) {
161                 final String userName = StringUtils.removeStart(token, MailConstants.PREFIX_USER);
162                 log.debug("username = {}", userName);
163                 User user = manager.getUser(userName);
164                 ret.append(getUserMail(user));
165             }
166             else if (token.startsWith(MailConstants.PREFIX_GROUP)) {
167                 final String groupName = StringUtils.removeStart(token, MailConstants.PREFIX_GROUP);
168                 try {
169                     Collection users = getAllUserNodes();
170                     Iterator iter = users.iterator();
171                     while(iter.hasNext()){
172                         Content userNode = ((Content) iter.next());
173                         User user = manager.getUser(userNode.getName());
174                         if (user.getGroups().contains(groupName)){
175                             ret.append(getUserMail(user));
176                             ret.append("\n");
177                         }
178                     }
179                 }
180                 catch (Exception e) {
181                     log.error("can not get user email info.");
182                 }
183             }
184             else if (token.startsWith(MailConstants.PREFIX_ROLE)) {
185                 final String roleName = StringUtils.removeStart(token, MailConstants.PREFIX_ROLE);
186                 try {
187                     Collection users = getAllUserNodes();
188                     Iterator iter = users.iterator();
189                     while(iter.hasNext()){
190                         Content userNode = ((Content) iter.next());
191                         User user = manager.getUser(userNode.getName());
192                         if (user.getRoles().contains(roleName)){
193                             ret.append(getUserMail(user));
194                             ret.append("\n");
195                         }
196                     }
197                 }
198                 catch (Exception e) {
199                     log.error("can not get user email info.");
200                 }
201             }
202             else {
203                 // none of the above, just add the mail to the list
204                 ret.append(token);
205             }
206         }
207         return ret.toString();
208     }
209 
210     /**
211      * TODO use UserManager. Will be fixed with MAGNOLIA-1947 / MAGNOLIA-1948
212      * @return
213      * @throws RepositoryException
214      */
215     protected static Collection<Content> getAllUserNodes() throws RepositoryException {
216         HierarchyManager hm = MgnlContext.getSystemContext().getHierarchyManager(ContentRepository.USERS);
217         Collection<Content> users = hm.getContent(Realm.REALM_ADMIN).getChildren(ItemType.USER);
218         users.addAll(hm.getContent(Realm.REALM_SYSTEM).getChildren(ItemType.USER));
219         return users;
220     }
221 
222     protected static  String getUserMail(User user) {
223         return user.getProperty("email");
224     }
225 
226     public static String getParameter(Map<String, String> param, String name, String defaultValue) {
227 
228         if(param != null && param.containsKey(name)) {
229           return param.get(name);
230         } else {
231             return defaultValue;
232         }
233     }
234 
235     public static void logMail(Map params, String loggerName) {
236         Iterator i = params.entrySet().iterator();
237         StringBuffer buf = new StringBuffer();
238         while (i.hasNext()) {
239             Entry pairs = (Entry) i.next();
240             buf.append(" " + pairs.getKey() + " : " + pairs.getValue()
241                     + ",");
242         }
243         org.apache.log4j.Logger.getLogger(loggerName).log(LoggingLevel.MAIL_TRAIL,
244                 StringUtils.remove(StringUtils.chomp(buf.toString(), ","), System.getProperty("line.separator")));
245     }
246 
247 }