| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Core\Utils\ImportExport; |
| 4 |
|
| 5 |
if ( ! defined( 'ABSPATH' ) ) { |
| 6 |
exit; // Exit if accessed directly. |
| 7 |
} |
| 8 |
|
| 9 |
class Url { |
| 10 |
|
| 11 |
/** |
| 12 |
* Migrate url to the current permalink structure. |
| 13 |
* The function will also check and change absolute url to relative one by the base url. |
| 14 |
* This is currently supports only "Post Name" permalink structure to any permalink structure. |
| 15 |
* |
| 16 |
* @param string $url The url that should be migrated. |
| 17 |
* @param string|Null $base_url The base url that should be clean from the url. |
| 18 |
* |
| 19 |
* @return string The migrated url || the $url if it couldn't find a match in the current permalink structure. |
| 20 |
*/ |
| 21 |
public static function migrate( $url, $base_url = '' ) { |
| 22 |
$full_url = $url; |
| 23 |
|
| 24 |
if ( ! empty( $base_url ) ) { |
| 25 |
$base_url = preg_quote( $base_url, '/' ); |
| 26 |
$url = preg_replace( "/^{$base_url}/", '', $url ); |
| 27 |
} |
| 28 |
|
| 29 |
$parsed_url = wp_parse_url( $url ); |
| 30 |
|
| 31 |
if ( $url === $full_url && ! empty( $parsed_url['host'] ) ) { |
| 32 |
return $full_url; |
| 33 |
} |
| 34 |
|
| 35 |
if ( ! empty( $parsed_url['path'] ) ) { |
| 36 |
$page = get_page_by_path( $parsed_url['path'] ); |
| 37 |
|
| 38 |
if ( ! $page ) { |
| 39 |
return $full_url; |
| 40 |
} |
| 41 |
|
| 42 |
$permalink = get_permalink( $page->ID ); |
| 43 |
} |
| 44 |
|
| 45 |
if ( empty( $permalink ) ) { |
| 46 |
return $full_url; |
| 47 |
} |
| 48 |
|
| 49 |
if ( ! empty( $parsed_url['query'] ) ) { |
| 50 |
parse_str( $parsed_url['query'], $parsed_query ); |
| 51 |
|
| 52 |
// Clean WP permalinks query args to prevent collision with the new permalink. |
| 53 |
unset( $parsed_query['p'] ); |
| 54 |
unset( $parsed_query['page_id'] ); |
| 55 |
|
| 56 |
$permalink = add_query_arg( $parsed_query, $permalink ); |
| 57 |
} |
| 58 |
|
| 59 |
if ( ! empty( $parsed_url['fragment'] ) ) { |
| 60 |
$permalink .= '#' . $parsed_url['fragment']; |
| 61 |
} |
| 62 |
|
| 63 |
return wp_make_link_relative( $permalink ); |
| 64 |
} |
| 65 |
} |
| 66 |
|