View Javadoc

1   /**
2    * This file Copyright (c) 2003-2011 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.Map.Entry;
62  import java.util.Properties;
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                 getGroupMembersMails(manager, ret, groupName);
173             }
174             else if (token.startsWith(MailConstants.PREFIX_ROLE)) {
175                 final String roleName = StringUtils.removeStart(token, MailConstants.PREFIX_ROLE);
176                 try {
177                     Collection users = getAllUserNodes();
178                     Iterator iter = users.iterator();
179                     while(iter.hasNext()){
180                         Content userNode = ((Content) iter.next());
181                         User user = manager.getUser(userNode.getName());
182                         if (user.getRoles().contains(roleName)){
183                             ret.append(getUserMail(user));
184                             ret.append("\n");
185                         }
186                     }
187                 }
188                 catch (Exception e) {
189                     log.error("can not get user email info.");
190                 }
191             }
192             else {
193                 // none of the above, just add the mail to the list
194                 ret.append(token);
195             }
196         }
197         return ret.toString();
198     }
199 
200     protected static void getGroupMembersMails(final UserManager manager, StringBuffer ret, final String groupName) {
201         log.debug("group = {}", groupName);
202         try {
203             Collection users = getAllUserNodes();
204             Iterator iter = users.iterator();
205             while(iter.hasNext()){
206                 Content userNode = ((Content) iter.next());
207                 User user = manager.getUser(userNode.getName());
208                 if (user.getAllGroups().contains(groupName)) {
209                     String mail = getUserMail(user);
210                     log.debug("user {} will be notified using mail address {}.", user.getName(), mail);
211                     if (mail != null) {
212                         ret.append(mail);
213                         ret.append("\n");
214                     }
215                 }
216             }
217         }
218         catch (Exception e) {
219             log.error("can not get user email info.", e);
220         }
221         log.debug("found:" + ret.toString());
222     }
223 
224     /**
225      * TODO use UserManager. Will be fixed with MAGNOLIA-1947 / MAGNOLIA-1948
226      * @return
227      * @throws RepositoryException
228      */
229     protected static Collection<Content> getAllUserNodes() throws RepositoryException {
230         HierarchyManager hm = MgnlContext.getSystemContext().getHierarchyManager(ContentRepository.USERS);
231         Collection<Content> users = hm.getContent(Realm.REALM_ADMIN).getChildren(ItemType.USER);
232         users.addAll(hm.getContent(Realm.REALM_SYSTEM).getChildren(ItemType.USER));
233         return users;
234     }
235 
236     protected static  String getUserMail(User user) {
237         return user.getProperty("email");
238     }
239 
240     public static Object getParameter(Map<String, Object> param, String name, String defaultValue) {
241 
242         if(param != null && param.containsKey(name)) {
243             return param.get(name);
244         } else {
245             return defaultValue;
246         }
247     }
248 
249     public static void logMail(Map params, String loggerName) {
250         Iterator i = params.entrySet().iterator();
251         StringBuffer buf = new StringBuffer();
252         while (i.hasNext()) {
253             Entry pairs = (Entry) i.next();
254             buf.append(" " + pairs.getKey() + " : " + pairs.getValue()
255                     + ",");
256         }
257         org.apache.log4j.Logger.getLogger(loggerName).log(LoggingLevel.MAIL_TRAIL,
258                 StringUtils.remove(StringUtils.chomp(buf.toString(), ","), System.getProperty("line.separator")));
259     }
260 
261 }