001    /**
002     * Copyright (c) 2000-2011 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.SystemException;
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.ByteBufferServletResponse;
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.UnicodeProperties;
036    import com.liferay.portal.kernel.util.Validator;
037    import com.liferay.portal.model.Group;
038    import com.liferay.portal.model.Layout;
039    import com.liferay.portal.model.LayoutTypePortletConstants;
040    import com.liferay.portal.model.Portlet;
041    import com.liferay.portal.model.PortletConstants;
042    import com.liferay.portal.service.GroupLocalServiceUtil;
043    import com.liferay.portal.service.LayoutLocalServiceUtil;
044    import com.liferay.portal.service.PortletLocalServiceUtil;
045    import com.liferay.portal.servlet.filters.BasePortalFilter;
046    import com.liferay.portal.util.PortalInstances;
047    import com.liferay.portal.util.PortalUtil;
048    import com.liferay.portal.util.PropsValues;
049    import com.liferay.portal.util.WebKeys;
050    import com.liferay.util.servlet.filters.CacheResponseData;
051    import com.liferay.util.servlet.filters.CacheResponseUtil;
052    
053    import javax.servlet.FilterChain;
054    import javax.servlet.FilterConfig;
055    import javax.servlet.http.HttpServletRequest;
056    import javax.servlet.http.HttpServletResponse;
057    import javax.servlet.http.HttpSession;
058    
059    /**
060     * @author Alexander Chow
061     * @author Javier de Ros
062     * @author Raymond Augé
063     */
064    public class CacheFilter extends BasePortalFilter {
065    
066            public static final String SKIP_FILTER = CacheFilter.class + "SKIP_FILTER";
067    
068            @Override
069            public void init(FilterConfig filterConfig) {
070                    super.init(filterConfig);
071    
072                    _pattern = GetterUtil.getInteger(
073                            filterConfig.getInitParameter("pattern"));
074    
075                    if ((_pattern != _PATTERN_FRIENDLY) &&
076                            (_pattern != _PATTERN_LAYOUT) &&
077                            (_pattern != _PATTERN_RESOURCE)) {
078    
079                            _log.error("Cache pattern is invalid");
080                    }
081            }
082    
083            @Override
084            public boolean isFilterEnabled(
085                    HttpServletRequest request, HttpServletResponse response) {
086    
087                    if (isCacheableRequest(request) && !isInclude(request) &&
088                            !isAlreadyFiltered(request)) {
089    
090                            return true;
091                    }
092                    else {
093                            return false;
094                    }
095            }
096    
097            protected String getCacheKey(HttpServletRequest request) {
098                    StringBundler sb = new StringBundler(13);
099    
100                    // Url
101    
102                    sb.append(HttpUtil.getProtocol(request));
103                    sb.append(Http.PROTOCOL_DELIMITER);
104                    sb.append(request.getContextPath());
105                    sb.append(request.getServletPath());
106                    sb.append(request.getPathInfo());
107                    sb.append(StringPool.QUESTION);
108                    sb.append(request.getQueryString());
109    
110                    // Language
111    
112                    sb.append(StringPool.POUND);
113    
114                    String languageId = (String)request.getAttribute(
115                            WebKeys.I18N_LANGUAGE_ID);
116    
117                    if (Validator.isNull(languageId)) {
118                            languageId = LanguageUtil.getLanguageId(request);
119                    }
120    
121                    sb.append(languageId);
122    
123                    // User agent
124    
125                    String userAgent = GetterUtil.getString(
126                            request.getHeader(HttpHeaders.USER_AGENT));
127    
128                    sb.append(StringPool.POUND);
129                    sb.append(userAgent.toLowerCase().hashCode());
130    
131                    // Gzip compression
132    
133                    sb.append(StringPool.POUND);
134                    sb.append(BrowserSnifferUtil.acceptsGzip(request));
135    
136                    return sb.toString().trim().toUpperCase();
137            }
138    
139            protected long getPlid(
140                    long companyId, String pathInfo, String servletPath, long defaultPlid) {
141    
142                    if (_pattern == _PATTERN_LAYOUT) {
143                            return defaultPlid;
144                    }
145    
146                    if (Validator.isNull(pathInfo) ||
147                            !pathInfo.startsWith(StringPool.SLASH)) {
148    
149                            return 0;
150                    }
151    
152                    // Group friendly URL
153    
154                    String friendlyURL = null;
155    
156                    int pos = pathInfo.indexOf(CharPool.SLASH, 1);
157    
158                    if (pos != -1) {
159                            friendlyURL = pathInfo.substring(0, pos);
160                    }
161                    else {
162                            if (pathInfo.length() > 1) {
163                                    friendlyURL = pathInfo.substring(0, pathInfo.length());
164                            }
165                    }
166    
167                    if (Validator.isNull(friendlyURL)) {
168                            return 0;
169                    }
170    
171                    long groupId = 0;
172                    boolean privateLayout = false;
173    
174                    try {
175                            Group group = GroupLocalServiceUtil.getFriendlyURLGroup(
176                                    companyId, friendlyURL);
177    
178                            groupId = group.getGroupId();
179    
180                            if (servletPath.startsWith(
181                                            PropsValues.
182                                                    LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING) ||
183                                    servletPath.startsWith(
184                                            PropsValues.
185                                                    LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING)) {
186    
187                                    privateLayout = true;
188                            }
189                            else if (servletPath.startsWith(
190                                                    PropsValues.
191                                                            LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING)) {
192    
193                                    privateLayout = false;
194                            }
195                    }
196                    catch (NoSuchLayoutException nsle) {
197                            if (_log.isWarnEnabled()) {
198                                    _log.warn(nsle);
199                            }
200                    }
201                    catch (Exception e) {
202                            if (_log.isWarnEnabled()) {
203                                    _log.error(e);
204                            }
205    
206                            return 0;
207                    }
208    
209                    // Layout friendly URL
210    
211                    friendlyURL = null;
212    
213                    if ((pos != -1) && ((pos + 1) != pathInfo.length())) {
214                            friendlyURL = pathInfo.substring(pos, pathInfo.length());
215                    }
216    
217                    if (Validator.isNull(friendlyURL)) {
218                            return 0;
219                    }
220    
221                    // If there is no layout path take the first from the group or user
222    
223                    try {
224                            Layout layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
225                                    groupId, privateLayout, friendlyURL);
226    
227                            return layout.getPlid();
228                    }
229                    catch (NoSuchLayoutException nsle) {
230                            _log.warn(nsle);
231    
232                            return 0;
233                    }
234                    catch (Exception e) {
235                            _log.error(e);
236    
237                            return 0;
238                    }
239            }
240    
241            protected boolean isAlreadyFiltered(HttpServletRequest request) {
242                    if (request.getAttribute(SKIP_FILTER) != null) {
243                            return true;
244                    }
245                    else {
246                            return false;
247                    }
248            }
249    
250            protected boolean isCacheableColumn(long companyId, String columnSettings)
251                    throws SystemException {
252    
253                    String[] portletIds = StringUtil.split(columnSettings);
254    
255                    for (String portletId : portletIds) {
256                            portletId = PortletConstants.getRootPortletId(portletId);
257    
258                            Portlet portlet = PortletLocalServiceUtil.getPortletById(
259                                    companyId, portletId);
260    
261                            if (!portlet.isLayoutCacheable()) {
262                                    return false;
263                            }
264                    }
265    
266                    return true;
267            }
268    
269            protected boolean isCacheableData(
270                    long companyId, HttpServletRequest request) {
271    
272                    try {
273                            if (_pattern == _PATTERN_RESOURCE) {
274                                    return true;
275                            }
276    
277                            long plid = getPlid(
278                                    companyId, request.getPathInfo(), request.getServletPath(),
279                                    ParamUtil.getLong(request, "p_l_id"));
280    
281                            if (plid <= 0) {
282                                    return false;
283                            }
284    
285                            Layout layout = LayoutLocalServiceUtil.getLayout(plid);
286    
287                            if (!layout.isTypePortlet()) {
288                                    return false;
289                            }
290    
291                            UnicodeProperties properties = layout.getTypeSettingsProperties();
292    
293                            for (int i = 0; i < 10; i++) {
294                                    String columnId = "column-" + i;
295    
296                                    String settings = properties.getProperty(
297                                            columnId, StringPool.BLANK);
298    
299                                    if (!isCacheableColumn(companyId, settings)) {
300                                            return false;
301                                    }
302                            }
303    
304                            String columnIdsString = properties.get(
305                                    LayoutTypePortletConstants.NESTED_COLUMN_IDS);
306    
307                            if (columnIdsString != null) {
308                                    String[] columnIds = StringUtil.split(columnIdsString);
309    
310                                    for (String columnId : columnIds) {
311                                            String settings = properties.getProperty(
312                                                    columnId, StringPool.BLANK);
313    
314                                            if (!isCacheableColumn(companyId, settings)) {
315                                                    return false;
316                                            }
317                                    }
318                            }
319    
320                            return true;
321                    }
322                    catch (Exception e) {
323                            return false;
324                    }
325            }
326    
327            protected boolean isCacheableRequest(HttpServletRequest request) {
328                    String portletId = ParamUtil.getString(request, "p_p_id");
329    
330                    if (Validator.isNotNull(portletId)) {
331                            return false;
332                    }
333    
334                    if ((_pattern == _PATTERN_FRIENDLY) || (_pattern == _PATTERN_LAYOUT)) {
335                            long userId = PortalUtil.getUserId(request);
336                            String remoteUser = request.getRemoteUser();
337    
338                            if ((userId > 0) || Validator.isNotNull(remoteUser)) {
339                                    return false;
340                            }
341                    }
342    
343                    if (_pattern == _PATTERN_LAYOUT) {
344                            String plid = ParamUtil.getString(request, "p_l_id");
345    
346                            if (Validator.isNull(plid)) {
347                                    return false;
348                            }
349                    }
350    
351                    return true;
352            }
353    
354            protected boolean isCacheableResponse(
355                    ByteBufferServletResponse byteBufferResponse) {
356    
357                    if ((byteBufferResponse.getStatus() == HttpServletResponse.SC_OK) &&
358                            (byteBufferResponse.getBufferSize() <
359                                    PropsValues.CACHE_CONTENT_THRESHOLD_SIZE)) {
360    
361                            return true;
362                    }
363                    else {
364                            return false;
365                    }
366            }
367    
368            protected boolean isInclude(HttpServletRequest request) {
369                    String uri = (String)request.getAttribute(
370                            JavaConstants.JAVAX_SERVLET_INCLUDE_REQUEST_URI);
371    
372                    if (uri == null) {
373                            return false;
374                    }
375                    else {
376                            return true;
377                    }
378            }
379    
380            @Override
381            protected void processFilter(
382                            HttpServletRequest request, HttpServletResponse response,
383                            FilterChain filterChain)
384                    throws Exception {
385    
386                    request.setAttribute(SKIP_FILTER, Boolean.TRUE);
387    
388                    String key = getCacheKey(request);
389    
390                    long companyId = PortalInstances.getCompanyId(request);
391    
392                    CacheResponseData cacheResponseData = CacheUtil.getCacheResponseData(
393                            companyId, key);
394    
395                    if (cacheResponseData == null) {
396                            if (!isCacheableData(companyId, request)) {
397                                    if (_log.isDebugEnabled()) {
398                                            _log.debug("Request is not cacheable " + key);
399                                    }
400    
401                                    processFilter(
402                                            CacheFilter.class, request, response, filterChain);
403    
404                                    return;
405                            }
406    
407                            if (_log.isInfoEnabled()) {
408                                    _log.info("Caching request " + key);
409                            }
410    
411                            ByteBufferServletResponse byteBufferResponse =
412                                    new ByteBufferServletResponse(response);
413    
414                            processFilter(
415                                    CacheFilter.class, request, byteBufferResponse, filterChain);
416    
417                            cacheResponseData = new CacheResponseData(byteBufferResponse);
418    
419                            LastPath lastPath = (LastPath)request.getAttribute(
420                                    WebKeys.LAST_PATH);
421    
422                            if (lastPath != null) {
423                                    cacheResponseData.setAttribute(WebKeys.LAST_PATH, lastPath);
424                            }
425    
426                            // Cache the result if and only if there is a result and the request
427                            // is cacheable. We have to test the cacheability of a request
428                            // twice because the user could have been authenticated after the
429                            // initial test.
430    
431                            String cacheControl = GetterUtil.getString(
432                                    byteBufferResponse.getHeader(HttpHeaders.CACHE_CONTROL));
433    
434                            if ((byteBufferResponse.getStatus() == HttpServletResponse.SC_OK) &&
435                                    !cacheControl.contains(HttpHeaders.PRAGMA_NO_CACHE_VALUE) &&
436                                    isCacheableRequest(request) &&
437                                    isCacheableResponse(byteBufferResponse)) {
438    
439                                    CacheUtil.putCacheResponseData(
440                                            companyId, key, cacheResponseData);
441                            }
442                    }
443                    else {
444                            LastPath lastPath = (LastPath)cacheResponseData.getAttribute(
445                                    WebKeys.LAST_PATH);
446    
447                            if (lastPath != null) {
448                                    HttpSession session = request.getSession();
449    
450                                    session.setAttribute(WebKeys.LAST_PATH, lastPath);
451                            }
452                    }
453    
454                    CacheResponseUtil.write(response, cacheResponseData);
455            }
456    
457            private static final int _PATTERN_FRIENDLY = 0;
458    
459            private static final int _PATTERN_LAYOUT = 1;
460    
461            private static final int _PATTERN_RESOURCE = 2;
462    
463            private static Log _log = LogFactoryUtil.getLog(CacheFilter.class);
464    
465            private int _pattern;
466    
467    }