added:
[mir.git] / source / mircoders / servlet / ServletModuleFileEdit.java
index c954ddc..6543c11 100755 (executable)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2001, 2002  The Mir-coders group
+ * Copyright (C) 2001, 2002 The Mir-coders group
  *
  * This file is part of Mir.
  *
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with the com.oreilly.servlet library, any library
- * licensed under the Apache Software License, The Sun (tm) Java Advanced
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of
- * the above that use the same license as the above), and distribute linked
- * combinations including the two.  You must obey the GNU General Public
- * License in all respects for all of the code used other than the above
- * mentioned libraries.  If you modify this file, you may extend this exception
- * to your version of the file, but you are not obligated to do so.  If you do
- * not wish to do so, delete this exception statement from your version.
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
  */
 
 package mircoders.servlet;
 
+import mir.servlet.AdminServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.util.FileRoutines;
+import mir.util.HTTPRequestParser;
+import mir.util.StringRoutines;
+import mir.util.URLBuilder;
+import mir.changetracker.ChangeType;
+import mircoders.global.MirGlobal;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 import java.io.*;
-import java.net.*;
-import javax.servlet.http.*;
-import javax.servlet.*;
-import freemarker.template.*;
-import mir.servlet.*;
-import mir.misc.*;
-import mir.misc.FileExtFilter;
+import java.util.*;
 
 /*
  *  ServletModuleFileEdit -
  *  Allows one to do a basic edit of a file in a directory specified
  *  in the config file.
  *
- * @author $Author: mh $
- * @version $Revision: 1.2 $ $Date: 2002/09/01 22:05:57 $
+ * @author $Author: zapata $
+ * @version $Revision: 1.13.2.14 $ $Date: 2006/12/25 20:10:23 $
  *
  */
 
-public class ServletModuleFileEdit extends ServletModule
-{
-
-       // Singelton / Kontruktor
-
-       private static ServletModuleFileEdit instance =
-                                                new ServletModuleFileEdit();
-       public static ServletModule getInstance() { return instance; }
-
-  private String _dirName;
-  private String _extName;
-
-       private ServletModuleFileEdit() {
-
-               theLog = Logfile.getInstance(
-        MirConfig.getPropWithHome("ServletModule.FileEdit.Logfile"));
-               _dirName = MirConfig.getProp("ServletModule.FileEdit.FileDirectory");
-               _extName = MirConfig.getProp("ServletModule.FileEdit.ExtFilter");
-
-               templateListString =
-      MirConfig.getProp("ServletModule.FileEdit.ListTemplate");
-               templateObjektString =
-      MirConfig.getProp("ServletModule.FileEdit.ObjektTemplate");
-               templateConfirmString =
-      MirConfig.getProp("ServletModule.FileEdit.ConfirmTemplate");
-       }
-
-       public void list(HttpServletRequest req, HttpServletResponse res)
-               throws ServletModuleException
-       {
-               // fetch and deliver
-               try {
-                       SimpleHash mergeData = new SimpleHash();
-                       String offset = req.getParameter("offset");
-                       if (offset==null || offset.equals("")) offset="0";
-                       mergeData.put("offset",offset);
-      File dir = new File(_dirName);
-      System.out.println("DIRNAME: "+_dirName);
-      FileExtFilter extFilter = new FileExtFilter(_extName);
-      String[] dirEntries = dir.list(extFilter);
-      SimpleList theList = new SimpleList();
-      for ( int i = 0; i < dirEntries.length; ++i ) {
-        System.out.println(" FILE: "+dirEntries[i]);
-        theList.add(dirEntries[i]);
+public class ServletModuleFileEdit extends AdminServletModule {
+  private Map directories;
+  private List directoryNames;
+
+  private FilenameFilter dirFilter;
+
+  public ServletModuleFileEdit() {
+    directories = new HashMap();
+    directoryNames = new ArrayList();
+
+    String settings[] =
+        getConfiguration().getStringArray("ServletModule.FileEdit.Configuration");
+
+    if (settings!=null) {
+      for (int i = 0; i < settings.length; i++) {
+        String setting = settings[i].trim();
+
+        if (setting.length() > 0) {
+          List parts = StringRoutines.splitStringWithEscape(setting, ':', '\\');
+          if (parts.size() != 4) {
+            getLogger().error("config error: " + settings[i] + ", 4 parts expected");
+          }
+          else {
+            String name = (String) parts.get(0);
+            String directory = (String) parts.get(1);
+            String filter = (String) parts.get(2);
+            String recursive = (String) parts.get(3);
+
+            directories.put(name, new FileEditDirectory(name, directory, filter,
+                "1".equals(recursive) || "y".equals(recursive.toLowerCase())));
+            directoryNames.add(name);
+          }
+        }
       }
-      mergeData.put("filelist",theList);
+    }
+
+    dirFilter = new FileRoutines.DirectoryFilter();
+  }
+
+  public List getEntries() {
+    return directoryNames;
+  }
+
+  public FileEditDirectory getDirectory(HttpServletRequest aRequest) throws ServletModuleExc {
+    FileEditDirectory result = (FileEditDirectory) directories.get(aRequest.getParameter("entry"));
+    if (result == null)
+      throw new ServletModuleExc("Unknown entry: " + aRequest.getParameter("entry"));
+
+    return result;
+  }
+
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    listSubDirectory(getDirectory(aRequest), "/", aRequest, aResponse);
+  }
+
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+      String filename = requestParser.getParameter("filename");
+      String subDirectory = requestParser.getParameterWithDefault("subdirectory", "");
 
-                       // raus damit
-                       HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req));
-               }
-               catch (IOException e) {throw new ServletModuleException(e.toString());}
-               catch (Exception e) {throw new ServletModuleException(e.toString());}
-       }
+      if (filename == null)
+        throw new ServletModuleExc("No filename  specified");
 
-  public void edit(HttpServletRequest req, HttpServletResponse res)
-    throws ServletModuleException
+      editFile(getDirectory(aRequest), filename, subDirectory, aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void enter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
   {
-    String filename = req.getParameter("filename");
-    if (filename == null) throw new ServletModuleException("No filename specified");
     try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
 
-      File f = new File(_dirName, filename);
-      FileReader in = new FileReader(f);
-      StringWriter out = new StringWriter();
+      String directoryName = requestParser.getParameter("directory");
+      String subDirectoryName = requestParser.getParameter("subdirectory");
 
-      int c;
-      while ((c = in.read()) != -1)
-        out.write(c);
-      in.close();
-      out.close();
-      SimpleHash withValues = new SimpleHash();
-      withValues.put("text", out.toString());
-      withValues.put("filename", filename);
+      if (directoryName==null | subDirectoryName==null)
+        throw new ServletModuleExc("No directory/subDirectory specified");
 
-        
-      deliver(req, res, withValues, null, templateObjektString);
-    } catch (Exception e) {
-      throw new ServletModuleException(e.toString());
+      listSubDirectory(getDirectory(aRequest), subDirectoryName+File.separator+directoryName, aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
     }
   }
 
-  public void update(HttpServletRequest req, HttpServletResponse res)
-    throws ServletModuleException
+  /**
+   * Called when an edited file is saved by the user
+   */
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+    String filename = requestParser.getParameter("filename");
+    String subDirectory = requestParser.getParameter("subdirectory");
+    String text =
+        StringRoutines.performRegularExpressionReplacement(
+            requestParser.getParameter("text"),
+            "\r\n",
+            System.getProperty("line.separator"));
+    FileEditDirectory directory = getDirectory(aRequest);
+
+    try {
+      File f = new File(new File(directory.getRootDirectory(), subDirectory), filename);
+
+      if (isDirectoryValid(directory, f)) {
+        FileWriter out = new FileWriter(f);
+        try {
+          out.write(text.toCharArray());
+        }
+        finally {
+          out.close();
+        }
+
+        logAdminUsage(aRequest, f.getAbsolutePath(), "object modified");
+
+        MirGlobal.getChangeEngine().getTracker().addChange(f.getCanonicalPath(), ChangeType.MODIFICATION);
+
+        editFile(directory, filename, subDirectory, aRequest, aResponse);
+      }
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void listSubDirectory(FileEditDirectory aDirectory, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
   {
-    String filename = req.getParameter("filename");
-    if (filename == null) throw new ServletModuleException("No filename specified");
     try {
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      File dir = new File(aDirectory.getRootDirectory(), aSubDirectory);
+
+      if (!isDirectoryValid(aDirectory, dir) || !dir.isDirectory()) {
+        dir = aDirectory.getRootDirectory();
+        aSubDirectory = "";
+      }
+
+      responseData.put("filelist", FileRoutines.getDirectoryContentsAsList(dir, aDirectory.getFilter()));
+
+      if (aDirectory.getRecursive()) {
+        List dirs = new ArrayList();
+        if (!dir.getCanonicalPath().equals(aDirectory.getRootDirectory().getCanonicalPath()))
+          responseData.put("updir", new File(aSubDirectory).getParent());
+
+        dirs.addAll(FileRoutines.getDirectoryContentsAsList(dir, dirFilter));
+
+        responseData.put("dirlist", dirs);
+      }
+      else {
+        responseData.put("dirlist", null);
+        responseData.put("updir", null);
+      }
+
+      responseData.put("subdirectory", aSubDirectory);
+      responseData.put("entry", aDirectory.getName());
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void editFile(FileEditDirectory aDirectory, String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+    try {
+      File f = new File(new File(aDirectory.getRootDirectory(), aSubDirectory), aFileName);
+
+      if (!isDirectoryValid(aDirectory, f) || f.isDirectory() || !isFileValid(aDirectory, f)) {
+        listSubDirectory(aDirectory, "", aRequest, aResponse);
+      }
+      else {
+        Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+        URLBuilder urlBuilder = new URLBuilder();
+
+        urlBuilder.setValue("module", "FileEdit");
+        urlBuilder.setValue("do", "enter");
+        urlBuilder.setValue("entry", aDirectory.getName());
+        urlBuilder.setValue("directory", "");
+        urlBuilder.setValue("subdirectory", aSubDirectory);
 
-      File f = new File(_dirName, filename);
-      StringReader in = new StringReader(req.getParameter("text"));
-      FileWriter out = new FileWriter(f);
+        BufferedReader in = new BufferedReader(new FileReader(f));
+        StringWriter textout = new StringWriter();
+        BufferedWriter out = new BufferedWriter(textout);
 
-      int c;
-      while ((c = in.read()) != -1)
-        out.write(c);
-      in.close();
-      out.close();
+        // TODO read array
+        char[] c = new char[4096];
+        int read;
+        while ((read=in.read(c)) != -1) {
+          out.write(c, 0, read);
+        }
+        in.close();
+        out.close();
 
-      edit(req, res);
-    } catch (Exception e) {
-      throw new ServletModuleException(e.toString());
+        responseData.put("entry", aDirectory.getName());
+        responseData.put("text", textout.toString());
+        responseData.put("filename", aFileName);
+        responseData.put("subdirectory", aSubDirectory);
+        responseData.put("returnurl", urlBuilder.getQuery());
+
+        ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
+      }
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
     }
   }
 
+  private boolean isDirectoryValid(FileEditDirectory aDirectory, File aFile) {
+    try {
+      return aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath());
+    }
+    catch (Throwable t) {
+      return false;
+    }
+  }
+
+  private boolean isFileValid(FileEditDirectory aDirectory, File aFile) {
+    try {
+      return aDirectory.getFilter().accept(aFile.getParentFile(), aFile.getName());
+    }
+    catch (Throwable t) {
+      return false;
+    }
+  }
+
+  private class FileEditDirectory {
+    private String name;
+    private FileRoutines.RegExpFileFilter filter;
+    private File rootDirectory;
+    private boolean recursive;
+
+    public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) {
+      name = aName;
+      rootDirectory = new File(aRootDirectory);
+      filter = new FileRoutines.RegExpFileFilter(aFilter);
+      recursive = aRecursive;
+    }
+
+    public String getName() {
+      return name;
+    }
+
+    public FileRoutines.RegExpFileFilter getFilter() {
+      return filter;
+    }
+
+    public File getRootDirectory() {
+      return rootDirectory;
+    }
+
+    public boolean getRecursive() {
+      return recursive;
+    }
+  }
 
 }