Gif icons for the External image handler dramatically improved
[mir.git] / source / mircoders / servlet / ServletModuleUploadedMedia.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30
31 package mircoders.servlet;
32
33 import java.io.InputStream;
34 import java.net.URLEncoder;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Vector;
40
41 import javax.servlet.ServletContext;
42 import javax.servlet.ServletOutputStream;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
45 import javax.servlet.http.HttpSession;
46
47 import mir.config.MirPropertiesConfiguration;
48 import mir.entity.Entity;
49 import mir.entity.EntityList;
50 import mir.log.LoggerWrapper;
51 import mir.media.MediaHelper;
52 import mir.media.MirMedia;
53 import mir.servlet.ServletModule;
54 import mir.servlet.ServletModuleExc;
55 import mir.servlet.ServletModuleFailure;
56 import mir.servlet.ServletModuleUserExc;
57 import mir.session.UploadedFile;
58 import mir.util.ExceptionFunctions;
59 import mir.util.HTTPParsedRequest;
60 import mircoders.entity.EntityComment;
61 import mircoders.entity.EntityContent;
62 import mircoders.entity.EntityUploadedMedia;
63 import mircoders.entity.EntityUsers;
64 import mircoders.media.MediaUploadProcessor;
65 import mircoders.module.*;
66 import mircoders.storage.DatabaseComment;
67 import mircoders.storage.DatabaseContent;
68 import mircoders.storage.DatabaseMediafolder;
69
70 import org.apache.commons.fileupload.FileItem;
71
72 import freemarker.template.SimpleHash;
73 import freemarker.template.SimpleList;
74
75 /*
76  *  ServletModuleBilder -
77  *  liefert HTML fuer Bilder
78  *
79  * @version $Id: ServletModuleUploadedMedia.java,v 1.28 2003/04/29 02:36:51 zapata Exp $
80  * @author RK, the mir-coders group
81  */
82
83 public abstract class ServletModuleUploadedMedia
84         extends mir.servlet.ServletModule {
85
86   //private static DatabaseRights dbRights;
87
88   public static ServletModule getInstance() {
89     return null;
90   }
91
92   public ServletModuleUploadedMedia() {
93     super();
94     logger = new LoggerWrapper("ServletModule.UploadedMedia");
95   }
96
97   public void insert(HttpServletRequest req, HttpServletResponse res)
98           throws ServletModuleExc, ServletModuleUserExc {
99     try {
100       HTTPParsedRequest parsedRequest = new HTTPParsedRequest(req,
101           configuration.getString("Mir.DefaultEncoding"),
102           configuration.getInt("MaxMediaUploadSize")*1024,
103           configuration.getString("TempDir"));
104
105       EntityUsers user = _getUser(req);
106       Map mediaValues = new HashMap();
107
108       mediaValues.put("to_publisher", _getUser(req).getId());
109
110       Iterator i = mainModule.getStorageObject().getFields().iterator();
111       while (i.hasNext()) {
112         String field = (String) i.next();
113         String value = parsedRequest.getParameter(field);
114         if (value!=null)
115           mediaValues.put(field, value);
116       }
117
118       List mediaList = new Vector();
119
120       i = parsedRequest.getFiles().iterator();
121       while (i.hasNext()) {
122         UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
123
124         String suffix = file.getFieldName().substring(5);
125         mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix));
126
127         mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
128       }
129
130       String articleid = parsedRequest.getParameter("articleid");
131       String commentid = parsedRequest.getParameter("commentid");
132
133       if (articleid!=null) {
134         EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid);
135
136         i=mediaList.iterator();
137
138         while (i.hasNext()) {
139           entContent.attach(((EntityUploadedMedia) i.next()).getId());
140         }
141
142         ((ServletModuleContent) ServletModuleContent.getInstance())._showObject(articleid, req, res);
143
144         return;
145       }
146
147       if (commentid!=null) {
148         EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(commentid);
149
150         i=mediaList.iterator();
151
152         while (i.hasNext()) {
153           comment.attach( ( (EntityUploadedMedia) i.next()).getId());
154         }
155
156         ((ServletModuleComment) ServletModuleComment.getInstance()).showComment(commentid, req, res);
157
158         return;
159       }
160
161       SimpleHash mergeData = new SimpleHash();
162       SimpleHash popups = new SimpleHash();
163       mergeData.put("contentlist", mir.generator.FreemarkerGenerator.makeAdapter(mediaList));
164
165       mergeData.put("count", Integer.toString(mediaList.size()));
166       mergeData.put("from", "1");
167       mergeData.put("to", Integer.toString(mediaList.size()));
168
169       //fetch the popups
170       popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
171       // raus damit
172       deliver(req, res, mergeData, popups, templateListString);
173     }
174     catch (Throwable t) {
175       Throwable cause = ExceptionFunctions.traceCauseException(t);
176
177       if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
178         throw new ServletModuleUserExc("media.error.unsupportedformat", new String[] {});
179       }
180       throw new ServletModuleFailure("ServletModuleUploadedMedia.insert: " + t.toString(), t);
181     }
182   }
183
184   public void update(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
185
186     try {
187       HTTPParsedRequest parsedRequest = new HTTPParsedRequest(req,
188           configuration.getString("Mir.DefaultEncoding"),
189           configuration.getInt("MaxMediaUploadSize")*1024,
190           configuration.getString("TempDir"));
191       EntityUsers user = _getUser(req);
192       Map mediaValues = new HashMap();
193
194       Iterator i = mainModule.getStorageObject().getFields().iterator();
195       while (i.hasNext()) {
196         String field = (String) i.next();
197         String value = parsedRequest.getParameter(field);
198         if (value!=null)
199           mediaValues.put(field, value);
200       }
201
202       mediaValues.put("to_publisher", user.getId());
203       mediaValues.put("is_produced", "0");
204       if (!mediaValues.containsKey("is_published"))
205         mediaValues.put("is_published", "0");
206
207       String id = mainModule.set(mediaValues);
208       logger.debug("update: media ID = " + id);
209       _edit(id, req, res);
210     }
211     catch (Throwable e) {
212       throw new ServletModuleFailure("upload -- exception " + e.toString(), e);
213     }
214
215   }
216
217
218   public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
219     // Parameter auswerten
220     SimpleHash mergeData = new SimpleHash();
221     SimpleHash popups = new SimpleHash();
222
223     String query_text = req.getParameter("query_text");
224     mergeData.put("query_text", query_text);
225     if (query_text != null) mergeData.put("query_text_encoded", URLEncoder.encode(query_text));
226     String query_field = req.getParameter("query_field");
227     mergeData.put("query_field", query_field);
228     String query_is_published = req.getParameter("query_is_published");
229     mergeData.put("query_is_published", query_is_published);
230     String query_media_folder = req.getParameter("query_media_folder");
231     mergeData.put("query_media_folder", query_media_folder);
232     String offset = req.getParameter("offset");
233     if (offset == null || offset.equals("")) offset = "0";
234     mergeData.put("offset", offset);
235
236     String order = req.getParameter("order");
237     if (order == null || order.equals("")) order = "webdb_lastchange desc";
238
239     // if in connection mode to content
240     mergeData.put("articleid", req.getParameter("articleid"));
241     mergeData.put("commentid", req.getParameter("commentid"));
242
243
244     // sql basteln
245     String whereClause = "";
246     boolean isFirst = true;
247     if (query_text != null && !query_text.equalsIgnoreCase("")) {
248       whereClause += "lower(" + query_field + ") like lower('%" + query_text + "%')";
249       isFirst = false;
250     }
251     if (query_is_published != null && !query_is_published.equals("")) {
252       if (isFirst == false) whereClause += " and ";
253       whereClause += "is_published='" + query_is_published + "'";
254       isFirst = false;
255     }
256     if (query_media_folder != null && !query_media_folder.equals("")) {
257       if (isFirst == false) whereClause += " and ";
258       whereClause += "to_media_folder='" + query_media_folder + "'";
259     }
260     //theLog.printDebugInfo("sql-whereclause: " + whereClause + " order: " + order + " offset: " + offset);
261
262     // fetch and deliver
263     try {
264       if (query_text != null || query_is_published != null || query_media_folder != null) {
265         EntityList theList = mainModule.getByWhereClause(whereClause, order, (new Integer(offset)).intValue(), 10);
266         if (theList != null) {
267           mergeData.put("contentlist", theList);
268           if (theList.getOrder() != null) {
269             mergeData.put("order", theList.getOrder());
270             mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder()));
271           }
272           mergeData.put("count", (new Integer(theList.getCount())).toString());
273           mergeData.put("from", (new Integer(theList.getFrom())).toString());
274           mergeData.put("to", (new Integer(theList.getTo())).toString());
275           if (theList.hasNextBatch())
276             mergeData.put("next", (new Integer(theList.getNextBatch())).toString());
277           if (theList.hasPrevBatch())
278             mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString());
279         }
280       }
281       popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
282
283       deliver(req, res, mergeData, popups, templateListString);
284     }
285     catch (Throwable e) {
286       throw new ServletModuleFailure(e);
287     }
288   }
289
290
291   public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
292     try {
293       SimpleHash mergeData = new SimpleHash();
294       SimpleHash popups = new SimpleHash();
295       String maxMedia = MirPropertiesConfiguration.instance().getString("ServletModule.OpenIndy.MaxMediaUploadItems");
296       String numOfMedia = req.getParameter("medianum");
297
298       mergeData.put("new", "1");
299       mergeData.put("articleid", req.getParameter("articleid"));
300       mergeData.put("commentid", req.getParameter("commentid"));
301
302       popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
303
304       if (numOfMedia==null || numOfMedia.equals("")) {
305         numOfMedia="1";
306       }
307       else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
308         numOfMedia = maxMedia;
309       }
310
311       int mediaNum = Integer.parseInt(numOfMedia);
312       SimpleList mediaFields = new SimpleList();
313       for(int i =0; i<mediaNum;i++){
314         Integer mNum = new Integer(i+1);
315         mediaFields.add(mNum.toString());
316       }
317       mergeData.put("medianum",numOfMedia);
318       mergeData.put("mediafields",mediaFields);
319       deliver(req, res, mergeData, popups, templateObjektString);
320     }
321     catch (Exception e) {
322       throw new ServletModuleFailure(e);
323     }
324   }
325
326   public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
327     String idParam = req.getParameter("id");
328     _edit(idParam, req, res);
329   }
330
331   private void _edit(String idParam, HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
332     if (idParam != null && !idParam.equals("")) {
333       try {
334         SimpleHash popups = new SimpleHash();
335         popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
336         deliver(req, res, mainModule.getById(idParam), popups,
337                 templateObjektString);
338       }
339       catch (Throwable e) {
340         throw new ServletModuleFailure(e);
341       }
342     }
343     else {
344       throw new ServletModuleExc("ServletmoduleUploadedMedia :: _edit without id");
345     }
346   }
347
348
349   /** @todo should be in ServletModule.java */
350   private EntityUsers _getUser(HttpServletRequest req) {
351     HttpSession session = req.getSession(false);
352     return (EntityUsers) session.getAttribute("login.uid");
353   }
354
355   public void getMedia(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
356     String idParam = req.getParameter("id");
357     if (idParam!=null && !idParam.equals("")) {
358       try {
359         EntityUploadedMedia ent = (EntityUploadedMedia)mainModule.getById(idParam);
360         Entity mediaType = ent.getMediaType();
361         MirMedia mediaHandler;
362
363         ServletContext ctx = MirPropertiesConfiguration.getContext();
364         String fName = ent.getId()+"."+mediaType.getValue("name");
365
366         mediaHandler = MediaHelper.getHandler(mediaType);
367         InputStream in = mediaHandler.getMedia(ent, mediaType);
368
369         res.setContentType(ctx.getMimeType(fName));
370         //important that before calling this res.getWriter was not called first
371         ServletOutputStream out = res.getOutputStream();
372
373         int read ;
374         byte[] buf = new byte[8 * 1024];
375         while((read = in.read(buf)) != -1) {
376           out.write(buf, 0, read);
377         }
378         in.close();
379         out.close();
380       }
381       catch (Throwable e) {
382         throw new ServletModuleFailure(e);
383       }
384     }
385     else logger.error("id not specified.");
386     // no exception allowed
387   }
388
389   public void getIcon(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
390   {
391     String idParam = req.getParameter("id");
392     if (idParam!=null && !idParam.equals("")) {
393       try {
394         EntityUploadedMedia ent = (EntityUploadedMedia) mainModule.getById(idParam);
395         Entity mediaType = ent.getMediaType();
396         MirMedia mediaHandler;
397
398         mediaHandler = MediaHelper.getHandler(mediaType);
399         InputStream in = mediaHandler.getIcon(ent);
400
401         if (in==null)
402           throw new ServletModuleExc("no icon available");
403
404         res.setContentType(mediaHandler.getIconMimeType(ent, mediaType));
405         //important that before calling this res.getWriter was not called first
406         ServletOutputStream out = res.getOutputStream();
407
408         int read ;
409         byte[] buf = new byte[8 * 1024];
410         while((read = in.read(buf)) != -1) {
411           out.write(buf, 0, read);
412         }
413         in.close();
414         out.close();
415       }
416
417       catch (Throwable e) {
418         throw new ServletModuleFailure(e);
419       }
420     }
421     else logger.error("getIcon: id not specified.");
422     // no exception allowed
423   }
424
425 }
426
427