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