View Javadoc

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