multiple file-editable directories
[mir.git] / source / mircoders / servlet / ServletModuleFileEdit.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.File;
34 import java.io.FileReader;
35 import java.io.FileWriter;
36 import java.io.FilenameFilter;
37 import java.io.StringReader;
38 import java.io.StringWriter;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Locale;
42 import java.util.Map;
43 import java.util.Vector;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46
47 import mir.log.LoggerWrapper;
48 import mir.servlet.ServletModule;
49 import mir.servlet.ServletModuleExc;
50 import mir.servlet.ServletModuleFailure;
51 import mir.util.FileFunctions;
52 import mir.util.HTTPRequestParser;
53 import mir.util.StringRoutines;
54 import mir.util.URLBuilder;
55
56 /*
57  *  ServletModuleFileEdit -
58  *  Allows one to do a basic edit of a file in a directory specified
59  *  in the config file.
60  *
61  * @author $Author: zapata $
62  * @version $Revision: 1.11 $ $Date: 2003/04/28 00:44:06 $
63  *
64  */
65
66 public class ServletModuleFileEdit extends ServletModule
67 {
68   private static ServletModuleFileEdit instance = new ServletModuleFileEdit();
69   public static ServletModule getInstance() { return instance; }
70
71   private Map directories;
72   private List directoryNames;
73
74   private FilenameFilter dirFilter;
75
76   private class FileEditDirectory {
77     private String name;
78     private FileFunctions.RegExpFileFilter filter;
79     private File rootDirectory;
80     private boolean recursive;
81
82     public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) {
83       name = aName;
84       rootDirectory = new File(aRootDirectory);
85       filter = new FileFunctions.RegExpFileFilter(aFilter);
86       recursive = aRecursive;
87     }
88
89     public String getName() {
90       return name;
91     }
92
93     public FileFunctions.RegExpFileFilter getFilter() {
94       return filter;
95     }
96
97     public File getRootDirectory() {
98       return rootDirectory;
99     }
100
101     public boolean getRecursive() {
102       return recursive;
103     }
104   }
105
106   private ServletModuleFileEdit() {
107     super();
108
109     logger = new LoggerWrapper("ServletModule.FileEdit");
110
111     directories = new HashMap();
112     directoryNames = new Vector();
113
114     String settings[] = configuration.getStringArray("ServletModule.FileEdit.Configuration");
115 /*
116 ServletModule.FileEdit.FileDirectory=/pub/Dokumente/Indymedia/de-tech/Mir/produced
117 ServletModule.FileEdit.ExtFilter=.*\.inc$
118 ServletModule.FileEdit.Recursive=0
119 */
120
121     if (settings!=null) {
122       for (int i = 0; i < settings.length; i++) {
123         String setting = settings[i].trim();
124
125         if (setting.length() > 0) {
126           List parts = StringRoutines.splitString(setting, ":");
127           if (parts.size() != 4) {
128             logger.error("config error: " + settings[i] + ", 4 parts expected");
129           }
130           else {
131             String name = (String) parts.get(0);
132             String directory = (String) parts.get(1);
133             String filter = (String) parts.get(2);
134             String recursive = (String) parts.get(3);
135
136             directories.put(name, new FileEditDirectory(name, directory, filter,
137                 recursive.equals("1") || recursive.toLowerCase().equals("y")));
138             directoryNames.add(name);
139           }
140         }
141       }
142     }
143
144     dirFilter = new FileFunctions.DirectoryFilter();
145
146     templateListString =configuration.getString("ServletModule.FileEdit.ListTemplate");
147     templateObjektString =configuration.getString("ServletModule.FileEdit.ObjektTemplate");
148     templateConfirmString =configuration.getString("ServletModule.FileEdit.ConfirmTemplate");
149   }
150
151   public List getEntries() {
152     return directoryNames;
153   }
154
155   public FileEditDirectory getDirectory(HttpServletRequest aRequest) throws ServletModuleExc {
156     FileEditDirectory result = (FileEditDirectory) directories.get(aRequest.getParameter("entry"));
157     if (result == null)
158       throw new ServletModuleExc("Unknown entry: " + aRequest.getParameter("entry"));
159
160     return result;
161   }
162
163   public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
164   {
165     listSubDirectory(getDirectory(aRequest), "/", aRequest, aResponse);
166   }
167
168   public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
169   {
170     try {
171       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
172
173       String filename = requestParser.getParameter("filename");
174       String subDirectory = requestParser.getParameterWithDefault("subdirectory", "");
175
176       if (filename == null)
177         throw new ServletModuleExc("No filename  specified");
178
179       editFile(getDirectory(aRequest), filename, subDirectory, aRequest, aResponse);
180     }
181     catch (Throwable e) {
182       throw new ServletModuleFailure(e);
183     }
184   }
185
186   public void enter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
187   {
188     try {
189       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
190
191       String directoryName = requestParser.getParameter("directory");
192       String subDirectoryName = requestParser.getParameter("subdirectory");
193
194       if (directoryName==null | subDirectoryName==null)
195         throw new ServletModuleExc("No directory/subDirectory specified");
196
197       listSubDirectory(getDirectory(aRequest), subDirectoryName+File.separator+directoryName, aRequest, aResponse);
198     }
199     catch (Throwable e) {
200       throw new ServletModuleFailure(e);
201     }
202   }
203
204   public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
205   {
206     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
207     String filename = requestParser.getParameter("filename");
208     String subDirectory = requestParser.getParameter("subdirectory");
209     String text = requestParser.getParameter("text");
210     FileEditDirectory directory = getDirectory(aRequest);
211
212     try {
213       File f = new File(new File(directory.getRootDirectory(), subDirectory), filename);
214
215       if (validateDirectory(directory, f)) {
216         StringReader in = new StringReader(text);
217         FileWriter out = new FileWriter(f);
218
219         int c;
220         while ( (c = in.read()) != -1)
221           out.write(c);
222         in.close();
223         out.close();
224
225         editFile(directory, filename, subDirectory, aRequest, aResponse);
226       }
227     }
228     catch (Throwable e) {
229       throw new ServletModuleFailure(e);
230     }
231   }
232
233   public void listSubDirectory(FileEditDirectory aDirectory, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
234   {
235     try {
236       Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
237       File dir = new File(aDirectory.getRootDirectory(), aSubDirectory);
238
239       if (!validateDirectory(aDirectory, dir) || !dir.isDirectory()) {
240         dir = aDirectory.getRootDirectory();
241         aSubDirectory = "";
242       }
243
244       responseData.put("filelist", FileFunctions.getDirectoryContentsAsList(dir, aDirectory.getFilter()));
245
246       if (aDirectory.getRecursive()) {
247         List dirs = new Vector();
248         if (!dir.getCanonicalPath().equals(aDirectory.getRootDirectory().getCanonicalPath()))
249           responseData.put("updir", new File(aSubDirectory).getParent());
250
251         dirs.addAll(FileFunctions.getDirectoryContentsAsList(dir, dirFilter));
252
253         responseData.put("dirlist", dirs);
254       }
255       else {
256         responseData.put("dirlist", null);
257         responseData.put("updir", null);
258       }
259
260       responseData.put("subdirectory", aSubDirectory);
261       responseData.put("entry", aDirectory.getName());
262
263       ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateListString);
264     }
265     catch (Throwable e) {
266       throw new ServletModuleFailure(e);
267     }
268   }
269
270   public void editFile(FileEditDirectory aDirectory, String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
271   {
272     try {
273       File f = new File(new File(aDirectory.getRootDirectory(), aSubDirectory), aFileName);
274
275       if (!validateDirectory(aDirectory, f) || f.isDirectory() || !validateFile(aDirectory, f)) {
276         listSubDirectory(aDirectory, "", aRequest, aResponse);
277       }
278       else {
279         Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
280         URLBuilder urlBuilder = new URLBuilder();
281
282         urlBuilder.setValue("module", "FileEdit");
283         urlBuilder.setValue("do", "enter");
284         urlBuilder.setValue("entry", aDirectory.getName());
285         urlBuilder.setValue("directory", "");
286         urlBuilder.setValue("subdirectory", aSubDirectory);
287
288         FileReader in = new FileReader(f);
289         StringWriter out = new StringWriter();
290
291         int c;
292         while ( (c = in.read()) != -1)
293           out.write(c);
294         in.close();
295         out.close();
296
297         responseData.put("entry", aDirectory.getName());
298         responseData.put("text", out.toString());
299         responseData.put("filename", aFileName);
300         responseData.put("subdirectory", aSubDirectory);
301         responseData.put("returnurl", urlBuilder.getQuery());
302
303         ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateObjektString);
304       }
305     }
306     catch (Throwable e) {
307       throw new ServletModuleFailure(e);
308     }
309   }
310
311   protected boolean validateDirectory(FileEditDirectory aDirectory, File aFile) {
312     try {
313       return (aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath()));
314     }
315     catch (Throwable t) {
316       return false;
317     }
318   }
319
320   protected boolean validateFile(FileEditDirectory aDirectory, File aFile) {
321     try {
322       return aDirectory.getFilter().accept(aFile.getParentFile(), aFile.getName());
323     }
324     catch (Throwable t) {
325       return false;
326     }
327   }
328 }