added:
[mir.git] / source / mircoders / servlet / ServletModuleFileEdit.java
index 862fe6e..6543c11 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002  The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with the com.oreilly.servlet library, any library\r
- * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
- * the above that use the same license as the above), and distribute linked\r
- * combinations including the two.  You must obey the GNU General Public\r
- * License in all respects for all of the code used other than the above\r
- * mentioned libraries.  If you modify this file, you may extend this exception\r
- * to your version of the file, but you are not obligated to do so.  If you do\r
- * not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.servlet;\r
-\r
-import java.io.File;\r
-import java.io.FileReader;\r
-import java.io.FileWriter;\r
-import java.io.FilenameFilter;\r
-import java.io.StringReader;\r
-import java.io.StringWriter;\r
-import java.util.Arrays;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.log.LoggerWrapper;\r
-import mir.servlet.ServletModule;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mir.util.FileFunctions;\r
-import mir.util.HTTPRequestParser;\r
-import mir.util.URLBuilder;\r
-\r
-/*\r
- *  ServletModuleFileEdit -\r
- *  Allows one to do a basic edit of a file in a directory specified\r
- *  in the config file.\r
- *\r
- * @author $Author: zapata $\r
- * @version $Revision: 1.8 $ $Date: 2003/03/17 20:47:04 $\r
- *\r
- */\r
-\r
-public class ServletModuleFileEdit extends ServletModule\r
-{\r
-  private static ServletModuleFileEdit instance = new ServletModuleFileEdit();\r
-  public static ServletModule getInstance() { return instance; }\r
-\r
-  private File rootDirectory;\r
-  private FilenameFilter filter;\r
-  private FilenameFilter dirFilter;\r
-  private boolean recurse;\r
-\r
-  private ServletModuleFileEdit() {\r
-    super();\r
-\r
-    logger = new LoggerWrapper("ServletModule.FileEdit");\r
-\r
-    rootDirectory = new File(configuration.getString("ServletModule.FileEdit.FileDirectory"));\r
-    recurse = configuration.getString("ServletModule.FileEdit.Recursive", "").equals("1");\r
-\r
-    filter = new FileFunctions.RegExpFileFilter(configuration.getString("ServletModule.FileEdit.ExtFilter"));\r
-    dirFilter = new FileFunctions.DirectoryFilter();\r
-\r
-    templateListString =configuration.getString("ServletModule.FileEdit.ListTemplate");\r
-    templateObjektString =configuration.getString("ServletModule.FileEdit.ObjektTemplate");\r
-    templateConfirmString =configuration.getString("ServletModule.FileEdit.ConfirmTemplate");\r
-  }\r
-\r
-  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    listSubDirectory("/", aRequest, aResponse);\r
-  }\r
-\r
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      String filename = requestParser.getParameter("filename");\r
-      String subDirectory = requestParser.getParameterWithDefault("subdirectory", "");\r
-\r
-      if (filename == null)\r
-        throw new ServletModuleExc("No filename  specified");\r
-\r
-      editFile(filename, subDirectory, aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void enter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    try {\r
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
-      String directoryName = requestParser.getParameter("directory");\r
-      String subDirectoryName = requestParser.getParameter("subdirectory");\r
-\r
-      if (directoryName==null | subDirectoryName==null)\r
-        throw new ServletModuleExc("No directory/subDirectory specified");\r
-\r
-      listSubDirectory(subDirectoryName+File.separator+directoryName, aRequest, aResponse);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    String filename = aRequest.getParameter("filename");\r
-    String subDirectory = aRequest.getParameter("subdirectory");\r
-    String text = aRequest.getParameter("text");\r
-\r
-    try {\r
-      File f = new File(new File(rootDirectory, subDirectory), filename);\r
-\r
-      if (validateDirectory(f)) {\r
-        StringReader in = new StringReader(text);\r
-        FileWriter out = new FileWriter(f);\r
-\r
-        int c;\r
-        while ( (c = in.read()) != -1)\r
-          out.write(c);\r
-        in.close();\r
-        out.close();\r
-\r
-        editFile(filename, subDirectory, aRequest, aResponse);\r
-      }\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void listSubDirectory(String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    try {\r
-      Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));\r
-      File dir = new File(rootDirectory, aSubDirectory);\r
-\r
-      if (!validateDirectory(dir) || !dir.isDirectory()) {\r
-        dir = rootDirectory;\r
-        aSubDirectory = "";\r
-      }\r
-\r
-      responseData.put("filelist", Arrays.asList(dir.list(filter)));\r
-\r
-      if (recurse) {\r
-        List dirs = new Vector();\r
-        if (!dir.getCanonicalPath().equals(rootDirectory.getCanonicalPath()))\r
-          responseData.put("updir", new File(aSubDirectory).getParent());\r
-\r
-        dirs.addAll(Arrays.asList(dir.list(dirFilter)));\r
-\r
-        responseData.put("dirlist", dirs);\r
-      }\r
-      else {\r
-        responseData.put("dirlist", null);\r
-        responseData.put("updir", null);\r
-      }\r
-\r
-      responseData.put("subdirectory", aSubDirectory);\r
-\r
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateListString);\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  public void editFile(String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
-  {\r
-    try {\r
-      File f = new File(new File(rootDirectory, aSubDirectory), aFileName);\r
-\r
-      if (!validateDirectory(f) || f.isDirectory() || !validateFile(f)) {\r
-        listSubDirectory("", aRequest, aResponse);\r
-      }\r
-      else {\r
-        Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));\r
-        URLBuilder urlBuilder = new URLBuilder();\r
-\r
-        urlBuilder.setValue("module", "FileEdit");\r
-        urlBuilder.setValue("do", "enter");\r
-        urlBuilder.setValue("directory", "");\r
-        urlBuilder.setValue("subdirectory", aSubDirectory);\r
-\r
-        FileReader in = new FileReader(f);\r
-        StringWriter out = new StringWriter();\r
-\r
-        int c;\r
-        while ( (c = in.read()) != -1)\r
-          out.write(c);\r
-        in.close();\r
-        out.close();\r
-\r
-        responseData.put("text", out.toString());\r
-        responseData.put("filename", aFileName);\r
-        responseData.put("subdirectory", aSubDirectory);\r
-        responseData.put("returnurl", urlBuilder.getQuery());\r
-\r
-        ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateObjektString);\r
-      }\r
-    }\r
-    catch (Throwable e) {\r
-      throw new ServletModuleFailure(e);\r
-    }\r
-  }\r
-\r
-  protected boolean validateDirectory(File aFile) {\r
-    try {\r
-      return (aFile.getCanonicalPath().startsWith(rootDirectory.getCanonicalPath()));\r
-    }\r
-    catch (Throwable t) {\r
-      return false;\r
-    }\r
-  }\r
-\r
-  protected boolean validateFile(File aFile) {\r
-    try {\r
-      return filter.accept(aFile.getParentFile(), aFile.getName());\r
-    }\r
-    catch (Throwable t) {\r
-      return false;\r
-    }\r
-  }\r
-}\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * 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  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.util.*;
+
+/*
+ *  ServletModuleFileEdit -
+ *  Allows one to do a basic edit of a file in a directory specified
+ *  in the config file.
+ *
+ * @author $Author: zapata $
+ * @version $Revision: 1.13.2.14 $ $Date: 2006/12/25 20:10:23 $
+ *
+ */
+
+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);
+          }
+        }
+      }
+    }
+
+    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", "");
+
+      if (filename == null)
+        throw new ServletModuleExc("No filename  specified");
+
+      editFile(getDirectory(aRequest), filename, subDirectory, aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  public void enter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
+  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+      String directoryName = requestParser.getParameter("directory");
+      String subDirectoryName = requestParser.getParameter("subdirectory");
+
+      if (directoryName==null | subDirectoryName==null)
+        throw new ServletModuleExc("No directory/subDirectory specified");
+
+      listSubDirectory(getDirectory(aRequest), subDirectoryName+File.separator+directoryName, aRequest, aResponse);
+    }
+    catch (Throwable e) {
+      throw new ServletModuleFailure(e);
+    }
+  }
+
+  /**
+   * 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
+  {
+    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);
+
+        BufferedReader in = new BufferedReader(new FileReader(f));
+        StringWriter textout = new StringWriter();
+        BufferedWriter out = new BufferedWriter(textout);
+
+        // 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();
+
+        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;
+    }
+  }
+
+}