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