View Javadoc

1   /*
2    * FCKeditor - The text editor for Internet - http://www.fckeditor.net
3    * Copyright (C) 2003-2008 Frederico Caldeira Knabben
4    * 
5    * == BEGIN LICENSE ==
6    * 
7    * Licensed under the terms of any of the following licenses at your
8    * choice:
9    * 
10   *  - GNU General Public License Version 2 or later (the "GPL")
11   *    http://www.gnu.org/licenses/gpl.html
12   * 
13   *  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
14   *    http://www.gnu.org/licenses/lgpl.html
15   * 
16   *  - Mozilla Public License Version 1.1 or later (the "MPL")
17   *    http://www.mozilla.org/MPL/MPL-1.1.html
18   * 
19   * == END LICENSE ==
20   */
21  package net.fckeditor.tool;
22  
23  import java.io.File;
24  import java.io.InputStream;
25  
26  import javax.servlet.http.HttpServletRequest;
27  
28  import org.apache.commons.io.FilenameUtils;
29  import org.devlib.schmidt.imageinfo.ImageInfo;
30  import org.slf4j.Logger;
31  import org.slf4j.LoggerFactory;
32  
33  import net.fckeditor.handlers.ConnectorHandler;
34  import net.fckeditor.handlers.ResourceTypeHandler;
35  
36  /**
37   * Some static helper methods in conjunction with files.
38   *
39   * @version $Id: UtilsFile.java 2151 2008-07-02 22:03:15Z mosipov $
40   */
41  public class UtilsFile {
42  	
43  	private static final Logger logger = LoggerFactory.getLogger(UtilsFile.class);
44  
45  	/**
46  	 * Do a cleanup of the file name to avoid possible problems.<br>
47  	 * The <code>forceSingleExtension<code> property will be respected!
48  	 * 
49  	 * @param fileName
50  	 * @return folder name where \ / | : ? * &quot; &lt; &gt; 'control chars' replaced by '_'
51  	 */
52      public static String sanitizeFileName(final String fileName) {
53      	if (fileName == null)
54      		return null;
55      	if (fileName.equals(""))
56      		return "";
57      
58      	String name = (ConnectorHandler.isForceSingleExtension()) ? UtilsFile.forceSingleExtension(fileName)
59      	        : fileName;
60      
61      	// Remove \ / | : ? * " < > with _
62      	return name.replaceAll("\\/|\\/|\\||:|\\?|\\*|\"|<|>|\\p{Cntrl}", "_");
63      }
64  
65  	/**
66  	 * Do a cleanup of the folder name to avoid possible problems.
67  	 * 
68  	 * @param folderName
69  	 * @return folder name where . \ / | : ? * &quot; &lt; &gt; 'control chars'
70  	 *         replaced by '_'
71  	 */
72      public static String sanitizeFolderName(final String folderName) {
73      	if (folderName == null)
74      		return null;
75      	if (folderName.equals(""))
76      		return "";
77      
78      	// Remove . \ / | : ? * " < > with _
79      	return folderName.replaceAll("\\.|\\/|\\/|\\||:|\\?|\\*|\"|<|>|\\p{Cntrl}", "_");
80      }
81  
82  	/**
83  	 * Checks if the underlying file of the InputStream is an image.
84  	 * 
85  	 * @param in An input stream
86  	 * @return <code>true</code> if the underlying file is an image else
87  	 *         <code>false</code>.
88  	 */
89  	public static boolean isImage(final InputStream in) {
90      	ImageInfo ii = new ImageInfo();
91      	ii.setInput(in);
92      	return ii.check();
93      }
94  
95  	/**
96  	 * Checks if a path corresponds to the rules defined <a
97  	 * href="http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Server_Side_Integration#File_Browser_Requests">here</a>.
98  	 * 
99  	 * @param path
100 	 * @return <code>true</code> if path corresponds to rules or
101 	 *         <code>false</code>.
102 	 */
103     public static boolean isValidPath(final String path) {
104     	if (Utils.isEmpty(path))
105     		return false;
106     	if (!path.startsWith("/"))
107     		return false;
108     	if (!path.endsWith("/"))
109     		return false;
110     	
111     	if (!path.equals(FilenameUtils.separatorsToUnix(FilenameUtils
112     			.normalize(path))))
113     		return false;
114     	
115     	return true;
116     }
117 
118 	/**
119 	 * Replaces all dots except the last one with underscores in a filename.
120 	 * 
121 	 * @param filename
122 	 * @return string with a single dot only
123 	 */
124     public static String forceSingleExtension(final String filename) {
125     	return filename.replaceAll("\\.(?![^.]+$)", "_");
126     }
127 
128 	/**
129      * Checks if a filename contains more than one dot.
130      * 
131      * @param filename
132      * @return <code>true</code> if filename contains severals dots else
133      *         <code>false</code>
134      */
135     public static boolean isSingleExtension(final String filename) {
136     	return filename.matches("[^\\.]+\\.[^\\.]+");
137     }
138     
139     /**
140 	 * Checks for a dir and creates it if it does not exist.
141 	 * 
142 	 * @param dir Directory to check/create.
143 	 */
144 	public static void checkDirAndCreate(File dir) {
145 		if (!dir.exists()) {
146 			dir.mkdirs();
147 			logger.debug("Dir '{}' successfully created", dir);
148 		}
149 	}
150 	
151 	/**
152 	 * Compose server-side response path.
153 	 * 
154 	 * @param request
155 	 * @param resourceType
156 	 * @return server-side path of <code>resourceType</code>.
157 	 */
158 	public static String constructServerSidePath(HttpServletRequest request,
159 			ResourceTypeHandler resourceType) {
160 		StringBuffer sb = new StringBuffer(ConnectorHandler
161 				.getUserFilesPath(request));
162 		sb.append(resourceType.getPath());
163 
164 		return sb.toString();
165 	}
166 
167 }