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