1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.servlet.filters.minifier;
24  
25  import com.liferay.portal.kernel.configuration.Filter;
26  import com.liferay.portal.kernel.log.Log;
27  import com.liferay.portal.kernel.log.LogFactoryUtil;
28  import com.liferay.portal.kernel.servlet.BrowserSniffer;
29  import com.liferay.portal.kernel.servlet.ServletContextUtil;
30  import com.liferay.portal.kernel.util.ArrayUtil;
31  import com.liferay.portal.kernel.util.ContentTypes;
32  import com.liferay.portal.kernel.util.FileUtil;
33  import com.liferay.portal.kernel.util.GetterUtil;
34  import com.liferay.portal.kernel.util.ParamUtil;
35  import com.liferay.portal.kernel.util.PropsKeys;
36  import com.liferay.portal.kernel.util.StringPool;
37  import com.liferay.portal.kernel.util.StringUtil;
38  import com.liferay.portal.kernel.util.Validator;
39  import com.liferay.portal.servlet.filters.BasePortalFilter;
40  import com.liferay.portal.servlet.filters.etag.ETagUtil;
41  import com.liferay.portal.util.MinifierUtil;
42  import com.liferay.portal.util.PropsUtil;
43  import com.liferay.portal.util.PropsValues;
44  import com.liferay.util.SystemProperties;
45  import com.liferay.util.servlet.ServletResponseUtil;
46  import com.liferay.util.servlet.filters.CacheResponse;
47  import com.liferay.util.servlet.filters.CacheResponseUtil;
48  
49  import java.io.File;
50  import java.io.IOException;
51  
52  import java.util.regex.Matcher;
53  import java.util.regex.Pattern;
54  
55  import javax.servlet.FilterChain;
56  import javax.servlet.FilterConfig;
57  import javax.servlet.ServletContext;
58  import javax.servlet.http.HttpServletRequest;
59  import javax.servlet.http.HttpServletResponse;
60  
61  /**
62   * <a href="MinifierFilter.java.html"><b><i>View Source</i></b></a>
63   *
64   * @author Brian Wing Shun Chan
65   */
66  public class MinifierFilter extends BasePortalFilter {
67  
68      public void init(FilterConfig filterConfig) {
69          super.init(filterConfig);
70  
71          _servletContext = filterConfig.getServletContext();
72          _servletContextName = GetterUtil.getString(
73              _servletContext.getServletContextName());
74  
75          if (Validator.isNull(_servletContextName)) {
76              _tempDir += "/portal";
77          }
78      }
79  
80      protected String aggregateCss(String dir, String content)
81          throws IOException {
82  
83          StringBuilder sb = new StringBuilder(content.length());
84  
85          int pos = 0;
86  
87          while (true) {
88              int x = content.indexOf(_CSS_IMPORT_BEGIN, pos);
89              int y = content.indexOf(
90                  _CSS_IMPORT_END, x + _CSS_IMPORT_BEGIN.length());
91  
92              if ((x == -1) || (y == -1)) {
93                  sb.append(content.substring(pos, content.length()));
94  
95                  break;
96              }
97              else {
98                  sb.append(content.substring(pos, x));
99  
100                 String importFile = content.substring(
101                     x + _CSS_IMPORT_BEGIN.length(), y);
102 
103                 String importContent = FileUtil.read(
104                     dir + StringPool.SLASH + importFile);
105 
106                 String importFilePath = StringPool.BLANK;
107 
108                 if (importFile.lastIndexOf(StringPool.SLASH) != -1) {
109                     importFilePath = StringPool.SLASH + importFile.substring(
110                         0, importFile.lastIndexOf(StringPool.SLASH) + 1);
111                 }
112 
113                 importContent = aggregateCss(
114                     dir + importFilePath, importContent);
115 
116                 int importDepth = StringUtil.count(
117                     importFile, StringPool.SLASH);
118 
119                 // LEP-7540
120 
121                 String relativePath = StringPool.BLANK;
122 
123                 for (int i = 0; i < importDepth; i++) {
124                     relativePath += "../";
125                 }
126 
127                 importContent = StringUtil.replace(
128                     importContent,
129                     new String[] {
130                         "url('" + relativePath,
131                         "url(\"" + relativePath,
132                         "url(" + relativePath
133                     },
134                     new String[] {
135                         "url('[$TEMP_RELATIVE_PATH$]",
136                         "url(\"[$TEMP_RELATIVE_PATH$]",
137                         "url([$TEMP_RELATIVE_PATH$]"
138                     });
139 
140                 importContent = StringUtil.replace(
141                     importContent, "[$TEMP_RELATIVE_PATH$]", StringPool.BLANK);
142 
143                 sb.append(importContent);
144 
145                 pos = y + _CSS_IMPORT_END.length();
146             }
147         }
148 
149         return sb.toString();
150     }
151 
152     protected String getMinifiedBundleContent(
153             HttpServletRequest request, HttpServletResponse response)
154         throws IOException {
155 
156         String minifierType = ParamUtil.getString(request, "minifierType");
157         String minifierBundleId = ParamUtil.getString(
158             request, "minifierBundleId");
159 
160         if (Validator.isNull(minifierType) ||
161             Validator.isNull(minifierBundleId) ||
162             !ArrayUtil.contains(
163                 PropsValues.JAVASCRIPT_BUNDLE_IDS, minifierBundleId)) {
164 
165             return null;
166         }
167 
168         String minifierBundleDir = PropsUtil.get(
169             PropsKeys.JAVASCRIPT_BUNDLE_DIR, new Filter(minifierBundleId));
170 
171         String bundleDirRealPath = ServletContextUtil.getRealPath(
172             _servletContext, minifierBundleDir);
173 
174         if (bundleDirRealPath == null) {
175             return null;
176         }
177 
178         String cacheFileName = _tempDir + request.getRequestURI();
179 
180         String queryString = request.getQueryString();
181 
182         if (queryString != null) {
183             cacheFileName += _QUESTION_SEPARATOR + queryString;
184         }
185 
186         String[] fileNames = PropsUtil.getArray(minifierBundleId);
187 
188         File cacheFile = new File(cacheFileName);
189 
190         if (cacheFile.exists()) {
191             boolean staleCache = false;
192 
193             for (String fileName : fileNames) {
194                 File file = new File(
195                     bundleDirRealPath + StringPool.SLASH + fileName);
196 
197                 if (file.lastModified() > cacheFile.lastModified()) {
198                     staleCache = true;
199 
200                     break;
201                 }
202             }
203 
204             if (!staleCache) {
205                 response.setContentType(ContentTypes.TEXT_JAVASCRIPT);
206 
207                 return FileUtil.read(cacheFile);
208             }
209         }
210 
211         if (_log.isInfoEnabled()) {
212             _log.info("Minifying JavaScript bundle " + minifierBundleId);
213         }
214 
215         StringBuilder sb = new StringBuilder();
216 
217         for (String fileName : fileNames) {
218             String content = FileUtil.read(
219                 bundleDirRealPath + StringPool.SLASH + fileName);
220 
221             sb.append(content);
222             sb.append(StringPool.NEW_LINE);
223         }
224 
225         String minifiedContent = minifyJavaScript(sb.toString());
226 
227         response.setContentType(ContentTypes.TEXT_JAVASCRIPT);
228 
229         FileUtil.write(cacheFile, minifiedContent);
230 
231         return minifiedContent;
232     }
233 
234     protected String getMinifiedContent(
235             HttpServletRequest request, HttpServletResponse response,
236             FilterChain filterChain)
237         throws Exception {
238 
239         String minifierType = ParamUtil.getString(request, "minifierType");
240         String minifierBundleId = ParamUtil.getString(
241             request, "minifierBundleId");
242         String minifierBundleDir = ParamUtil.getString(
243             request, "minifierBundleDir");
244 
245         if (Validator.isNull(minifierType) ||
246             Validator.isNotNull(minifierBundleId) ||
247             Validator.isNotNull(minifierBundleDir)) {
248 
249             return null;
250         }
251 
252         String requestURI = request.getRequestURI();
253 
254         String requestPath = requestURI;
255 
256         String contextPath = request.getContextPath();
257 
258         if (!contextPath.equals(StringPool.SLASH)) {
259             requestPath = requestPath.substring(contextPath.length());
260         }
261 
262         String realPath = ServletContextUtil.getRealPath(
263             _servletContext, requestPath);
264 
265         if (realPath == null) {
266             return null;
267         }
268 
269         realPath = StringUtil.replace(
270             realPath, StringPool.BACK_SLASH, StringPool.SLASH);
271 
272         File file = new File(realPath);
273 
274         if (!file.exists()) {
275             return null;
276         }
277 
278         String minifiedContent = null;
279 
280         String cacheCommonFileName = _tempDir + requestURI;
281 
282         String queryString = request.getQueryString();
283 
284         if (queryString != null) {
285             cacheCommonFileName += _QUESTION_SEPARATOR + queryString;
286         }
287 
288         File cacheContentTypeFile = new File(
289             cacheCommonFileName + "_E_CONTENT_TYPE");
290         File cacheDataFile = new File(cacheCommonFileName + "_E_DATA");
291 
292         if ((cacheDataFile.exists()) &&
293             (cacheDataFile.lastModified() >= file.lastModified())) {
294 
295             minifiedContent = FileUtil.read(cacheDataFile);
296 
297             if (cacheContentTypeFile.exists()) {
298                 String contentType = FileUtil.read(cacheContentTypeFile);
299 
300                 response.setContentType(contentType);
301             }
302         }
303         else {
304             if (realPath.endsWith(_CSS_EXTENSION)) {
305                 if (_log.isInfoEnabled()) {
306                     _log.info("Minifying CSS " + file);
307                 }
308 
309                 minifiedContent = minifyCss(request, file);
310 
311                 response.setContentType(ContentTypes.TEXT_CSS);
312 
313                 FileUtil.write(cacheContentTypeFile, ContentTypes.TEXT_CSS);
314             }
315             else if (realPath.endsWith(_JAVASCRIPT_EXTENSION)) {
316                 if (_log.isInfoEnabled()) {
317                     _log.info("Minifying JavaScript " + file);
318                 }
319 
320                 minifiedContent = minifyJavaScript(file);
321 
322                 response.setContentType(ContentTypes.TEXT_JAVASCRIPT);
323 
324                 FileUtil.write(
325                     cacheContentTypeFile, ContentTypes.TEXT_JAVASCRIPT);
326             }
327             else if (realPath.endsWith(_JSP_EXTENSION)) {
328                 if (_log.isInfoEnabled()) {
329                     _log.info("Minifying JSP " + file);
330                 }
331 
332                 CacheResponse cacheResponse = new CacheResponse(
333                     response, StringPool.UTF8);
334 
335                 processFilter(
336                     MinifierFilter.class, request, cacheResponse, filterChain);
337 
338                 CacheResponseUtil.addHeaders(
339                     response, cacheResponse.getHeaders());
340 
341                 response.setContentType(cacheResponse.getContentType());
342 
343                 minifiedContent = new String(
344                     cacheResponse.getData(), StringPool.UTF8);
345 
346                 if (minifierType.equals("css")) {
347                     minifiedContent = minifyCss(request, minifiedContent);
348                 }
349                 else if (minifierType.equals("js")) {
350                     minifiedContent = minifyJavaScript(minifiedContent);
351                 }
352 
353                 FileUtil.write(
354                     cacheContentTypeFile, cacheResponse.getContentType());
355             }
356             else {
357                 return null;
358             }
359 
360             FileUtil.write(cacheDataFile, minifiedContent);
361         }
362 
363         return minifiedContent;
364     }
365 
366     protected String minifyCss(HttpServletRequest request, File file)
367         throws IOException {
368 
369         String content = FileUtil.read(file);
370 
371         content = aggregateCss(file.getParent(), content);
372 
373         return minifyCss(request, content);
374     }
375 
376     protected String minifyCss(HttpServletRequest request, String content) {
377         String browserId = ParamUtil.getString(request, "browserId");
378 
379         if (!browserId.equals(BrowserSniffer.BROWSER_ID_IE)) {
380             Matcher matcher = _pattern.matcher(content);
381 
382             content = matcher.replaceAll(StringPool.BLANK);
383         }
384 
385         return MinifierUtil.minifyCss(content);
386     }
387 
388     protected String minifyJavaScript(File file) throws IOException {
389         String content = FileUtil.read(file);
390 
391         return minifyJavaScript(content);
392     }
393 
394     protected String minifyJavaScript(String content) {
395         return MinifierUtil.minifyJavaScript(content);
396     }
397 
398     protected void processFilter(
399             HttpServletRequest request, HttpServletResponse response,
400             FilterChain filterChain)
401         throws Exception {
402 
403         String minifiedContent = getMinifiedContent(
404             request, response, filterChain);
405 
406         if (Validator.isNull(minifiedContent)) {
407             minifiedContent = getMinifiedBundleContent(request, response);
408         }
409 
410         if (Validator.isNull(minifiedContent)) {
411             processFilter(MinifierFilter.class, request, response, filterChain);
412         }
413         else {
414             if (!ETagUtil.processETag(request, response, minifiedContent)) {
415                 ServletResponseUtil.write(response, minifiedContent);
416             }
417         }
418     }
419 
420     private static final String _CSS_IMPORT_BEGIN = "@import url(";
421 
422     private static final String _CSS_IMPORT_END = ");";
423 
424     private static final String _CSS_EXTENSION = ".css";
425 
426     private static final String _JAVASCRIPT_EXTENSION = ".js";
427 
428     private static final String _JSP_EXTENSION = ".jsp";
429 
430     private static final String _QUESTION_SEPARATOR = "_Q_";
431 
432     private static final String _TEMP_DIR =
433         SystemProperties.get(SystemProperties.TMP_DIR) + "/liferay/minifier";
434 
435     private static Log _log = LogFactoryUtil.getLog(MinifierFilter.class);
436 
437     private static Pattern _pattern = Pattern.compile(
438         "^(\\.ie|\\.js\\.ie)([^}]*)}", Pattern.MULTILINE);
439 
440     private ServletContext _servletContext;
441     private String _servletContextName;
442     private String _tempDir = _TEMP_DIR;
443 
444 }