beans_url_to_path

Convert internal url to a path.

This function must only be used with internal urls.

beans_url_to_path( string $url )

Return: (string) Absolute path.

Parameters

NameTypeRequiredDefaultDescription
$urlstringtrue-Url to be converted. Accepts only internal urls.

Source

function beans_url_to_path( $url ) {

	static $root, $blogdetails;

	// Stop here if it is not an internal url.
	if ( false === stripos( $url, parse_url( site_url(), PHP_URL_HOST ) ) ) {
		return beans_sanitize_path( $url );
	}

	// Fix protocole. It isn't needed to set SSL as it is only used to parse the URL.
	if ( preg_match( '#^(\/\/)#', $url ) ) {
		$url = 'http:' . $url;
	}

	// Parse url and standardize backslashes.
	$url = parse_url( $url, PHP_URL_PATH );
	$path = wp_normalize_path( $url );
	$explode = beans_get( 0, explode( '/' , trailingslashit( ltrim( $path, '/' ) ) ) );

	// Maybe remove tilde from path.
	if ( false !== stripos( $explode, '~' ) ) {
		$path = preg_replace( '#\~[^/]*\/#', '', $path );
	}

	// Set root if it isn't cached yet.
	if ( ! $root ) {

		// Standardize backslashes and remove windows drive for local installs.
		$root = wp_normalize_path( untrailingslashit( ABSPATH ) );
		$set_root = true;

	}

	// Remove subfolder if necessary.
	if ( '' !== ( $subfolder = parse_url( site_url(), PHP_URL_PATH ) ) ) {

		// Set root if it isn't cached.
		if ( isset( $set_root ) ) {

			// Remove subfolder.
			$root = preg_replace( '#' . untrailingslashit( preg_quote( $subfolder ) ) . '$#', '', $root );

			// Add an extra step which is only used for extremely rare case.
			if ( defined( 'WP_SITEURL' ) && '' !== ( $subfolder = parse_url( WP_SITEURL, PHP_URL_PATH ) ) ) {
				$root = preg_replace( '#' . untrailingslashit( preg_quote( $subfolder ) ) . '$#', '', $root );
			}
		}

		// Remove the blog path for multsites.
		if ( ! is_main_site() ) {

			// Set blogdetails if it isn't cached.
			if ( ! $blogdetails ) {
				$blogdetails = get_blog_details( get_current_blog_id() );
			}

			$path = preg_replace( '#^(\/?)' . trailingslashit( preg_quote( ltrim( $blogdetails->path, '/' ) ) ) . '#', '', $path );

		}
	}

	// Remove Windows drive for local installs if the root isn't cached yet.
	if ( isset( $set_root ) ) {
		$root = beans_sanitize_path( $root );
	}

	// Add root of it doesn't exist.
	if ( false === strpos( $path, $root ) ) {
		$path = trailingslashit( $root ) . ltrim( $path, '/' );
	}

	return beans_sanitize_path( $path );

}