1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
38
39
40
41 public class UtilsFile {
42
43 private static final Logger logger = LoggerFactory.getLogger(UtilsFile.class);
44
45
46
47
48
49
50
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
62 return name.replaceAll("\\/|\\/|\\||:|\\?|\\*|\"|<|>|\\p{Cntrl}", "_");
63 }
64
65
66
67
68
69
70
71
72 public static String sanitizeFolderName(final String folderName) {
73 if (folderName == null)
74 return null;
75 if (folderName.equals(""))
76 return "";
77
78
79 return folderName.replaceAll("\\.|\\/|\\/|\\||:|\\?|\\*|\"|<|>|\\p{Cntrl}", "_");
80 }
81
82
83
84
85
86
87
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
97
98
99
100
101
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
120
121
122
123
124 public static String forceSingleExtension(final String filename) {
125 return filename.replaceAll("\\.(?![^.]+$)", "_");
126 }
127
128
129
130
131
132
133
134
135 public static boolean isSingleExtension(final String filename) {
136 return filename.matches("[^\\.]+\\.[^\\.]+");
137 }
138
139
140
141
142
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
153
154
155
156
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 }