Convert all relative URLs according to a <base> in HTML
425809
public static function resolve_base($body)
    {
        // check for <base href=...>
        if (preg_match('!(<base.*href=["\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {
            $replacer = new rcube_base_replacer($regs[2]);
            $body     = $replacer->replace($body);
        }

        return $body;
    }
989109
def as_href(from_path)
      if @options.all_one_file
        "#" + path
      else
        RDoc::Markup::ToHtml.gen_relative_url from_path, path
      end
    end
1020234
def build_url (self):
        
        # norm base url - can raise UnicodeError from url.idna_encode()
        base_url, is_idn = url_norm(self.base_url, self.encoding)
        # make url absolute
        if self.base_ref:
            # use base reference as parent url
            if ":" not in self.base_ref:
                # some websites have a relative base reference
                self.base_ref = urljoin(self.parent_url, self.base_ref)
            self.url = urljoin(self.base_ref, base_url)
        elif self.parent_url:
            # strip the parent url query and anchor
            urlparts = list(urlparse.urlsplit(self.parent_url))
            urlparts[4] = ""
            parent_url = urlutil.urlunsplit(urlparts)
            self.url = urljoin(parent_url, base_url)
        else:
            self.url = base_url
        # urljoin can unnorm the url path, so norm it again
        urlparts = list(urlparse.urlsplit(self.url))
        if urlparts[2]:
            urlparts[2] = urlutil.collapse_segments(urlparts[2])
        self.url = urlutil.urlunsplit(urlparts)
        # split into (modifiable) list
        self.urlparts = strformat.url_unicode_split(self.url)
        self.build_url_parts()
        # and unsplit again
        self.url = urlutil.urlunsplit(self.urlparts)
1264162
def _make_absolute(self, link):
        """"""

        # Parse the link with stdlib.
        parsed = urlparse(link)._asdict()

        # If link is relative, then join it with base_url.
        if not parsed['netloc']:
            return urljoin(self.base_url, link)

        # Link is absolute; if it lacks a scheme, add one from base_url.
        if not parsed['scheme']:
            parsed['scheme'] = urlparse(self.base_url).scheme

            # Reconstruct the URL to incorporate the new scheme.
            parsed = (v for v in parsed.values())
            return urlunparse(parsed)

        # Link is absolute and complete with scheme; nothing to be done here.
        return link
117696
def base_url(self, value):
        
        logger.debug('StackInABoxService ({0}:{1}) Updating Base URL '
                     'from {2} to {3}'
                     .format(self.__id,
                             self.name,
                             self.__base_url,
                             value))
        self.__base_url = value
        for k, v in six.iteritems(self.routes):
            v['regex'] = StackInABoxService.get_service_regex(
                value,
                v['uri'],
                v['handlers'].is_subservice)
682891
function absoluteUrl (baseUrl, pathUrl) {
  if (pathUrl && pathUrl.slice(0, 4) !== 'http') {
    return [baseUrl, pathUrl].map((path) => {
      if (path[0] === '/') {
        path = path.slice(1)
      }
      if (path[path.length - 1] === '/') {
        path = path.slice(0, path.length - 1)
      }
      return path
    }).join('/')
  }

  return pathUrl
}
329036
def make_absolute(base, relative):
        

        # Python 3.4 and lower do not remove folder traversal strings.
        # This was fixed in 3.5 (https://docs.python.org/3/whatsnew/3.5.html#urllib)
        while relative.startswith('/../') or relative.startswith('../'):
            relative = relative[3:]

            base_parsed = urlparse(base)
            new_path = base_parsed.path.rsplit('/', 1)[0]
            base_parsed = base_parsed._replace(path=new_path)
            base = base_parsed.geturl()

        return urljoin(base, relative)
860427
def base_url(self, value):
        """"""
        logger.debug('StackInABox({0}): Updating URL from {1} to {2}'
                     .format(self.__id, self.__base_url, value))
        self.__base_url = value
        for k, v in six.iteritems(self.services):
            matcher, service = v
            service.base_url = StackInABox.__get_service_url(value,
                                                             service.name)
            logger.debug('StackInABox({0}): Service {1} has url {2}'
                         .format(self.__id, service.name, service.base_url))
843628
def clean_url(url, base_url=None):
    """"""
    parsed_url = urlparse(url)

    fragment = '{url.fragment}'.format(url=parsed_url)
    if fragment:
        url = url.split(fragment)[0]

    # Identify internal URLs and fix their format
    netloc = '{url.netloc}'.format(url=parsed_url)
    if base_url is not None and not netloc:
        parsed_base = urlparse(base_url)
        split_base = '{url.scheme}://{url.netloc}{url.path}/'.format(url=parsed_base)
        url = urljoin(split_base, url)
        netloc = '{url.netloc}'.format(url=urlparse(url))

    if 'www.' in netloc:
        url = url.replace(netloc, netloc.replace('www.', ''))
    return url.rstrip(string.punctuation)
387269
def relative(self):
        
        if not self.is_absolute():
            raise ValueError("URL should be absolute")
        val = self._val._replace(scheme="", netloc="")
        return URL(val, encoded=True)
1259528
function(relative) {
    var base = this;           // The base url we're resolving against
    var r = new URL(relative); // The relative reference url to resolve
    var t = new URL();         // The absolute target url we will return

    if (r.scheme !== undefined) {
      t.scheme = r.scheme;
      t.username = r.username;
      t.password = r.password;
      t.host = r.host;
      t.port = r.port;
      t.path = remove_dot_segments(r.path);
      t.query = r.query;
    }
    else {
      t.scheme = base.scheme;
      if (r.host !== undefined) {
        t.username = r.username;
        t.password = r.password;
        t.host = r.host;
        t.port = r.port;
        t.path = remove_dot_segments(r.path);
        t.query = r.query;
      }
      else {
        t.username = base.username;
        t.password = base.password;
        t.host = base.host;
        t.port = base.port;
        if (!r.path) { // undefined or empty
          t.path = base.path;
          if (r.query !== undefined)
            t.query = r.query;
          else
            t.query = base.query;
        }
        else {
          if (r.path.charAt(0) === "/") {
            t.path = remove_dot_segments(r.path);
          }
          else {
            t.path = merge(base.path, r.path);
            t.path = remove_dot_segments(t.path);
          }
          t.query = r.query;
        }
      }
    }
    t.fragment = r.fragment;

    return t.toString();


    function merge(basepath, refpath) {
      if (base.host !== undefined && !base.path)
        return "/" + refpath;

      var lastslash = basepath.lastIndexOf("/");
      if (lastslash === -1)
        return refpath;
      else
        return basepath.substring(0, lastslash+1) + refpath;
    }

    function remove_dot_segments(path) {
      if (!path) return path; // For "" or undefined

      var output = "";
      while(path.length > 0) {
        if (path === "." || path === "..") {
          path = "";
          break;
        }

        var twochars = path.substring(0,2);
        var threechars = path.substring(0,3);
        var fourchars = path.substring(0,4);
        if (threechars === "../") {
          path = path.substring(3);
        }
        else if (twochars === "./") {
          path = path.substring(2);
        }
        else if (threechars === "/./") {
          path = "/" + path.substring(3);
        }
        else if (twochars === "/." && path.length === 2) {
          path = "/";
        }
        else if (fourchars === "/../" ||
             (threechars === "/.." && path.length === 3)) {
          path = "/" + path.substring(4);

          output = output.replace(/\/?[^\/]*$/, "");
        }
        else {
          var segment = path.match(/(\/?([^\/]*))/)[0];
          output += segment;
          path = path.substring(segment.length);
        }
      }

      return output;
    }
  }
948365
function set_base_url($url = '')
    {
        if (empty($url)) {
            if (!empty($_SERVER['HTTP_HOST'])) {
                $this->url = 'http://' . $_SERVER['HTTP_HOST'];
            }
            else {
                $this->url = '';
            }
        }
        else {
            // Strip any trailing slashes for consistency (relative
            // URLs may already start with a slash like "/file.html")
            if (substr($url, -1) == '/') {
                $url = substr($url, 0, -1);
            }
            $this->url = $url;
        }
    }
1153560
def to_url(self):
        """"""
        base_url = urlparse(self.url)

        if PY3:
            query = parse_qs(base_url.query)
            for k, v in self.items():
                query.setdefault(k, []).append(to_utf8_optional_iterator(v))
            scheme = base_url.scheme
            netloc = base_url.netloc
            path = base_url.path
            params = base_url.params
            fragment = base_url.fragment
        else:
            query = parse_qs(to_utf8(base_url.query))
            for k, v in self.items():
                query.setdefault(to_utf8(k), []).append(to_utf8_optional_iterator(v))
            scheme = to_utf8(base_url.scheme)
            netloc = to_utf8(base_url.netloc)
            path = to_utf8(base_url.path)
            params = to_utf8(base_url.params)
            fragment = to_utf8(base_url.fragment)

        url = (scheme, netloc, path, params, urlencode(query, True), fragment)
        return urlunparse(url)
182576
function toAbsoluteUrl(url, host) {

                    return isAbsolute(url) ? url : (startWithSlash(url) ? host + url : host + '/' + url);

                }
872630
private static String makeBaseUri(URL url) {
		String r = url.getProtocol().toLowerCase() + "://" +
				url.getHost().toLowerCase();
		if ((url.getProtocol().equalsIgnoreCase("http") &&
				url.getPort() != -1 && url.getPort() != 80) ||
			(url.getProtocol().equalsIgnoreCase("https") &&
					url.getPort() != -1 && url.getPort() != 443)) {
			r += ":" + url.getPort();
		}
		return r;
	}
428462
function(route, args, base) {
            base = base || "";
            args = args || {};
            var url = route;
            url = url.replace("#!/","#").replace("#!", "#").replace("#", "");
            _.map(args, function(value, attr) {
                url = url.replace("\:"+attr, value);
            });
            return base+"#/"+url;
        }
244414
private String convertRelativeURIToURL(String relativeURI)
    {

        if (relativeURI == null)
        {
            throw new IllegalStateException();
        }
        else
        {
            relativeURI = relativeURI.trim();
        }

        // If the passed URI contains "://" before the query string then it is either an
        // absolute URL or invalid and cannot be converted anyway
        int indexOfSchemeDelimiter = relativeURI.indexOf("://");
        if (indexOfSchemeDelimiter != -1)
        {
            int indexOfQueryString = relativeURI.indexOf('?');

            // If "://" occurs after '?' then it's part of the query string.
            // Otherwise return this absolute (or invalid) URL
            if ((indexOfQueryString == -1) || (indexOfSchemeDelimiter < indexOfQueryString))
            {
                return relativeURI;
            }
        }

        String urlScheme = _request.getScheme();		
        if (com.ibm.ws.webcontainer.osgi.WebContainer.getServletContainerSpecLevel() >= 31) {
            if (relativeURI.startsWith("//")) {
                StringBuffer url = new StringBuffer(urlScheme);
                url.append(":"); // slash slash will be added from the relativeURI
                url.append(relativeURI);
                return url.toString();
            }
        }

        String webAppRootURI = null;
        boolean relativeToRootURI = false;
        try
        {
            webAppRootURI = getWebApp().getContextPath().trim();
            if (webAppRootURI.startsWith("/") == false)
            {
                webAppRootURI = ("/" + webAppRootURI);
            }
        }
        catch (Exception ex)
        {
            com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(ex, "com.ibm.ws.webcontainer.webapp.WebAppDispatcherResponse.convertRelativeURIToURL", "184", this);
            webAppRootURI = "/";
        }

        try
        {
            relativeToRootURI = relativeURI.startsWith("/");

            // If relative URI begins with "./" (current level in URL hierarchy) then remove it
            if (relativeURI.startsWith("./"))
                relativeURI = relativeURI.substring(2);

            IExtendedRequest request = _request;

            // 112000 - begin - there was no reason to have two schemes for handling relative to root vs.
            // not relative to root so redid the section below

            // add the server info to the front of the url
            int urlPort = request.getServerPort();

            StringBuffer url = new StringBuffer(urlScheme);
            url.append("://");
            url.append(request.getServerName());

            // Add the port to the URL if it is not the default one for the scheme
            if (((urlScheme.equals("http") == true) && (urlPort != 80)) || ((urlScheme.equals("https") == true) && (urlPort != 443)))
            {
                url.append(":");
                url.append(urlPort);
            }

            String redirectURL = null;
            if (relativeToRootURI)
            {
                // 115010 - begin
                // if the relative URI begins with '/' and we're in sendRedirect compatibility mode, then make uri 
                // relative to the context root...otherwise, make it relative to the server (no context root)
                if (com.ibm.ws.webcontainer.util.WebContainerSystemProps.getSendRedirectCompatibilty())
                {
                    // append webapp context and relative URI
                    url.append(webAppRootURI);
                    url.append(relativeURI);
                }
                else
                {
                    url.append(relativeURI);
                }
                // 115010 - end
                redirectURL = url.toString();
            }
            else
            {
                // not relative to webapp context root, but relative to the presently
                // invoked URL

                String requestString = HttpUtils.getRequestURL((HttpServletRequest) request).toString();
                String pathInfo = request.getPathInfo();
                // start PI22830
                if(!webAppRootURI.equals("/") && request.getRequestURI().equals(webAppRootURI)){
                    requestString = requestString + "/";
                    if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        logger.logp(Level.FINE, CLASS_NAME,"convertRelativeURIToURL", "appended / to requestString --> " + requestString);
                } // end PI22830

                if ((pathInfo != null) && (pathInfo.length() > 0))
                {
                    if (!pathInfo.startsWith("/"))
                    {
                        pathInfo = "/" + pathInfo;
                    }
                    //start PK23779

                    if(redirectWithPathInfo || (com.ibm.ws.webcontainer.osgi.WebContainer.getServletContainerSpecLevel() >= 31)){
                        requestString = requestString.substring(0, requestString.lastIndexOf("/"));
                    }
                    else{
                        // Remove the PathInfo from the request
                        requestString = requestString.substring(0, requestString.lastIndexOf(pathInfo));
                    }
                    //end PK23779
                    redirectURL = requestString + "/" + relativeURI;
                }
                else
                {
                    redirectURL = requestString.substring(0, requestString.lastIndexOf('/') + 1) + relativeURI;
                }
            }
            if (redirectURL.indexOf("..") > -1)
            { // only normalize where required.. this is expensive.
                int skip = new String(urlScheme + "://").length();
                int split = redirectURL.indexOf("/", skip);
                String serverString = redirectURL.substring(0, split);
                String uri = redirectURL.substring(split);
                uri = getWebApp().normalize(uri);
                if (uri != null)
                {
                    return serverString + uri;
                }
            }
            else
            { // return url since it is already normalized.
                return redirectURL;
            }
            // 112000 - end
        }
        catch (Exception ex)
        {
            com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(ex, "com.ibm.ws.webcontainer.webapp.WebAppDispatcherResponse.convertRelativeURIToURL", "256", this);
        }

        // Could not convert
        return relativeURI;
    }