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