support for wildcard like base content-type mappings in media_type table.
[mir.git] / source / mircoders / servlet / ServletModuleOpenIndy.java
index eaedd49..ba005bc 100755 (executable)
@@ -1,8 +1,11 @@
 package mircoders.servlet;
 
 import java.io.*;
+import java.lang.*;
 import java.sql.*;
 import java.util.*;
+import java.net.*;
+import java.lang.reflect.*;
 import javax.servlet.*;
 import javax.servlet.http.*;
 
@@ -15,6 +18,7 @@ import mir.module.*;
 import mir.misc.*;
 import mir.entity.*;
 import mir.storage.*;
+import mir.media.*;
 
 import mircoders.entity.*;
 import mircoders.storage.*;
@@ -33,10 +37,14 @@ import mircoders.producer.*;
 public class ServletModuleOpenIndy extends ServletModule
 {
 
-  private String          commentFormTemplate, commentFormDoneTemplate;
-  private String          postingFormTemplate, postingFormDoneTemplate;
-  private ModuleContent   contentModule;
-  private ModuleImages     imageModule;
+  private String        commentFormTemplate, commentFormDoneTemplate,
+                        commentFormDupeTemplate;
+  private String        postingFormTemplate, postingFormDoneTemplate,
+                        postingFormDupeTemplate;
+  private ModuleContent contentModule;
+  private ModuleImages  imageModule;
+  private ModuleTopics  themenModule;
+  private String        directOp ="yes";
 
   // Singelton / Kontruktor
   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
@@ -44,14 +52,17 @@ public class ServletModuleOpenIndy extends ServletModule
 
   private ServletModuleOpenIndy() {
     try {
-      theLog = Logfile.getInstance(Configuration.getProperty("Home") + Configuration.getProperty("ServletModule.OpenIndy.Logfile"));
-      commentFormTemplate = Configuration.getProperty("ServletModule.OpenIndy.CommentTemplate");
-      commentFormDoneTemplate = Configuration.getProperty("ServletModule.OpenIndy.CommentDoneTemplate");
-      postingFormTemplate = Configuration.getProperty("ServletModule.OpenIndy.PostingTemplate");
-      postingFormDoneTemplate = Configuration.getProperty("ServletModule.OpenIndy.PostingDoneTemplate");
-
+      theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
+      commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
+      commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
+      commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
+      postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
+      postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
+      postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
+      directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
       mainModule = new ModuleComment(DatabaseComment.getInstance());
       contentModule = new ModuleContent(DatabaseContent.getInstance());
+      themenModule = new ModuleTopics(DatabaseTopics.getInstance());
       imageModule = new ModuleImages(DatabaseImages.getInstance());
       defaultAction="addposting";
     }
@@ -91,16 +102,30 @@ public class ServletModuleOpenIndy extends ServletModule
       // ok, collecting data from form
       try {
         HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
+       
+        //no html in comments(for now)
+        for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
+            String k=(String)i.next();
+            String v=(String)withValues.get(k);
+            
+            withValues.put(k,StringUtil.removeHTMLTags(v));
+        }
         withValues.put("is_published","1");
 
         // inserting into database
         String id = mainModule.add(withValues);
-
+        theLog.printDebugInfo("id: "+id);
+        //insert was not successfull
+        if(id==null){
+          deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
+        }
+        
         // producing new page
         new ProducerContent().handle(null, null, true, false, aid);
 
         // sync the server
         int exitValue = Helper.rsync();
+        theLog.printDebugInfo("rsync:"+exitValue);
 
         // redirecting to url
         // should implement back to article
@@ -119,15 +144,35 @@ public class ServletModuleOpenIndy extends ServletModule
    *  Method for delivering the form-Page for open posting
    */
 
-  public void addposting(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
-  {
+  public void addposting(HttpServletRequest req, HttpServletResponse res)
+    throws ServletModuleException {
     SimpleHash mergeData = new SimpleHash();
+    String numOfMedia = req.getParameter("medianum");
+    if(numOfMedia==null||numOfMedia.equals("")){
+      numOfMedia="1";
+    }
+    
+    int mediaNum = Integer.parseInt(numOfMedia);
+    SimpleList mediaFields = new SimpleList();
+    for(int i =0; i<mediaNum;i++){
+      Integer mNum = new Integer(i+1);
+      mediaFields.add(mNum.toString());
+    }
+    mergeData.put("medianum",numOfMedia);
+    mergeData.put("mediafields",mediaFields);
+    
+    
     /** @todo popups missing */
     try{
-      mergeData.put("languagePopUpData",DatabaseLanguage.getInstance().getPopupData());
+      SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
+      mergeData.put("languagePopUpData", popUpData );
+      mergeData.put("themenPopupData", themenModule.getTopicsAsSimpleList());
     } catch (Exception e) {
-      theLog.printError("languagePopUpData failed");
-    }
+      theLog.printError("languagePopUpData or getTopicslist failed "
+                        +e.toString());
+      throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
+    } 
+      
     deliver(req, res, mergeData, postingFormTemplate);
   }
 
@@ -137,92 +182,258 @@ public class ServletModuleOpenIndy extends ServletModule
    */
 
   public void insposting(HttpServletRequest req, HttpServletResponse res)
-    throws ServletModuleException
+    throws ServletModuleException, ServletModuleUserException
   {
     SimpleHash mergeData = new SimpleHash();
+    boolean setMedia=false;
+               boolean setTopic = false;
 
     try {
-
       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
+          
       HashMap withValues = mp.getParameters();
-      byte[] mediaData=mp.getMedia();
-      String fileName=mp.getFilename();
-      
-      theLog.printDebugInfo("ContentType: "+mp.getContentType());
-      
-      // if op contains imagedata
-      String mediaId=null;
-      if (mediaData!=null && fileName!=null) {
-        HashMap mediaValues = new HashMap();
-        mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
-        mediaValues.put("to_publisher", "1"); // op user
-        mediaValues.put("to_media_folder", "7"); // op media_folder
-        mediaValues.put("is_produced", "0");
-        mediaValues.put("is_published","1");
 
-        String mediaTitle=(String)withValues.get("media_title");
-        if (mediaTitle==null)
-          mediaTitle = (String)withValues.get("title");
-        mediaValues.put("title",mediaTitle);
-
-        if (fileName.toLowerCase().endsWith("rm")) {
-          // this is video !!
-          //theLog.printDebugInfo("--GOT VIDEO");
-          EntityVideo entVideo = new EntityVideo(DatabaseVideos.getInstance());
-          entVideo.setValues(mediaValues);
-          mediaId = entVideo.insert();
-          entVideo.setVideoData(mediaData);
-        }
-        else if (fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".gif")) {
-          // this is image !!
-          mediaId = imageModule.add(mediaValues);
-          EntityImage entImage = (EntityImage)imageModule.getById(mediaId);
-
-          int fileType = -1;
-          if (fileName.toLowerCase().endsWith(".jpg")) fileType=0;
-          if (fileName.toLowerCase().endsWith(".gif")) fileType=1;
-          if (fileType>=0) {
-            entImage.setImage(mediaData, fileType);
-            withValues.put("to_media",mediaId);
-          }
-          else
-            theLog.printDebugInfo("Wrong file uploaded!" + fileName);
+      if ((((String)withValues.get("title")).length() == 0) ||
+          (((String)withValues.get("description")).length() == 0) ||
+          (((String)withValues.get("content_data")).length() == 0))
+            throw new ServletModuleUserException("Missing field");
+      
+      // call the routines that escape html
+
+      for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
+        String k=(String)i.next();
+        String v=(String)withValues.get(k);
+        
+        if (k.equals("content_data")){
+          //this doesn't quite work yet, so for now, all html goes
+          //withValues.put(k,StringUtil.approveHTMLTags(v));
+          //withValues.put(k,StringUtil.removeHTMLTags(v));
+        } else {
+          withValues.put(k,StringUtil.removeHTMLTags(v));
         }
+        
       }
 
       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
       withValues.put("is_produced", "0");
-      // op-articles are immediatly published
-      withValues.put("is_published","1");
+      // op-articles are not immediatly published
+      // we don't know that all is good yet (media, title is present, etc..)
+      withValues.put("is_published","0");
+      // if op direct article-type == newswire
+      if (directOp.equals("yes")) withValues.put("to_article_type","1");
+      
       // owner is openposting user
       withValues.put("to_publisher","1");
       if (withValues.get("creator").toString().equals(""))
         withValues.put("creator","Anonym");
 
       // inserting  content into database
-      String id = contentModule.add(withValues);
+      String cid = contentModule.add(withValues);
+      theLog.printDebugInfo("id: "+cid);
+      //insert was not successfull
+      if(cid==null){
+        //How do we know that it was not succesful cause of a
+        //dupe, what if it failed cause of "No space left on device"?
+        //Or is there something I am missing? Wouldn't it be better
+        //to have an explicit dupe check and then insert? I have no
+        //idea what I am talking about. this comment is in case
+        //I forget to explicitely ask. -mh
+        deliver(req, res, mergeData, postingFormDupeTemplate);
+      }
+
+      String[] to_topicsArr = mp.getParameterValues("to_topic");
+      
+                       if (to_topicsArr != null && to_topicsArr.length > 0) {
+        try{
+          DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
+          setTopic = true;
+        } catch (Exception e) {
+          theLog.printError("setting content_x_topic failed");
+          contentModule.deleteById(cid);
+          throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
+        } //end try
+      } //end if
+        
+      // if op contains uploaddata
+      String mediaId=null;
+      int i=1;
+      for(Iterator it = mp.requestList.iterator(); it.hasNext();){
+        MpRequest mpReq = (MpRequest)it.next();
+        String fileName = mpReq.getFilename();
+
+        //get the content-type from what the client browser
+        //sends us. (the "Oreilly method")
+        String contentType = mpReq.getContentType();
+
+        theLog.printInfo("FROM BROWSER: "+contentType);
+
+        //if the client browser sent us unknown (text/plain is default)
+        //or if we got application/octet-stream, it's possible that
+        //the browser is in error, better check against the file extension
+        if (contentType.equals("text/plain") ||
+            contentType.equals("application/octet-stream")) {
+            /**
+             * This is just a temporary way to get the content-type via
+             * the .extension , we could maybe use a magic method, by looking
+             * at the header (first few bytes) of the file. (like the file(1)
+             * command).
+             * The Oreilly method  relies on the content-type that the client
+             * browser sends and that sometimes is application-octet stream with
+             * broken/mis-configured browsers.
+             *
+             * The map file should be Mir/content-types.properties, it's the
+             * default Sun Java file with some additional entries that it did
+             * not have. So if you support a new media type you have to make
+             * sure that it is in this file -mh
+             */
+            contentType = FileUtil.guessContentTypeFromName(fileName);
+            if (contentType==null)
+                contentType = "text/plain"; // rfc1867 says this is the default
+        }
+        HashMap mediaValues = new HashMap();
 
+        theLog.printInfo("CONTENT TYPE IS: "+contentType);
+        
+        if (contentType.equals("text/plain") ||
+            contentType.equals("application/octet-stream")) {
+          throw new ServletModuleUserException("One or more files of unrecognized types");
+        }
+
+        String mediaTitle=(String)withValues.get("media_title"+i);
+        i++;
+
+        if (mediaTitle==null)
+            mediaTitle = (String)withValues.get("title");
+
+        mediaValues.put("title", mediaTitle);
+        mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
+        mediaValues.put("to_publisher", "1"); // op user
+        mediaValues.put("to_media_folder", "7"); // op media_folder
+        mediaValues.put("is_produced", "0");
+        mediaValues.put("is_published","0");
+
+        //the where clause to find the media_type entry
+        //from the content-type.
+        //we use the media type entry to lookup the
+        //media Handler/Storage classes
+        //String wc = " mime_type = '"+contentType+"'";
+
+        // @todo this should probably be moved to DatabaseMediaType -mh
+        String[] cTypeSplit = StringUtil.split(contentType, "/");
+        String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
+
+        DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
+        EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
+
+        String mediaTypeId = null;
+        MirMedia mediaHandler;
+        Database mediaStorage;
+        //if we found an entry matching the
+        //content-type int the table.
+        if (mediaTypesList.size() > 0) {
+          Entity mediaType = null;
+          
+          // find out if we an exact content-type match if so take it.
+          // otherwise just use the first one.
+          // @todo this should probably be moved to DatabaseMediaType -mh
+          for(int j=0;i<mediaTypesList.size();j++) {
+            if(contentType.equals(
+                            mediaTypesList.elementAt(j).getValue("mime_type")))
+              mediaType = mediaTypesList.elementAt(j);
+          }
+
+          if( mediaType == null )
+            mediaType = mediaTypesList.elementAt(0);
+                
+          //get the class names from the media_type table.
+          mediaTypeId = mediaType.getId();
+          try {
+            // ############### @todo: merge these and the getURL call into one
+            // getURL helper call that just takes the Entity as a parameter
+            // along with media_type
+            mediaHandler = MediaHelper.getHandler(mediaType);
+            mediaStorage = MediaHelper.getStorage(mediaType,
+                                                "mircoders.storage.Database");
+          } catch (MirMediaException e) {
+            theLog.printError("getting media handler failed: "+e.toString());
+            contentModule.deleteById(cid);
+            throw new ServletModuleException("getting media handler failed: "
+                                            +e.toString());
+          }
+
+          mediaValues.put("to_media_type",mediaTypeId);
+
+          //load the classes via reflection
+          String MediaId;
+          Entity mediaEnt = null;
+          try {
+            mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
+            mediaEnt.setStorage(mediaStorage);
+            mediaEnt.setValues(mediaValues);
+            mediaId = mediaEnt.insert();
+
+            //save and store the media data/metadata
+            mediaHandler.set(mpReq.getMedia(), mediaEnt,
+                            mediaType);
+
+            //were done with mpReq at this point, dereference it.
+            //as it contains mucho mem. -mh 01.10.2001
+            mpReq=null;
+              
+            //we got this far, associate the media to the article
+            mediaEnt.setValueForProperty("is_published","1");
+            mediaEnt.update();
+            new ProducerMedia().handle(null,null,false,false,mediaId);
+            DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
+          } catch (Exception e) {
+            theLog.printError("setting media failed: "+e.toString());
+            contentModule.deleteById(cid);
+            throw new ServletModuleException("setting media failed: "+e.toString());
+          }
+
+        } else {
+          contentModule.deleteById(cid);
+          theLog.printDebugInfo("Wrong file type uploaded!: " + fileName);
+          throw new ServletModuleUserException("One or more files of unrecognized types");
+        } // end if-else mediaTypesList.size() > 0
+          
+      } //end for Iterator...
+
+      //if we're here all is ok...
+      EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
+      contentEnt.setValueForProperty("is_published","1");
+      contentEnt.update();
+
+
+      //dereference mp. -mh
+      mp=null;
 
-      // producing new page
-      if(mediaId!=null){
-        new ProducerImages().handle(null, null, false, false, mediaId);
-      }
       // producing openpostinglist
       new ProducerOpenPosting().handle(null,null,false,false);
       // producing new page
-      new ProducerContent().handle(null, null, false, false,id);
-
+      new ProducerContent().handle(null, null, false, false,cid);
+      //if direct op producing startpage
+      if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
+      
+                       //produce the topicPages if set
+                       //should be more intelligent
+                       //if(setTopic==true) new ProducerTopics().handle(null,null);
+                       
       // sync the server
+      //should be configureable
       int exitValue = Helper.rsync();
+      theLog.printDebugInfo("rsync: "+exitValue);
 
     }
-    catch (IOException e) { throw new ServletModuleException(e.toString());}
-    catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
-    catch (ModuleException e) { throw new ServletModuleException(e.toString());}
+    catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
+    catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
+    catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
 
     deliver(req, res, mergeData, postingFormDoneTemplate);
   }
 
 }
 
+