Skip to content

Instantly share code, notes, and snippets.

@costdev
Last active Mar 30, 2022
Embed
What would you like to do?
A small WordPress plugin which attempts to detect VirtualBox.
<?php
/**
* Plugin Name: VirtualBox Detection.
* Description: Attempt to detect VirtualBox.
* Author: WordPress Core Contributors
* Author URI: https://make.wordpress.org/core
* License: GPLv2 or later.
* Version: 1.0.1
* Gist Plugin URI: https://gist.github.com/costdev/75138bbb72f77166e05cf49b5952f821
*/
/**
* Attempt to detect a VirtualBox environment.
*
* This attempts all known methods of detecting VirtualBox.
*
* @global $wp_filesystem The filesystem.
*
* @since 1.0.0
*
* @return bool Whether or not VirtualBox was detected.
*/
function is_virtualbox() {
global $wp_filesystem;
static $is_virtualbox;
if ( $is_virtualbox ) {
return $is_virtualbox;
}
// Detection via filter.
if ( apply_filters( 'is_virtualbox', false ) ) {
$is_virtualbox = 'Detected via filter';
return $is_virtualbox;
}
// Detection via Composer.
if ( function_exists( 'getenv' ) && getenv( 'COMPOSER_RUNTIME_ENV' ) === 'virtualbox' ) {
$is_virtualbox = 'Detected via Composer';
return $is_virtualbox;
}
$virtualbox_unames = array( 'vvv' );
// Detection via `php_uname()`.
if ( function_exists( 'php_uname' ) && in_array( php_uname( 'n' ), $virtualbox_unames, true ) ) {
$is_virtualbox = 'Detected via php_uname()';
return $is_virtualbox;
}
/*
* Vagrant can use alternative providers.
* This isn't reliable without some additional check(s).
*/
$virtualbox_usernames = array( 'vagrant' );
// Detection via user name with POSIX.
if ( function_exists( 'posix_getpwuid' ) && function_exists( 'posix_geteuid' ) ) {
$user = posix_getpwuid( posix_geteuid() );
if ( $user && in_array( $user['name'], $virtualbox_usernames, true ) ) {
$is_virtualbox = 'Detected via posix_getpwuid( posix_geteuid() )';
return $is_virtualbox;
}
}
// Initialize the filesystem if not set.
if ( ! $wp_filesystem ) {
require_once ABSPATH . '/wp-admin/includes/file.php';
WP_Filesystem();
}
// Detection via file owner.
if ( in_array( $wp_filesystem->owner( __FILE__ ), $virtualbox_usernames, true ) ) {
$is_virtualbox = 'Detected via file owner using $wp_filesystem';
return $is_virtualbox;
}
// Detection via file group.
if ( in_array( $wp_filesystem->group( __FILE__ ), $virtualbox_usernames, true ) ) {
$is_virtualbox = 'Detected via file group using $wp_filesystem';
return $is_virtualbox;
}
// Give up.
$is_virtualbox = false;
return $is_virtualbox;
}
add_action( 'admin_notices', 'show_whether_virtualbox' );
function show_whether_virtualbox() {
$is_virtualbox = is_virtualbox();
printf(
'<div class="notice notice-info"><p>%s</p></div>',
$is_virtualbox ? $is_virtualbox . ' - ' . __( 'This site uses VirtualBox.' ) : __( 'This site does not use VirtualBox.' )
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment