customizable administer links
[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.12 $ $Date: 2003/04/28 01:57:14 $
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     if (settings!=null) {
117       for (int i = 0; i < settings.length; i++) {
118         String setting = settings[i].trim();
119
120         if (setting.length() > 0) {
121           List parts = StringRoutines.splitString(setting, ":");
122           if (parts.size() != 4) {
123             logger.error("config error: " + settings[i] + ", 4 parts expected");
124           }
125           else {
126             String name = (String) parts.get(0);
127             String directory = (String) parts.get(1);
128             String filter = (String) parts.get(2);
129             String recursive = (String) parts.get(3);
130
131             directories.put(name, new FileEditDirectory(name, directory, filter,
132                 recursive.equals("1") || recursive.toLowerCase().equals("y")));
133             directoryNames.add(name);
134           }
135         }
136       }
137     }
138
139     dirFilter = new FileFunctions.DirectoryFilter();
140
141     templateListString =configuration.getString("ServletModule.FileEdit.ListTemplate");
142     templateObjektString =configuration.getString("ServletModule.FileEdit.ObjektTemplate");
143     templateConfirmString =configuration.getString("ServletModule.FileEdit.ConfirmTemplate");
144   }
145
146   public List getEntries() {
147     return directoryNames;
148   }
149
150   public FileEditDirectory getDirectory(HttpServletRequest aRequest) throws ServletModuleExc {
151     FileEditDirectory result = (FileEditDirectory) directories.get(aRequest.getParameter("entry"));
152     if (result == null)
153       throw new ServletModuleExc("Unknown entry: " + aRequest.getParameter("entry"));
154
155     return result;
156   }
157
158   public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
159   {
160     listSubDirectory(getDirectory(aRequest), "/", aRequest, aResponse);
161   }
162
163   public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
164   {
165     try {
166       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
167
168       String filename = requestParser.getParameter("filename");
169       String subDirectory = requestParser.getParameterWithDefault("subdirectory", "");
170
171       if (filename == null)
172         throw new ServletModuleExc("No filename  specified");
173
174       editFile(getDirectory(aRequest), filename, subDirectory, aRequest, aResponse);
175     }
176     catch (Throwable e) {
177       throw new ServletModuleFailure(e);
178     }
179   }
180
181   public void enter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
182   {
183     try {
184       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
185
186       String directoryName = requestParser.getParameter("directory");
187       String subDirectoryName = requestParser.getParameter("subdirectory");
188
189       if (directoryName==null | subDirectoryName==null)
190         throw new ServletModuleExc("No directory/subDirectory specified");
191
192       listSubDirectory(getDirectory(aRequest), subDirectoryName+File.separator+directoryName, aRequest, aResponse);
193     }
194     catch (Throwable e) {
195       throw new ServletModuleFailure(e);
196     }
197   }
198
199   public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
200   {
201     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
202     String filename = requestParser.getParameter("filename");
203     String subDirectory = requestParser.getParameter("subdirectory");
204     String text = requestParser.getParameter("text");
205     FileEditDirectory directory = getDirectory(aRequest);
206
207     try {
208       File f = new File(new File(directory.getRootDirectory(), subDirectory), filename);
209
210       if (validateDirectory(directory, f)) {
211         StringReader in = new StringReader(text);
212         FileWriter out = new FileWriter(f);
213
214         int c;
215         while ( (c = in.read()) != -1)
216           out.write(c);
217         in.close();
218         out.close();
219
220         editFile(directory, filename, subDirectory, aRequest, aResponse);
221       }
222     }
223     catch (Throwable e) {
224       throw new ServletModuleFailure(e);
225     }
226   }
227
228   public void listSubDirectory(FileEditDirectory aDirectory, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
229   {
230     try {
231       Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
232       File dir = new File(aDirectory.getRootDirectory(), aSubDirectory);
233
234       if (!validateDirectory(aDirectory, dir) || !dir.isDirectory()) {
235         dir = aDirectory.getRootDirectory();
236         aSubDirectory = "";
237       }
238
239       responseData.put("filelist", FileFunctions.getDirectoryContentsAsList(dir, aDirectory.getFilter()));
240
241       if (aDirectory.getRecursive()) {
242         List dirs = new Vector();
243         if (!dir.getCanonicalPath().equals(aDirectory.getRootDirectory().getCanonicalPath()))
244           responseData.put("updir", new File(aSubDirectory).getParent());
245
246         dirs.addAll(FileFunctions.getDirectoryContentsAsList(dir, dirFilter));
247
248         responseData.put("dirlist", dirs);
249       }
250       else {
251         responseData.put("dirlist", null);
252         responseData.put("updir", null);
253       }
254
255       responseData.put("subdirectory", aSubDirectory);
256       responseData.put("entry", aDirectory.getName());
257
258       ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateListString);
259     }
260     catch (Throwable e) {
261       throw new ServletModuleFailure(e);
262     }
263   }
264
265   public void editFile(FileEditDirectory aDirectory, String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
266   {
267     try {
268       File f = new File(new File(aDirectory.getRootDirectory(), aSubDirectory), aFileName);
269
270       if (!validateDirectory(aDirectory, f) || f.isDirectory() || !validateFile(aDirectory, f)) {
271         listSubDirectory(aDirectory, "", aRequest, aResponse);
272       }
273       else {
274         Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
275         URLBuilder urlBuilder = new URLBuilder();
276
277         urlBuilder.setValue("module", "FileEdit");
278         urlBuilder.setValue("do", "enter");
279         urlBuilder.setValue("entry", aDirectory.getName());
280         urlBuilder.setValue("directory", "");
281         urlBuilder.setValue("subdirectory", aSubDirectory);
282
283         FileReader in = new FileReader(f);
284         StringWriter out = new StringWriter();
285
286         int c;
287         while ( (c = in.read()) != -1)
288           out.write(c);
289         in.close();
290         out.close();
291
292         responseData.put("entry", aDirectory.getName());
293         responseData.put("text", out.toString());
294         responseData.put("filename", aFileName);
295         responseData.put("subdirectory", aSubDirectory);
296         responseData.put("returnurl", urlBuilder.getQuery());
297
298         ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateObjektString);
299       }
300     }
301     catch (Throwable e) {
302       throw new ServletModuleFailure(e);
303     }
304   }
305
306   protected boolean validateDirectory(FileEditDirectory aDirectory, File aFile) {
307     try {
308       return (aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath()));
309     }
310     catch (Throwable t) {
311       return false;
312     }
313   }
314
315   protected boolean validateFile(FileEditDirectory aDirectory, File aFile) {
316     try {
317       return aDirectory.getFilter().accept(aFile.getParentFile(), aFile.getName());
318     }
319     catch (Throwable t) {
320       return false;
321     }
322   }
323 }