001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.servlet.filters.cache;
016    
017    import com.liferay.portal.NoSuchLayoutException;
018    import com.liferay.portal.kernel.exception.PortalException;
019    import com.liferay.portal.kernel.language.LanguageUtil;
020    import com.liferay.portal.kernel.log.Log;
021    import com.liferay.portal.kernel.log.LogFactoryUtil;
022    import com.liferay.portal.kernel.servlet.BrowserSnifferUtil;
023    import com.liferay.portal.kernel.servlet.BufferCacheServletResponse;
024    import com.liferay.portal.kernel.servlet.HttpHeaders;
025    import com.liferay.portal.kernel.struts.LastPath;
026    import com.liferay.portal.kernel.util.CharPool;
027    import com.liferay.portal.kernel.util.GetterUtil;
028    import com.liferay.portal.kernel.util.Http;
029    import com.liferay.portal.kernel.util.HttpUtil;
030    import com.liferay.portal.kernel.util.JavaConstants;
031    import com.liferay.portal.kernel.util.ParamUtil;
032    import com.liferay.portal.kernel.util.StringBundler;
033    import com.liferay.portal.kernel.util.StringPool;
034    import com.liferay.portal.kernel.util.StringUtil;
035    import com.liferay.portal.kernel.util.Validator;
036    import com.liferay.portal.model.Group;
037    import com.liferay.portal.model.Layout;
038    import com.liferay.portal.model.LayoutTypePortlet;
039    import com.liferay.portal.security.auth.AuthTokenUtil;
040    import com.liferay.portal.service.GroupLocalServiceUtil;
041    import com.liferay.portal.service.LayoutLocalServiceUtil;
042    import com.liferay.portal.servlet.filters.BasePortalFilter;
043    import com.liferay.portal.util.PortalInstances;
044    import com.liferay.portal.util.PortalUtil;
045    import com.liferay.portal.util.PropsValues;
046    import com.liferay.portal.util.WebKeys;
047    import com.liferay.util.servlet.filters.CacheResponseData;
048    import com.liferay.util.servlet.filters.CacheResponseUtil;
049    
050    import javax.servlet.FilterChain;
051    import javax.servlet.FilterConfig;
052    import javax.servlet.http.HttpServletRequest;
053    import javax.servlet.http.HttpServletResponse;
054    import javax.servlet.http.HttpSession;
055    
056    /**
057     * @author Alexander Chow
058     * @author Javier de Ros
059     * @author Raymond Aug??
060     */
061    public class CacheFilter extends BasePortalFilter {
062    
063            public static final String SKIP_FILTER = CacheFilter.class + "SKIP_FILTER";
064    
065            @Override
066            public void init(FilterConfig filterConfig) {
067                    super.init(filterConfig);
068    
069                    _pattern = GetterUtil.getInteger(
070                            filterConfig.getInitParameter("pattern"));
071    
072                    if ((_pattern != _PATTERN_FRIENDLY) &&
073                            (_pattern != _PATTERN_LAYOUT) &&
074                            (_pattern != _PATTERN_RESOURCE)) {
075    
076                            _log.error("Cache pattern is invalid");
077                    }
078            }
079    
080            @Override
081            public boolean isFilterEnabled(
082                    HttpServletRequest request, HttpServletResponse response) {
083    
084                    if (isCacheableRequest(request) && !isInclude(request) &&
085                            !isAlreadyFiltered(request)) {
086    
087                            return true;
088                    }
089                    else {
090                            return false;
091                    }
092            }
093    
094            protected String getCacheKey(HttpServletRequest request) {
095                    StringBundler sb = new StringBundler(13);
096    
097                    // Url
098    
099                    sb.append(HttpUtil.getProtocol(request));
100                    sb.append(Http.PROTOCOL_DELIMITER);
101    
102                    String url = PortalUtil.getCurrentCompleteURL(request);
103    
104                    sb.append(HttpUtil.getDomain(url));
105    
106                    sb.append(request.getContextPath());
107                    sb.append(request.getServletPath());
108                    sb.append(request.getPathInfo());
109                    sb.append(StringPool.QUESTION);
110    
111                    String queryString = request.getQueryString();
112    
113                    if (queryString == null) {
114                            queryString = (String)request.getAttribute(
115                                    JavaConstants.JAVAX_SERVLET_FORWARD_QUERY_STRING);
116    
117                            if (queryString == null) {
118                                    int pos = url.indexOf(CharPool.QUESTION);
119    
120                                    if (pos > -1) {
121                                            queryString = url.substring(pos + 1);
122                                    }
123                            }
124                    }
125    
126                    if (queryString != null) {
127                            sb.append(queryString);
128                    }
129    
130                    // Language
131    
132                    sb.append(StringPool.POUND);
133    
134                    String languageId = (String)request.getAttribute(
135                            WebKeys.I18N_LANGUAGE_ID);
136    
137                    if (Validator.isNull(languageId)) {
138                            languageId = LanguageUtil.getLanguageId(request);
139                    }
140    
141                    sb.append(languageId);
142    
143                    // User agent
144    
145                    String userAgent = GetterUtil.getString(
146                            request.getHeader(HttpHeaders.USER_AGENT));
147    
148                    sb.append(StringPool.POUND);
149                    sb.append(StringUtil.toLowerCase(userAgent).hashCode());
150    
151                    // Gzip compression
152    
153                    sb.append(StringPool.POUND);
154                    sb.append(BrowserSnifferUtil.acceptsGzip(request));
155    
156                    return StringUtil.toUpperCase(sb.toString().trim());
157            }
158    
159            protected long getPlid(
160                    long companyId, String pathInfo, String servletPath, long defaultPlid) {
161    
162                    if (_pattern == _PATTERN_LAYOUT) {
163                            return defaultPlid;
164                    }
165    
166                    if (Validator.isNull(pathInfo) ||
167                            !pathInfo.startsWith(StringPool.SLASH)) {
168    
169                            return 0;
170                    }
171    
172                    // Group friendly URL
173    
174                    String friendlyURL = null;
175    
176                    int pos = pathInfo.indexOf(CharPool.SLASH, 1);
177    
178                    if (pos != -1) {
179                            friendlyURL = pathInfo.substring(0, pos);
180                    }
181                    else if (pathInfo.length() > 1) {
182                            friendlyURL = pathInfo;
183                    }
184    
185                    if (Validator.isNull(friendlyURL)) {
186                            return 0;
187                    }
188    
189                    long groupId = 0;
190                    boolean privateLayout = false;
191    
192                    try {
193                            Group group = GroupLocalServiceUtil.getFriendlyURLGroup(
194                                    companyId, friendlyURL);
195    
196                            groupId = group.getGroupId();
197    
198                            if (servletPath.startsWith(
199                                            PropsValues.
200                                                    LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING) ||
201                                    servletPath.startsWith(
202                                            PropsValues.
203                                                    LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING)) {
204    
205                                    privateLayout = true;
206                            }
207                            else if (servletPath.startsWith(
208                                                    PropsValues.
209                                                            LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING)) {
210    
211                                    privateLayout = false;
212                            }
213                    }
214                    catch (NoSuchLayoutException nsle) {
215                            if (_log.isWarnEnabled()) {
216                                    _log.warn(nsle);
217                            }
218                    }
219                    catch (Exception e) {
220                            if (_log.isWarnEnabled()) {
221                                    _log.warn(e);
222                            }
223    
224                            return 0;
225                    }
226    
227                    // Layout friendly URL
228    
229                    friendlyURL = null;
230    
231                    if ((pos != -1) && ((pos + 1) != pathInfo.length())) {
232                            friendlyURL = pathInfo.substring(pos);
233                    }
234    
235                    if (Validator.isNull(friendlyURL)) {
236                            try {
237                                    long plid = LayoutLocalServiceUtil.getDefaultPlid(
238                                            groupId, privateLayout);
239    
240                                    return plid;
241                            }
242                            catch (Exception e) {
243                                    _log.warn(e);
244    
245                                    return 0;
246                            }
247                    }
248                    else if (friendlyURL.endsWith(StringPool.FORWARD_SLASH)) {
249                            friendlyURL = friendlyURL.substring(0, friendlyURL.length() - 1);
250                    }
251    
252                    // If there is no layout path take the first from the group or user
253    
254                    try {
255                            Layout layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
256                                    groupId, privateLayout, friendlyURL);
257    
258                            return layout.getPlid();
259                    }
260                    catch (NoSuchLayoutException nsle) {
261                            _log.warn(nsle);
262    
263                            return 0;
264                    }
265                    catch (Exception e) {
266                            _log.error(e);
267    
268                            return 0;
269                    }
270            }
271    
272            protected boolean isAlreadyFiltered(HttpServletRequest request) {
273                    if (request.getAttribute(SKIP_FILTER) != null) {
274                            return true;
275                    }
276                    else {
277                            return false;
278                    }
279            }
280    
281            protected boolean isCacheableData(
282                    long companyId, HttpServletRequest request) {
283    
284                    try {
285                            if (_pattern == _PATTERN_RESOURCE) {
286                                    return true;
287                            }
288    
289                            long plid = getPlid(
290                                    companyId, request.getPathInfo(), request.getServletPath(),
291                                    ParamUtil.getLong(request, "p_l_id"));
292    
293                            if (plid <= 0) {
294                                    return false;
295                            }
296    
297                            Layout layout = LayoutLocalServiceUtil.getLayout(plid);
298    
299                            if (!layout.isTypePortlet()) {
300                                    return false;
301                            }
302    
303                            LayoutTypePortlet layoutTypePortlet =
304                                    (LayoutTypePortlet)layout.getLayoutType();
305    
306                            return layoutTypePortlet.isCacheable();
307                    }
308                    catch (Exception e) {
309                            return false;
310                    }
311            }
312    
313            protected boolean isCacheableRequest(HttpServletRequest request) {
314                    String portletId = ParamUtil.getString(request, "p_p_id");
315    
316                    if (Validator.isNotNull(portletId)) {
317                            return false;
318                    }
319    
320                    if ((_pattern == _PATTERN_FRIENDLY) || (_pattern == _PATTERN_LAYOUT)) {
321                            long userId = PortalUtil.getUserId(request);
322                            String remoteUser = request.getRemoteUser();
323    
324                            if ((userId > 0) || Validator.isNotNull(remoteUser)) {
325                                    return false;
326                            }
327                    }
328    
329                    if (_pattern == _PATTERN_LAYOUT) {
330                            String plid = ParamUtil.getString(request, "p_l_id");
331    
332                            if (Validator.isNull(plid)) {
333                                    return false;
334                            }
335                    }
336    
337                    return true;
338            }
339    
340            protected boolean isCacheableResponse(
341                    BufferCacheServletResponse bufferCacheServletResponse) {
342    
343                    if ((bufferCacheServletResponse.getStatus() ==
344                                    HttpServletResponse.SC_OK) &&
345                            (bufferCacheServletResponse.getBufferSize() <
346                                    PropsValues.CACHE_CONTENT_THRESHOLD_SIZE)) {
347    
348                            return true;
349                    }
350                    else {
351                            return false;
352                    }
353            }
354    
355            protected boolean isInclude(HttpServletRequest request) {
356                    String uri = (String)request.getAttribute(
357                            JavaConstants.JAVAX_SERVLET_INCLUDE_REQUEST_URI);
358    
359                    if (uri == null) {
360                            return false;
361                    }
362                    else {
363                            return true;
364                    }
365            }
366    
367            @Override
368            protected void processFilter(
369                            HttpServletRequest request, HttpServletResponse response,
370                            FilterChain filterChain)
371                    throws Exception {
372    
373                    request.setAttribute(SKIP_FILTER, Boolean.TRUE);
374    
375                    String key = getCacheKey(request);
376    
377                    String pAuth = request.getParameter("p_auth");
378    
379                    if (Validator.isNotNull(pAuth)) {
380                            try {
381                                    AuthTokenUtil.checkCSRFToken(
382                                            request, CacheFilter.class.getName());
383                            }
384                            catch (PortalException pe) {
385                                    if (_log.isDebugEnabled()) {
386                                            _log.debug(
387                                                    "Request is not cacheable " + key +
388                                                            ", invalid token received");
389                                    }
390    
391                                    processFilter(
392                                            CacheFilter.class, request, response, filterChain);
393    
394                                    return;
395                            }
396    
397                            key = key.replace(StringUtil.toUpperCase(pAuth), "VALID");
398                    }
399    
400                    long companyId = PortalInstances.getCompanyId(request);
401    
402                    CacheResponseData cacheResponseData = CacheUtil.getCacheResponseData(
403                            companyId, key);
404    
405                    if ((cacheResponseData == null) || !cacheResponseData.isValid()) {
406                            if (!_isValidCache(cacheResponseData) ||
407                                    !isCacheableData(companyId, request)) {
408    
409                                    if (_log.isDebugEnabled()) {
410                                            _log.debug("Request is not cacheable " + key);
411                                    }
412    
413                                    if (cacheResponseData == null) {
414                                            if (_log.isInfoEnabled()) {
415                                                    _log.info("Caching request with invalid state " + key);
416                                            }
417    
418                                            CacheUtil.putCacheResponseData(
419                                                    companyId, key, new CacheResponseData());
420                                    }
421    
422                                    processFilter(
423                                            CacheFilter.class, request, response, filterChain);
424    
425                                    return;
426                            }
427    
428                            if (_log.isInfoEnabled()) {
429                                    _log.info("Caching request " + key);
430                            }
431    
432                            BufferCacheServletResponse bufferCacheServletResponse =
433                                    new BufferCacheServletResponse(response);
434    
435                            processFilter(
436                                    CacheFilter.class, request, bufferCacheServletResponse,
437                                    filterChain);
438    
439                            cacheResponseData = new CacheResponseData(
440                                    bufferCacheServletResponse);
441    
442                            LastPath lastPath = (LastPath)request.getAttribute(
443                                    WebKeys.LAST_PATH);
444    
445                            if (lastPath != null) {
446                                    cacheResponseData.setAttribute(WebKeys.LAST_PATH, lastPath);
447                            }
448    
449                            // Cache the result if and only if there is a result and the request
450                            // is cacheable. We have to test the cacheability of a request twice
451                            // because the user could have been authenticated after the initial
452                            // test.
453    
454                            String cacheControl = GetterUtil.getString(
455                                    bufferCacheServletResponse.getHeader(
456                                            HttpHeaders.CACHE_CONTROL));
457    
458                            if (isCacheableResponse(bufferCacheServletResponse) &&
459                                    !cacheControl.contains(HttpHeaders.PRAGMA_NO_CACHE_VALUE) &&
460                                    isCacheableRequest(request)) {
461    
462                                    CacheUtil.putCacheResponseData(
463                                            companyId, key, cacheResponseData);
464                            }
465                    }
466                    else {
467                            LastPath lastPath = (LastPath)cacheResponseData.getAttribute(
468                                    WebKeys.LAST_PATH);
469    
470                            if (lastPath != null) {
471                                    HttpSession session = request.getSession();
472    
473                                    session.setAttribute(WebKeys.LAST_PATH, lastPath);
474                            }
475                    }
476    
477                    CacheResponseUtil.write(response, cacheResponseData);
478            }
479    
480            private boolean _isValidCache(CacheResponseData cacheResponseData) {
481                    if ((cacheResponseData != null) && !cacheResponseData.isValid()) {
482                            return false;
483                    }
484    
485                    return true;
486            }
487    
488            private static final int _PATTERN_FRIENDLY = 0;
489    
490            private static final int _PATTERN_LAYOUT = 1;
491    
492            private static final int _PATTERN_RESOURCE = 2;
493    
494            private static Log _log = LogFactoryUtil.getLog(CacheFilter.class);
495    
496            private int _pattern;
497    
498    }