add in HTML tag mangling routines to protect the media metadata fields
[mir.git] / source / mircoders / media / MediaRequest.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 the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package mircoders.media;
33
34 import java.util.*;
35 import java.io.*;
36
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.ServletContext;
39
40 import com.oreilly.servlet.multipart.FilePart;
41
42 import mircoders.storage.DatabaseMediaType;
43 import mircoders.producer.ProducerMedia;
44 import mir.storage.StorageObjectException;
45 import mir.storage.Database;
46 import mir.module.ModuleException;
47 import mir.entity.*;
48 import mir.misc.*;
49 import mir.media.*;
50
51 /*
52  *  MediaRequest.java -
53  *    Takes an HTTPServletRequest from a mutltipart form and finds the files
54  *    uploaded via the com.oreilly.servlet.multipart package. Finally the
55  *    appropriate media objects are set.
56  *
57  * @author mh
58  * @version $Id: MediaRequest.java,v 1.11 2002/12/23 03:38:32 mh Exp $
59  *
60  */
61
62 public class MediaRequest implements FileHandler
63 {
64
65   String _user;
66   EntityList _returnList = new EntityList();
67   boolean _produce, _publish;
68
69   public MediaRequest(String user, boolean produce, boolean publish) {
70     _user = user;
71     _produce = produce;
72     _publish = publish;
73   }
74
75   public EntityList getEntityList() {
76     return _returnList;
77   }
78
79   /*
80    * parses the files in the uploaded media and creates media Entity's out of
81    * them.  Produces them if the "produce" argument is true. The "publish"
82    * parameter determines if it should publish per default in the case where no
83    * is_published parameter (from the upload form) is supplied. (for backwards
84    * compatibility.)
85    */
86   public void setFile(FilePart filePart, int fileNum, HashMap mediaValues)
87     throws FileHandlerException, FileHandlerUserException {
88
89     String mediaId=null;
90     MirMedia mediaHandler;
91     Database mediaStorage = null;
92     ProducerMedia mediaProducer = null;
93
94     try {
95       String fileName = filePart.getFileName();
96
97       //get the content-type from what the client browser
98       //sends us. (the "Oreilly method")
99       String contentType = filePart.getContentType();
100
101       //theLog.printInfo("FROM BROWSER: "+contentType);
102
103       //if the client browser sent us unknown (text/plain is default)
104       //or if we got application/octet-stream, it's possible that
105       //the browser is in error, better check against the file extension
106       if (contentType.equals("text/plain") ||
107           contentType.equals("application/octet-stream")) {
108         /**
109          * Fallback to finding the mime-type through the standard ServletApi
110          * ServletContext getMimeType() method.
111          *
112          * This is a way to get the content-type via the .extension,
113          * we could maybe use a magic method as an additional method of
114          * figuring out the content-type, by looking at the header (first
115          * few bytes) of the file. (like the file(1) command). We could
116          * also call the "file" command through Runtime. This is an
117          * option that I almost prefer as it is already implemented and
118          * exists with an up-to-date map on most modern Unix like systems.
119          * I haven't found a really nice implementation of the magic method
120          * in pure java yet.
121          *
122          * The first method we try thought is the "Oreilly method". It
123          * relies on the content-type that the client browser sends and
124          * that sometimes is application-octet stream with
125          * broken/mis-configured browsers.
126          *
127          * The map file we use for the extensions is the standard web-app
128          * deployment descriptor file (web.xml). See Mir's web.xml or see
129          * your Servlet containers (most likely Tomcat) documentation.
130          * So if you support a new media type you have to make sure that
131          * it is in this file -mh
132          */
133         ServletContext ctx =
134           (ServletContext)MirConfig.getPropAsObject("ServletContext");
135         contentType = ctx.getMimeType(fileName);
136         if (contentType==null)
137           contentType = "text/plain"; // rfc1867 says this is the default
138       }
139       //theLog.printInfo("CONTENT TYPE IS: "+contentType);
140
141       if (contentType.equals("text/plain") ||
142           contentType.equals("application/octet-stream")) {
143         _throwBadContentType(fileName, contentType);
144       }
145
146       // call the routines that escape html
147       for (Iterator i=mediaValues.keySet().iterator(); i.hasNext(); ){
148         String k=(String)i.next();
149         String v=(String)mediaValues.get(k);
150         
151         if (k.equals("description")) {
152           String tmp = StringUtil.deleteForbiddenTags(v);
153           mediaValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
154         } else {
155           //we don't want people fucking with the author/title, etc..
156           mediaValues.put(k,StringUtil.removeHTMLTags(v));
157         }
158         
159       }
160
161       String mediaTitle = (String)mediaValues.get("media_title"+fileNum);
162       if ( (mediaTitle == null) || (mediaTitle.length() == 0)) {
163         //  uncomment the next line and comment out the exception throw
164         //  if you'd rather just assign missing media titles automatically
165         //  mediaTitle="media item "+fileNum;
166         throw new FileHandlerUserException("Missing field: media title "+mediaTitle+fileNum);
167       }
168
169       // TODO: need to add all the extra fields that can be present in the
170       // admin upload form. -mh
171       mediaValues.put("title", mediaTitle);
172       mediaValues.put("date", StringUtil.date2webdbDate(
173                                                     new GregorianCalendar()));
174       mediaValues.put("to_publisher", _user);
175       //mediaValues.put("to_media_folder", "7"); // op media_folder
176       mediaValues.put("is_produced", "0");
177
178       // icky backwards compatibility code -mh
179       if (_publish == true) {
180         mediaValues.put("is_published", "1");
181       } else {
182         if (!mediaValues.containsKey("is_published"))
183           mediaValues.put("is_published", "0");
184       }
185
186       // @todo this should probably be moved to DatabaseMediaType -mh
187       String[] cTypeSplit = StringUtil.split(contentType, "/");
188       String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
189
190       DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
191       EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
192
193       String mediaTypeId = null;
194
195       //if we didn't find an entry matching the
196       //content-type int the table.
197       if (mediaTypesList.size() == 0) {
198        _throwBadContentType(fileName, contentType);
199       }
200
201       Entity mediaType = null;
202       Entity mediaType2 = null;
203
204       // find out if we an exact content-type match if so take it.
205       // otherwise try to match majortype/*
206       // @todo this should probably be moved to DatabaseMediaType -mh
207       for(int j=0;j<mediaTypesList.size();j++) {
208         if(contentType.equals(
209               mediaTypesList.elementAt(j).getValue("mime_type")))
210           mediaType = mediaTypesList.elementAt(j);
211         else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
212                   cTypeSplit[0]+"/*") )
213           mediaType2= mediaTypesList.elementAt(j);
214       }
215
216       if ( (mediaType == null) && (mediaType2 == null) ) {
217         _throwBadContentType(fileName, contentType);
218       } else if( (mediaType == null) && (mediaType2 != null) ) {
219         mediaType = mediaType2;
220       }
221
222       //get the class names from the media_type table.
223       mediaTypeId = mediaType.getId();
224       // ############### @todo: merge these and the getURL call into one
225       // getURL helper call that just takes the Entity as a parameter
226       // along with media_type
227       try {
228         mediaHandler = MediaHelper.getHandler(mediaType);
229         mediaStorage = MediaHelper.getStorage(mediaType,
230                                             "mircoders.storage.Database");
231       }
232       catch (MirMediaException e) {
233         throw new FileHandlerException (e.getMessage());
234       }
235       mediaValues.put("to_media_type",mediaTypeId);
236
237       //load the classes via reflection
238       String MediaId;
239       Entity mediaEnt = null;
240       try {
241         mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
242         if (_produce == true) {
243           Class prodCls = Class.forName("mircoders.producer.Producer"+
244                                         mediaType.getValue("tablename"));
245           mediaProducer = (ProducerMedia)prodCls.newInstance();
246         }
247       } catch (Exception e) {
248         throw new FileHandlerException("Error in MediaRequest: "+e.toString());
249       }
250
251       mediaEnt.setStorage(mediaStorage);
252       mediaEnt.setValues(mediaValues);
253       mediaId = mediaEnt.insert();
254
255       //save and store the media data/metadata
256       try {
257         mediaHandler.set(filePart.getInputStream(), mediaEnt, mediaType);
258       }
259       catch (MirMediaException e) {
260         e.printStackTrace(System.out);
261         throw new FileHandlerException(e.getMessage());
262       }
263       try {
264         if (_produce == true )
265           mediaProducer.handle(null, null, false, false, mediaId);
266       } catch (ModuleException e) {
267         // first try to delete it.. don't catch exception as we've already..
268         try { mediaStorage.delete(mediaId); } catch (Exception e2) {}
269         throw new FileHandlerException("error in MediaRequest: "+e.toString());
270       }
271
272       _returnList.add(mediaEnt);
273     }
274     catch (StorageObjectException e) {
275       // first try to delete it.. don't catch exception as we've already..
276       try { mediaStorage.delete(mediaId); } catch (Exception e2) {}
277       throw new FileHandlerException("error in MediaRequest: "+e.toString());
278     } //end try/catch block
279
280   } // method setFile()
281
282   private void _throwBadContentType (String fileName, String contentType)
283     throws FileHandlerUserException {
284
285     //theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
286       //                    +contentType);
287     throw new FileHandlerUserException("The file you uploaded is of the "
288         +"following mime-type: "+contentType
289         +", we do not support this mime-type. "
290         +"Error One or more files of unrecognized type. Sorry");
291   }
292
293 }
294