001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.staticexport;
029
030import org.opencms.ade.detailpage.I_CmsDetailPageFinder;
031import org.opencms.file.CmsObject;
032import org.opencms.file.CmsResource;
033import org.opencms.file.CmsResourceFilter;
034import org.opencms.file.CmsVfsException;
035import org.opencms.file.CmsVfsResourceNotFoundException;
036import org.opencms.file.types.CmsResourceTypeImage;
037import org.opencms.loader.CmsLoaderException;
038import org.opencms.main.CmsException;
039import org.opencms.main.CmsLog;
040import org.opencms.main.CmsStaticResourceHandler;
041import org.opencms.main.OpenCms;
042import org.opencms.site.CmsSite;
043import org.opencms.site.CmsSiteMatcher;
044import org.opencms.util.CmsFileUtil;
045import org.opencms.util.CmsPair;
046import org.opencms.util.CmsStringUtil;
047import org.opencms.util.CmsUUID;
048import org.opencms.workplace.CmsWorkplace;
049
050import java.net.URI;
051import java.util.List;
052import java.util.Locale;
053
054import org.apache.commons.logging.Log;
055
056/**
057 * Default link substitution behavior.<p>
058 *
059 * @since 7.0.2
060 *
061 * @see CmsLinkManager#substituteLink(org.opencms.file.CmsObject, String, String, boolean)
062 *      for the method where this handler is used.
063 */
064public class CmsDefaultLinkSubstitutionHandler implements I_CmsLinkSubstitutionHandler {
065
066    /**
067     * Request context attribute name to make the link substitution handler treat the link like an image link.<p>
068     */
069    public static final String ATTR_IS_IMAGE_LINK = "IS_IMAGE_LINK";
070
071    /** Key for a request context attribute to control whether the getRootPath method uses the current site root for workplace requests.
072     *  The getRootPath method clears this attribute when called.
073     */
074    public static final String DONT_USE_CURRENT_SITE_FOR_WORKPLACE_REQUESTS = "DONT_USE_CURRENT_SITE_FOR_WORKPLACE_REQUESTS";
075
076    /** The log object for this class. */
077    private static final Log LOG = CmsLog.getLog(CmsDefaultLinkSubstitutionHandler.class);
078
079    /** Prefix used for request context attributes to control whether a different site root should be used in appendServerPrefix. */
080    public static final String OVERRIDE_SITEROOT_PREFIX = "OVERRIDE_SITEROOT:";
081
082    /**
083     * Returns the resource root path in the OpenCms VFS for the given link, or <code>null</code> in
084     * case the link points to an external site.<p>
085     *
086     * If the target URI contains no site information, but starts with the opencms context, the context is removed:<pre>
087     * /opencms/opencms/system/further_path -> /system/further_path</pre>
088     *
089     * If the target URI contains no site information, the path will be prefixed with the current site
090     * from the provided OpenCms user context:<pre>
091     * /folder/page.html -> /sites/mysite/folder/page.html</pre>
092     *
093     * If the path of the target URI is relative, i.e. does not start with "/",
094     * the path will be prefixed with the current site and the given relative path,
095     * then normalized.
096     * If no relative path is given, <code>null</code> is returned.
097     * If the normalized path is outsite a site, null is returned.<pre>
098     * page.html -> /sites/mysite/page.html
099     * ../page.html -> /sites/mysite/page.html
100     * ../../page.html -> null</pre>
101     *
102     * If the target URI contains a scheme/server name that denotes an opencms site,
103     * it is replaced by the appropriate site path:<pre>
104     * http://www.mysite.de/folder/page.html -> /sites/mysite/folder/page.html</pre><p>
105     *
106     * If the target URI contains a scheme/server name that does not match with any site,
107     * or if the URI is opaque or invalid,
108     * <code>null</code> is returned:<pre>
109     * http://www.elsewhere.com/page.html -> null
110     * mailto:someone@elsewhere.com -> null</pre>
111     *
112     * @see org.opencms.staticexport.I_CmsLinkSubstitutionHandler#getLink(org.opencms.file.CmsObject, java.lang.String, java.lang.String, boolean)
113     */
114    public String getLink(CmsObject cms, String link, String siteRoot, boolean forceSecure) {
115
116        return getLink(cms, link, siteRoot, null, forceSecure);
117    }
118
119    /**
120     * @see org.opencms.staticexport.I_CmsLinkSubstitutionHandler#getLink(org.opencms.file.CmsObject, java.lang.String, java.lang.String, java.lang.String, boolean)
121     */
122    public String getLink(CmsObject cms, String link, String siteRoot, String targetDetailPage, boolean forceSecure) {
123
124        if (CmsStringUtil.isEmpty(link)) {
125            // not a valid link parameter, return an empty String
126            return "";
127        }
128
129        if (CmsStaticResourceHandler.isStaticResourceUri(link)) {
130            return CmsWorkplace.getStaticResourceUri(link);
131        }
132
133        // make sure we have an absolute link
134        String absoluteLink = CmsLinkManager.getAbsoluteUri(link, cms.getRequestContext().getUri());
135        String overrideSiteRoot = null;
136
137        String vfsName;
138        String parameters;
139        // check if the link has parameters, if so cut them
140        int pos = absoluteLink.indexOf('?');
141        if (pos >= 0) {
142            vfsName = absoluteLink.substring(0, pos);
143            parameters = absoluteLink.substring(pos);
144        } else {
145            vfsName = absoluteLink;
146            parameters = null;
147        }
148
149        // check for anchor
150        String anchor = null;
151        pos = vfsName.indexOf('#');
152        if (pos >= 0) {
153            anchor = vfsName.substring(pos);
154            vfsName = vfsName.substring(0, pos);
155        }
156
157        String resultLink = null;
158        String uriBaseName = null;
159        boolean useRelativeLinks = false;
160
161        // determine the target site of the link
162        CmsSite currentSite = OpenCms.getSiteManager().getCurrentSite(cms);
163        CmsSite targetSite = null;
164        if (CmsStringUtil.isNotEmpty(siteRoot)) {
165            targetSite = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);
166        }
167        if (targetSite == null) {
168            targetSite = currentSite;
169        }
170
171        String targetSiteRoot = targetSite.getSiteRoot();
172        String originalVfsName = vfsName;
173        String detailPage = null;
174        CmsResource detailContent = null;
175        try {
176            String rootVfsName;
177            if (!vfsName.startsWith(targetSiteRoot)
178                && !vfsName.startsWith(CmsResource.VFS_FOLDER_SYSTEM + "/")
179                && !OpenCms.getSiteManager().startsWithShared(vfsName)) {
180                rootVfsName = CmsStringUtil.joinPaths(targetSiteRoot, vfsName);
181            } else {
182                rootVfsName = vfsName;
183            }
184            if (!rootVfsName.startsWith(CmsWorkplace.VFS_PATH_WORKPLACE)) {
185                // never use the ADE manager for workplace links, to be sure the workplace stays usable in case of configuration errors
186                I_CmsDetailPageFinder finder = OpenCms.getADEManager().getDetailPageFinder();
187                detailPage = finder.getDetailPage(cms, rootVfsName, cms.getRequestContext().getUri(), targetDetailPage);
188            }
189            if (detailPage != null) {
190                CmsSite detailPageSite = OpenCms.getSiteManager().getSiteForRootPath(detailPage);
191                if (detailPageSite != null) {
192                    targetSite = detailPageSite;
193                    overrideSiteRoot = targetSiteRoot = targetSite.getSiteRoot();
194                    detailPage = detailPage.substring(targetSiteRoot.length());
195                    if (!detailPage.startsWith("/")) {
196                        detailPage = "/" + detailPage;
197                    }
198                }
199                String originalSiteRoot = cms.getRequestContext().getSiteRoot();
200                try {
201                    cms.getRequestContext().setSiteRoot("");
202                    CmsResource element = cms.readResource(rootVfsName, CmsResourceFilter.IGNORE_EXPIRATION);
203                    detailContent = element;
204                    Locale locale = cms.getRequestContext().getLocale();
205                    List<Locale> defaultLocales = OpenCms.getLocaleManager().getDefaultLocales();
206                    vfsName = CmsStringUtil.joinPaths(
207                        detailPage,
208                        cms.getDetailName(element, locale, defaultLocales),
209                        "/");
210
211                } catch (CmsVfsException e) {
212                    LOG.error(e.getLocalizedMessage(), e);
213                } finally {
214                    cms.getRequestContext().setSiteRoot(originalSiteRoot);
215
216                }
217            }
218        } catch (CmsVfsResourceNotFoundException e) {
219            LOG.info(e.getLocalizedMessage(), e);
220        } catch (CmsException e) {
221            LOG.error(e.getLocalizedMessage(), e);
222        }
223
224        // if the link points to another site, there needs to be a server prefix
225        String serverPrefix;
226        if (targetSite != currentSite) {
227            serverPrefix = targetSite.getUrl();
228        } else {
229            serverPrefix = "";
230        }
231
232        // in the online project, check static export and secure settings
233        if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {
234            // first check if this link needs static export
235            CmsStaticExportManager exportManager = OpenCms.getStaticExportManager();
236            String oriUri = cms.getRequestContext().getUri();
237            // check if we need relative links in the exported pages
238            if (exportManager.relativeLinksInExport(cms.getRequestContext().getSiteRoot() + oriUri)) {
239                // try to get base URI from cache
240                String cacheKey = exportManager.getCacheKey(targetSiteRoot, oriUri);
241                uriBaseName = exportManager.getCachedOnlineLink(cacheKey);
242                if (uriBaseName == null) {
243                    // base not cached, check if we must export it
244                    if (exportManager.isExportLink(cms, oriUri)) {
245                        // base URI must also be exported
246                        uriBaseName = exportManager.getRfsName(cms, oriUri);
247                    } else {
248                        // base URI dosn't need to be exported
249                        CmsPair<String, String> uriParamPair = addVfsPrefix(cms, oriUri, targetSite, parameters);
250                        uriBaseName = uriParamPair.getFirst();
251                        parameters = uriParamPair.getSecond();
252                    }
253                    // cache export base URI
254                    exportManager.cacheOnlineLink(cacheKey, uriBaseName);
255                }
256                // use relative links only on pages that get exported
257                useRelativeLinks = uriBaseName.startsWith(
258                    exportManager.getRfsPrefix(cms.getRequestContext().getSiteRoot() + oriUri));
259            }
260
261            String detailPagePart = detailPage == null ? "" : detailPage + ":";
262            // check if we have the absolute VFS name for the link target cached
263            // (We really need the target site root in the cache key, because different resources with the same site paths
264            // but in different sites may have different export settings. It seems we don't really need the site root
265            // from the request context as part of the key, but we'll leave it in to make sure we don't break anything.)
266            String cacheKey = generateCacheKey(cms, targetSiteRoot, detailPagePart, absoluteLink);
267            resultLink = exportManager.getCachedOnlineLink(cacheKey);
268            if (resultLink == null) {
269                String storedSiteRoot = cms.getRequestContext().getSiteRoot();
270                try {
271                    cms.getRequestContext().setSiteRoot(targetSite.getSiteRoot());
272                    // didn't find the link in the cache
273                    if (exportManager.isExportLink(cms, vfsName)) {
274                        parameters = prepareExportParameters(cms, vfsName, parameters);
275                        // export required, get export name for target link
276                        resultLink = exportManager.getRfsName(cms, vfsName, parameters, targetDetailPage);
277                        // now set the parameters to null, we do not need them anymore
278                        parameters = null;
279                    } else {
280                        // no export required for the target link
281                        CmsPair<String, String> uriParamPair = addVfsPrefix(cms, vfsName, targetSite, parameters);
282                        resultLink = uriParamPair.getFirst();
283                        parameters = uriParamPair.getSecond();
284                        // add cut off parameters if required
285                        if (parameters != null) {
286                            resultLink = resultLink.concat(parameters);
287                        }
288                    }
289                } finally {
290                    cms.getRequestContext().setSiteRoot(storedSiteRoot);
291                }
292                // cache the result
293                exportManager.cacheOnlineLink(cacheKey, resultLink);
294            }
295
296            // now check for the secure settings
297
298            // check if either the current site or the target site does have a secure server configured
299            if (targetSite.hasSecureServer() || currentSite.hasSecureServer()) {
300
301                if (!vfsName.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) {
302                    // don't make a secure connection to the "/system" folder (why ?)
303                    int linkType = -1;
304                    try {
305                        // read the linked resource
306                        linkType = cms.readResource(originalVfsName).getTypeId();
307                    } catch (CmsException e) {
308                        // the resource could not be read
309                        if (LOG.isInfoEnabled()) {
310                            String message = Messages.get().getBundle().key(
311                                Messages.LOG_RESOURCE_ACESS_ERROR_3,
312                                vfsName,
313                                cms.getRequestContext().getCurrentUser().getName(),
314                                cms.getRequestContext().getSiteRoot());
315                            if (LOG.isDebugEnabled()) {
316                                LOG.debug(message, e);
317                            } else {
318                                LOG.info(message);
319                            }
320                        }
321                    }
322
323                    // images are always referenced without a server prefix
324                    int imageId;
325                    try {
326                        imageId = OpenCms.getResourceManager().getResourceType(
327                            CmsResourceTypeImage.getStaticTypeName()).getTypeId();
328                    } catch (CmsLoaderException e1) {
329                        // should really never happen
330                        LOG.warn(e1.getLocalizedMessage(), e1);
331                        imageId = CmsResourceTypeImage.getStaticTypeId();
332                    }
333                    boolean hasIsImageLinkAttr = Boolean.parseBoolean(
334                        "" + cms.getRequestContext().getAttribute(ATTR_IS_IMAGE_LINK));
335                    if ((linkType != imageId) && !hasIsImageLinkAttr) {
336                        // check the secure property of the link
337                        boolean secureRequest = cms.getRequestContext().isSecureRequest()
338                            || exportManager.isSecureLink(cms, oriUri);
339
340                        boolean secureLink;
341                        if (detailContent == null) {
342                            secureLink = isSecureLink(cms, vfsName, targetSite, secureRequest);
343                        } else {
344                            secureLink = isDetailPageLinkSecure(
345                                cms,
346                                detailPage,
347                                detailContent,
348                                targetSite,
349                                secureRequest);
350
351                        }
352                        // if we are on a normal server, and the requested resource is secure,
353                        // the server name has to be prepended
354                        if (secureLink && (forceSecure || !secureRequest)) {
355                            serverPrefix = targetSite.getSecureUrl();
356                        } else if (!secureLink && secureRequest) {
357                            serverPrefix = targetSite.getUrl();
358                        }
359                    }
360                }
361            }
362            // make absolute link relative, if relative links in export are required
363            // and if the link does not point to another server
364            if (useRelativeLinks && CmsStringUtil.isEmpty(serverPrefix)) {
365                // in case the current page is a detailpage, append another path level
366                if (cms.getRequestContext().getDetailContentId() != null) {
367                    uriBaseName = CmsStringUtil.joinPaths(
368                        CmsResource.getFolderPath(uriBaseName),
369                        cms.getRequestContext().getDetailContentId().toString() + "/index.html");
370                }
371                resultLink = CmsLinkManager.getRelativeUri(uriBaseName, resultLink);
372            }
373
374        } else {
375            // offline project, no export or secure handling required
376            if (OpenCms.getRunLevel() >= OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
377                // in unit test this code would fail otherwise
378                CmsPair<String, String> uriParamPair = addVfsPrefix(cms, vfsName, targetSite, parameters);
379                resultLink = uriParamPair.getFirst();
380                parameters = uriParamPair.getSecond();
381            }
382
383            // add cut off parameters and return the result
384            if ((parameters != null) && (resultLink != null)) {
385                resultLink = resultLink.concat(parameters);
386            }
387        }
388
389        if ((anchor != null) && (resultLink != null)) {
390            resultLink = resultLink.concat(anchor);
391        }
392        if (overrideSiteRoot != null) {
393            cms.getRequestContext().setAttribute(OVERRIDE_SITEROOT_PREFIX + resultLink, overrideSiteRoot);
394        }
395
396        return serverPrefix.concat(resultLink);
397    }
398
399    /**
400     * @see org.opencms.staticexport.I_CmsLinkSubstitutionHandler#getRootPath(org.opencms.file.CmsObject, java.lang.String, java.lang.String)
401     */
402    public String getRootPath(CmsObject cms, String targetUri, String basePath) {
403
404        String result = getSimpleRootPath(cms, targetUri, basePath);
405        String detailRootPath = getDetailRootPath(cms, result);
406        if (detailRootPath != null) {
407            result = detailRootPath;
408        }
409        return result;
410
411    }
412
413    /**
414     * Adds the VFS prefix to the VFS name and potentially adjusts request parameters<p>
415     * This method is required as a hook used in {@link CmsLocalePrefixLinkSubstitutionHandler}.<p>
416     *
417     * @param cms the cms context
418     * @param vfsName the VFS name
419     * @param targetSite the target site
420     * @param parameters the request parameters
421     *
422     * @return the path and the (adjusted) request parameters.
423     */
424    protected CmsPair<String, String> addVfsPrefix(
425        CmsObject cms,
426        String vfsName,
427        CmsSite targetSite,
428        String parameters) {
429
430        return new CmsPair<String, String>(OpenCms.getStaticExportManager().getVfsPrefix().concat(vfsName), parameters);
431    }
432
433    /**
434     * Generates the cache key for Online links.
435     * @param cms the current CmsObject
436     * @param targetSiteRoot the target site root
437     * @param detailPagePart the detail page part
438     * @param absoluteLink the absolute (site-relative) link to the resource
439     * @return the cache key
440     */
441    protected String generateCacheKey(
442        CmsObject cms,
443        String targetSiteRoot,
444        String detailPagePart,
445        String absoluteLink) {
446
447        return cms.getRequestContext().getSiteRoot() + ":" + targetSiteRoot + ":" + detailPagePart + absoluteLink;
448    }
449
450    /**
451     * Returns the root path for given site.<p>
452     * This method is required as a hook used in {@link CmsLocalePrefixLinkSubstitutionHandler}.<p>
453     * @param cms the cms context
454     * @param path the path
455     * @param siteRoot the site root, will be null in case of the root site
456     * @param isRootPath in case the path is already a root path
457     *
458     * @return the root path
459     */
460    protected String getRootPathForSite(CmsObject cms, String path, String siteRoot, boolean isRootPath) {
461
462        if (isRootPath || (siteRoot == null)) {
463            return CmsStringUtil.joinPaths("/", path);
464        } else {
465            return cms.getRequestContext().addSiteRoot(siteRoot, path);
466        }
467    }
468
469    /**
470     * Gets the root path without taking into account detail page links.<p>
471     *
472     * @param cms - see the getRootPath() method
473     * @param targetUri - see the getRootPath() method
474     * @param basePath - see the getRootPath() method
475     * @return - see the getRootPath() method
476     */
477    protected String getSimpleRootPath(CmsObject cms, String targetUri, String basePath) {
478
479        if (cms == null) {
480            // required by unit test cases
481            return targetUri;
482        }
483
484        URI uri;
485        String path;
486        String suffix = "";
487
488        // malformed uri
489        try {
490            uri = new URI(targetUri);
491            path = uri.getPath();
492            suffix = getSuffix(uri);
493        } catch (Exception e) {
494            if (LOG.isWarnEnabled()) {
495                LOG.warn(Messages.get().getBundle().key(Messages.LOG_MALFORMED_URI_1, targetUri), e);
496            }
497            return null;
498        }
499        // opaque URI
500        if (uri.isOpaque()) {
501            return null;
502        }
503
504        // in case the target is the workplace UI
505        if (CmsLinkManager.isWorkplaceUri(uri)) {
506            return null;
507        }
508
509        // in case the target is a static resource served from the class path
510        if (CmsStaticResourceHandler.isStaticResourceUri(uri)) {
511            return CmsStringUtil.joinPaths(
512                CmsStaticResourceHandler.STATIC_RESOURCE_PREFIX,
513                CmsStaticResourceHandler.removeStaticResourcePrefix(path));
514        }
515
516        CmsStaticExportManager exportManager = OpenCms.getStaticExportManager();
517        if (exportManager.isValidRfsName(path)) {
518            String originalSiteRoot = cms.getRequestContext().getSiteRoot();
519            String vfsName = null;
520            try {
521                cms.getRequestContext().setSiteRoot("");
522                vfsName = exportManager.getVfsName(cms, path);
523                if (vfsName != null) {
524                    return vfsName;
525                }
526            } finally {
527                cms.getRequestContext().setSiteRoot(originalSiteRoot);
528            }
529        }
530
531        // absolute URI (i.e. URI has a scheme component like http:// ...)
532        if (uri.isAbsolute()) {
533            CmsSiteMatcher targetMatcher = new CmsSiteMatcher(targetUri);
534            if (OpenCms.getSiteManager().isMatching(targetMatcher)
535                || targetMatcher.equals(cms.getRequestContext().getRequestMatcher())) {
536
537                path = CmsLinkManager.removeOpenCmsContext(path);
538                boolean isWorkplaceServer = OpenCms.getSiteManager().isWorkplaceRequest(targetMatcher)
539                    || targetMatcher.equals(cms.getRequestContext().getRequestMatcher());
540                if (isWorkplaceServer) {
541                    String selectedPath;
542                    String targetSiteRoot = OpenCms.getSiteManager().getSiteRoot(path);
543                    if (targetSiteRoot != null) {
544                        selectedPath = getRootPathForSite(cms, path, targetSiteRoot, true);
545                    } else {
546                        // set selectedPath with the path for the current site
547                        selectedPath = getRootPathForSite(cms, path, cms.getRequestContext().getSiteRoot(), false);
548                        String pathForMatchedSite = getRootPathForSite(
549                            cms,
550                            path,
551                            OpenCms.getSiteManager().matchSite(targetMatcher).getSiteRoot(),
552                            false);
553                        String originalSiteRoot = cms.getRequestContext().getSiteRoot();
554                        try {
555                            cms.getRequestContext().setSiteRoot("");
556                            // the path for the current site normally is preferred, but if it doesn't exist and the path for the matched site
557                            // does exist, then use the path for the matched site
558                            if (!cms.existsResource(selectedPath, CmsResourceFilter.ALL)
559                                && cms.existsResource(pathForMatchedSite, CmsResourceFilter.ALL)) {
560                                selectedPath = pathForMatchedSite;
561                            }
562                        } finally {
563                            cms.getRequestContext().setSiteRoot(originalSiteRoot);
564                        }
565                    }
566                    return selectedPath + suffix;
567                } else {
568                    // add the site root of the matching site
569                    return getRootPathForSite(
570                        cms,
571                        path + suffix,
572                        OpenCms.getSiteManager().matchSite(targetMatcher).getSiteRoot(),
573                        false);
574                }
575            } else {
576                return null;
577            }
578        }
579
580        // relative URI (i.e. no scheme component, but filename can still start with "/")
581        String context = OpenCms.getSystemInfo().getOpenCmsContext();
582        String vfsPrefix = OpenCms.getStaticExportManager().getVfsPrefix();
583        if ((context != null) && (path.startsWith(context + "/") || (path.startsWith(vfsPrefix + "/")))) {
584            // URI is starting with opencms context
585
586            // cut context from path
587            path = CmsLinkManager.removeOpenCmsContext(path);
588
589            String targetSiteRoot = getTargetSiteRoot(cms, path, basePath);
590
591            return getRootPathForSite(
592                cms,
593                path + suffix,
594                targetSiteRoot,
595                (targetSiteRoot != null) && path.startsWith(targetSiteRoot));
596        }
597
598        // URI with relative path is relative to the given relativePath if available and in a site,
599        // otherwise invalid
600        if (CmsStringUtil.isNotEmpty(path) && (path.charAt(0) != '/')) {
601            if (basePath != null) {
602                String absolutePath;
603                int pos = path.indexOf("../../galleries/pics/");
604                if (pos >= 0) {
605                    // HACK: mixed up editor path to system gallery image folder
606                    return CmsWorkplace.VFS_PATH_SYSTEM + path.substring(pos + 6) + suffix;
607                }
608                absolutePath = CmsLinkManager.getAbsoluteUri(path, cms.getRequestContext().addSiteRoot(basePath));
609                if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
610                    return absolutePath + suffix;
611                }
612                // HACK: some editor components (e.g. HtmlArea) mix up the editor URL with the current request URL
613                absolutePath = CmsLinkManager.getAbsoluteUri(
614                    path,
615                    cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS);
616                if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
617                    return absolutePath + suffix;
618                }
619                // HACK: same as above, but XmlContent editor has one path element more
620                absolutePath = CmsLinkManager.getAbsoluteUri(
621                    path,
622                    cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS + "xmlcontent/");
623                if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
624                    return absolutePath + suffix;
625                }
626            }
627
628            return null;
629        }
630
631        if (CmsStringUtil.isNotEmpty(path)) {
632            String targetSiteRoot = getTargetSiteRoot(cms, path, basePath);
633
634            return getRootPathForSite(
635                cms,
636                path + suffix,
637                targetSiteRoot,
638                (targetSiteRoot != null) && path.startsWith(targetSiteRoot));
639        }
640
641        // URI without path (typically local link)
642        return suffix;
643    }
644
645    /**
646     * Checks whether a link to a detail page should be secure.<p>
647     *
648     * @param cms the current CMS context
649     * @param detailPage the detail page path
650     * @param detailContent the detail content resource
651     * @param targetSite the target site containing the detail page
652     * @param secureRequest true if the currently running request is secure
653     *
654     * @return true if the link should be a secure link
655     */
656    protected boolean isDetailPageLinkSecure(
657        CmsObject cms,
658        String detailPage,
659        CmsResource detailContent,
660        CmsSite targetSite,
661        boolean secureRequest) {
662
663        boolean result = false;
664        CmsStaticExportManager exportManager = OpenCms.getStaticExportManager();
665        try {
666            cms = OpenCms.initCmsObject(cms);
667            if (targetSite.getSiteRoot() != null) {
668                cms.getRequestContext().setSiteRoot(targetSite.getSiteRoot());
669            }
670            CmsResource defaultFile = cms.readDefaultFile(detailPage);
671            if (defaultFile != null) {
672                result = exportManager.isSecureLink(cms, defaultFile.getRootPath(), "", secureRequest);
673            }
674        } catch (Exception e) {
675            LOG.error("Error while checking whether detail page link should be secure: " + e.getLocalizedMessage(), e);
676        }
677        return result;
678    }
679
680    /**
681     * Checks if the link target is a secure link.<p
682     *
683     * @param cms the current CMS context
684     * @param vfsName the path of the link target
685     * @param targetSite the target site containing the detail page
686     * @param secureRequest true if the currently running request is secure
687     *
688     * @return true if the link should be a secure link
689     */
690    protected boolean isSecureLink(CmsObject cms, String vfsName, CmsSite targetSite, boolean secureRequest) {
691
692        return OpenCms.getStaticExportManager().isSecureLink(cms, vfsName, targetSite.getSiteRoot(), secureRequest);
693    }
694
695    /**
696     * Prepares the request parameters for the given resource.<p>
697     * This method is required as a hook used in {@link CmsLocalePrefixLinkSubstitutionHandler}.<p>
698     *
699     * @param cms the cms context
700     * @param vfsName the vfs name
701     * @param parameters the parameters to prepare
702     *
703     * @return the root path
704     */
705    protected String prepareExportParameters(CmsObject cms, String vfsName, String parameters) {
706
707        return parameters;
708    }
709
710    /**
711     * Gets the suffix (query + fragment) of the URI.<p>
712     *
713     * @param uri the URI
714     * @return the suffix of the URI
715     */
716    String getSuffix(URI uri) {
717
718        String fragment = uri.getFragment();
719        if (fragment != null) {
720            fragment = "#" + fragment;
721        } else {
722            fragment = "";
723        }
724
725        String query = uri.getRawQuery();
726        if (query != null) {
727            query = "?" + query;
728        } else {
729            query = "";
730        }
731        return query.concat(fragment);
732    }
733
734    /**
735     * Tries to interpret the given URI as a detail page URI and returns the detail content's root path if possible.<p>
736     *
737     * If the given URI is not a detail URI, null will be returned.<p>
738     *
739     * @param cms the CMS context to use
740     * @param result the detail root path, or null if the given uri is not a detail page URI
741     *
742     * @return the detail content root path
743     */
744    private String getDetailRootPath(CmsObject cms, String result) {
745
746        if (result == null) {
747            return null;
748        }
749        try {
750            URI uri = new URI(result);
751            String path = uri.getPath();
752            if (CmsStringUtil.isEmptyOrWhitespaceOnly(path) || !OpenCms.getADEManager().isInitialized()) {
753                return null;
754            }
755            String name = CmsFileUtil.removeTrailingSeparator(CmsResource.getName(path));
756            CmsUUID detailId = OpenCms.getADEManager().getDetailIdCache(
757                cms.getRequestContext().getCurrentProject().isOnlineProject()).getDetailId(name);
758            if (detailId == null) {
759                return null;
760            }
761            String origSiteRoot = cms.getRequestContext().getSiteRoot();
762            try {
763                cms.getRequestContext().setSiteRoot("");
764                // real root paths have priority over detail contents
765                if (cms.existsResource(path)) {
766                    return null;
767                }
768            } finally {
769                cms.getRequestContext().setSiteRoot(origSiteRoot);
770            }
771            CmsResource detailResource = cms.readResource(detailId, CmsResourceFilter.ALL);
772            return detailResource.getRootPath() + getSuffix(uri);
773        } catch (Exception e) {
774            LOG.error(e.getLocalizedMessage(), e);
775            return null;
776        }
777    }
778
779    /**
780     * Returns the target site for the given path.<p>
781     *
782     * @param cms the cms context
783     * @param path the path
784     * @param basePath the base path
785     *
786     * @return the target site
787     */
788    private String getTargetSiteRoot(CmsObject cms, String path, String basePath) {
789
790        if (OpenCms.getSiteManager().startsWithShared(path) || path.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) {
791            return null;
792        }
793        String targetSiteRoot = OpenCms.getSiteManager().getSiteRoot(path);
794        if ((targetSiteRoot == null) && (basePath != null)) {
795            targetSiteRoot = OpenCms.getSiteManager().getSiteRoot(basePath);
796        }
797        if (targetSiteRoot == null) {
798            targetSiteRoot = cms.getRequestContext().getSiteRoot();
799        }
800        return targetSiteRoot;
801    }
802
803}