View Javadoc
1   /**
2    * This file Copyright (c) 2015-2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.resources;
35  
36  import info.magnolia.cms.core.AggregationState;
37  import info.magnolia.context.Context;
38  import info.magnolia.context.WebContext;
39  import info.magnolia.link.LinkUtil;
40  import info.magnolia.objectfactory.Components;
41  import info.magnolia.resourceloader.Resource;
42  import info.magnolia.resourceloader.ResourceOrigin;
43  import info.magnolia.templating.functions.TemplatingFunctions;
44  
45  import java.util.Optional;
46  import java.util.TimeZone;
47  import java.util.regex.Matcher;
48  import java.util.regex.Pattern;
49  
50  import javax.inject.Inject;
51  import javax.inject.Provider;
52  import javax.inject.Singleton;
53  
54  import org.apache.commons.lang3.StringUtils;
55  import org.apache.commons.lang3.time.FastDateFormat;
56  import org.slf4j.Logger;
57  import org.slf4j.LoggerFactory;
58  
59  /**
60   * A simple component that helps locating resources in {@link ResourceOrigin} and generate links to them. Specifically,
61   * it handles prefixing links with context path and the fingerprinting.
62   */
63  @Singleton
64  public class ResourceLinker {
65      private static final Logger log = LoggerFactory.getLogger(ResourceLinker.class);
66  
67      // Currently lenient, allowing both ~ and .
68      private static final Pattern CACHE_PATTERN = Pattern.compile("[~.]\\d{4}(-\\d{2}){5}-\\d{3}[~.]cache");
69  
70      private static final FastDateFormat TIME_STAMP_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd-HH-mm-ss-SSS", TimeZone.getTimeZone("GMT"));
71  
72      private final ResourceOrigin origin;
73      private final Provider<ResourcesModule> configuration;
74      private final Provider<Context> webContextProvider;
75  
76      @Inject
77      public ResourceLinker(ResourceOrigin origin, Provider<ResourcesModule> configuration, Provider<Context> webContextProvider) {
78          this.origin = origin;
79          this.configuration = configuration;
80          this.webContextProvider = webContextProvider;
81      }
82  
83      /**
84       * @deprecated since 2.6.1 - use {@link #ResourceLinker(ResourceOrigin, Provider, Provider)} instead.
85       */
86      @Deprecated
87      public ResourceLinker(ResourceOrigin origin, Provider<ResourcesModule> configuration, Provider<AggregationState> aggregationStateProvider, TemplatingFunctions templatingFunctions) {
88          this(origin, configuration, () -> Components.getComponent(Context.class));
89      }
90  
91      public String getServletMapping() {
92          return cleanDownloadPath() + "/*";
93      }
94  
95      /**
96       * Returns whatever's been configured as {@link ResourcesModule#downloadPath}, with a single leading slash and no leading slash.
97       */
98      protected String cleanDownloadPath() {
99          final String downloadPath = configuration.get().getDownloadPath();
100         return downloadPath.replaceFirst("^/*(.*?)/*$", "/$1");
101     }
102 
103     public String linkTo(String path, boolean addFingerPrint) {
104         if (LinkUtil.EXTERNAL_LINK_PATTERN.matcher(path).matches()) {
105             // TODO Client code should do this check, ideally. See e.g feature/better-resdef branch of magnolia-site (ResourceDefinition)
106             log.debug("Ignoring request to transform a link to {}, it's already an external link.", path);
107             return path;
108         }
109 
110         // Link prefix will be contextPath and site-prefix if any. The servlet will be matched because matching is done against AggState.currentURI. See info.magnolia.cms.filters.Mapping.findMatcher(javax.servlet.http.HttpServletRequest)
111         final StringBuilder sb = new StringBuilder();
112         getLinkPrefix().ifPresent(sb::append);
113 
114         final String servletMappingPrefix = cleanDownloadPath();
115 
116         // We support links configured with the (servlet mapping) prefix and without (one can configure just the path as in the resources app)
117         final String resourcePath;
118         if (path.startsWith(servletMappingPrefix)) {
119             resourcePath = path.substring(servletMappingPrefix.length());
120         } else {
121             resourcePath = path;
122         }
123 
124         final boolean isKnownResource = origin.hasPath(resourcePath);
125         if (isKnownResource) {
126             sb.append(servletMappingPrefix);
127             if (addFingerPrint) {
128                 final Resource resource = origin.getByPath(resourcePath);
129                 final String fingerPrint = fingerPrintFor(resource);
130                 final String ext = StringUtils.substringAfterLast(resourcePath, ".");
131                 final String withoutExt = StringUtils.substringBeforeLast(resourcePath, ".");
132                 sb.append(withoutExt).append("~").append(fingerPrint).append("~cache");
133                 // Add the dot only if the #ext is present.
134                 if (StringUtils.isNotBlank(ext)) {
135                     sb.append(".").append(ext);
136                 }
137             } else {
138                 sb.append(resourcePath);
139             }
140         } else {
141             // Then we use the given path regardless of prefix
142             sb.append(path);
143             if (addFingerPrint) {
144                 log.warn("Could not generate fingerprint for unknown resource {}", path);
145             }
146         }
147 
148         return sb.toString();
149     }
150 
151     /**
152      * Called with a pathInfo, cleans up the given path and returns the corresponding {@link Resource}.
153      * Leniently returns null if no such resource exists.
154      *
155      * @see javax.servlet.http.HttpServletRequest#getPathInfo()
156      */
157     public Resource getResource(String pathInfo) {
158         final String path = stripFarFutureCachingTimestamp(pathInfo);
159         if (!origin.hasPath(path)) {
160             return null;
161         }
162         return origin.getByPath(path);
163     }
164 
165     // We have to do this here - AggregationState has a cleaned up version, but we can't rely on this,
166     // since it's currently done in RepositoryMappingFilter, which is later than servlets in the chain.
167     // Besides, that'd prevent us from using request.pathInfo as well.
168     // TODO This should really be factored out - see info.magnolia.module.resources.Resource.getLink()
169     // and info.magnolia.cms.util.LinkUtil
170     protected String stripFarFutureCachingTimestamp(String resourcePath) {
171         final Matcher matcher = CACHE_PATTERN.matcher(resourcePath);
172         return matcher.replaceFirst("");
173     }
174 
175     protected String fingerPrintFor(info.magnolia.resourceloader.Resource resource) {
176         final long lastMod = resource.getLastModified();
177         return TIME_STAMP_FORMAT.format(lastMod);
178     }
179 
180     /**
181      * Gets prefix containing context path.
182      * <p>This implementation is not site-aware, meaning that site-prefix is not added to the prefix.</p>
183      * <p>Note: current request must be in {@link WebContext} in order to be able to get context path.</p>
184      *
185      * @return context path (if any)
186      */
187     protected Optional<String> getLinkPrefix() {
188         final Context context = webContextProvider.get();
189         if (context instanceof WebContext) {
190             String contextPath = ((WebContext) context).getContextPath();
191             return Optional.of(contextPath);
192         }
193         return Optional.empty();
194     }
195 }