Created
April 16, 2019 16:32
-
-
Save georgestephanis/5e6a06320792f967fff462081bc30813 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Plugin name: Host Detection | |
/* | |
CREATE TABLE `shared_host_landing` ( | |
`id` int(11) unsigned NOT NULL AUTO_INCREMENT, | |
`host` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'The hosting company', | |
`hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'The md5 hash of the html landing page', | |
`html` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'The html landing page served up when no domain is specified to the shared host', | |
PRIMARY KEY (`id`), | |
UNIQUE KEY `hash` (`hash`) | |
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; | |
*/ | |
function get_host_details_by_url( $url ) { | |
$domain = wp_parse_url( $url, PHP_URL_HOST ); | |
$ips = gethostbynamel( $domain ); // Domains can have multiple A records, let's grab them all. | |
if ( ! $ips ) { | |
return null; | |
} | |
// Return details on the first one we find. | |
foreach ( $ips as $ip ) { | |
$details = get_host_details_by_ip( $ip ); | |
if ( $details ) { | |
return $details; | |
} | |
} | |
return null; | |
} | |
function get_host_details_by_ip( $ip ) { | |
$url = "http://{$ip}"; | |
$response = wp_remote_get( esc_url_raw( $url ) ); | |
$html = wp_remote_retrieve_body( $response ); | |
return check_landing_page_details( $html ); | |
} | |
function check_landing_page_details( $html ) { | |
global $wpdb; | |
// If we want to apply some regex check or something before checking the db, let's give it a shot. | |
$host = apply_filters( 'pre_guess_host_from_landing_page', null, $html ); | |
if ( $host ) { | |
return $host; | |
} | |
$html = trim( $html ); | |
$hash = md5( $html ); | |
$host = $wpdb->get_var( $wpdb->prepare( "SELECT `host` FROM `shared_host_landing` WHERE `hash` = '%s'", $hash ) ); | |
// If it comes back as null, we don't have a record of it, insert. | |
if ( is_null( $host ) ) { | |
// Possibly easier way for other bits of code to recognize the landing page. | |
$host = apply_filters( 'guess_host_from_landing_page', $host, $html ); | |
$wpdb->insert( | |
'shared_host_landing', | |
array( | |
'host' => $host, | |
'hash' => $hash, | |
'html' => $html, | |
) | |
); | |
} | |
return $host; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment