diff --git a/CHANGELOG.md b/CHANGELOG.md index 3faffcae0..dca13d629 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ This project adheres to [Semantic Versioning](http://semver.org/). ## [unreleased] Unreleased +### Added + +- The `AirplaneMode` module, based on the `norcross/airplane-mode` plugin, to put the website under test in "airplane mode", preventing it from making any network requests during tests. + ## [4.1.3] 2024-03-13; ### Added diff --git a/bin/update_airplane_mode_plugin b/bin/update_airplane_mode_plugin new file mode 100755 index 000000000..9a418aba3 --- /dev/null +++ b/bin/update_airplane_mode_plugin @@ -0,0 +1,13 @@ +#! /usr/bin/env sh + +set -eu + +script_dir=$(dirname "$0") +root_dir=$(cd "$script_dir/.." && pwd) +plugin_file_src="https://downloads.wordpress.org/plugin/airplane-mode.zip"; +# Download the zip file and unzip it in the includes/airplane-mode directory +curl -L "$plugin_file_src" -o "$root_dir/includes/airplane-mode.zip" +unzip -o "$root_dir/includes/airplane-mode.zip" -d "$root_dir/includes/" +# Remove the zip file +rm "$root_dir/includes/airplane-mode.zip" + diff --git a/bin/update_sqlite_plugin b/bin/update_sqlite_plugin index f21278f94..f7724f1aa 100755 --- a/bin/update_sqlite_plugin +++ b/bin/update_sqlite_plugin @@ -1,6 +1,6 @@ #! /usr/bin/env sh -set -eux +set -eu script_dir=$(dirname "$0") root_dir=$(cd "$script_dir/.." && pwd) diff --git a/docs/modules/AirplaneMode.md b/docs/modules/AirplaneMode.md new file mode 100644 index 000000000..d9109626f --- /dev/null +++ b/docs/modules/AirplaneMode.md @@ -0,0 +1,37 @@ +## AirplaneMode module + +This module allows you to easily put the website under test in "airplane mode", preventing it from making any network requests. + +The module uses the `norcross/airplane-mode` plugin to add or remove it from the website must-use plugins directory when activated. + +This module should be used together with [the `WPWebDriver`][1] or [`WPBrowser`][2] modules. + +## Configuration + +* `muPluginsDir` - **required**; the path to the WordPress must-use plugins directory. +* `symlink` - whether to symlink the plugin or copy it. By default, the plugin is **copied** in the must-use plugins directory and `symlink` is set to `false`. If you're **not** using containers, that will ignore symlinked plugins, you can set `symlink` to `true` to symlink the plugin in the must-use plugins directory. Symbolic linking is faster and uses less disk space than copying the plugin. + +Example configuration to symlink the plugin in the `muPluginsDir` directory before the tests: + +```yaml +modules: + enabled: + lucatume\WPBrowser\Module\AirplaneMode: + muPluginsDir: 'var/wordpress/wp-content/mu-plugins' + symlink: true +``` + +Example configuration to copy the plugin in the `muPluginsDir` directory before the tests: + +```yaml +modules: + enabled: + lucatume\WPBrowser\Module\AirplaneMode: + muPluginsDir: 'var/wordpress/wp-content/mu-plugins' + symlink: false +``` + +The module will either symlink or copy the plugin in the `muPluginsDir` directory, depending on the `symlink` configuration parameter before the test suite runs, and will remove it after the test suite has run. + +[1]: ./WPWebDriver.md +[2]: ./WPBrowser.md diff --git a/includes/airplane-mode/CHANGES.md b/includes/airplane-mode/CHANGES.md new file mode 100755 index 000000000..f7e60f4aa --- /dev/null +++ b/includes/airplane-mode/CHANGES.md @@ -0,0 +1,95 @@ +#### Version 0.2.5 - 2019/11/15 +* Remove usage of method that's been deprecated in WordPress trunk. props @johnbillion + +#### Version 0.2.4 - 2017/12/13 +* Added localhost bypass for loading CSS and JS files when hot reloading. props @shadyvb +* Added additional hook removals for new automated updates and language packs. +* Removed outdated `create_function` call for PHP 7.2 compatibility. props @geminorum +* General cleanup + +#### Version 0.2.3 - 2017/03/05 +* Adding option to force transient purge +* Adding `clean` action to WP-CLI functions + +#### Version 0.2.2 - 2016/12/07 +* Adding WP-CLI support. props @markjaquith + +#### Version 0.2.1 - 2016/10/19 +* Fix settings page language drowdown when used offline. props @onnimonni + +#### Version 0.2.0 - 2016/08/26 +* modify CSS loading for front-end, removed loading for login page. props @barryceelen +* fixed WP.org theme API call request to avoid `WP_Error` return. props @onnimonni + +#### Version 0.1.9 - 2016/07/25 +* prevent BuddyPress from falling back to Gravatar. props @johnbillion + +#### Version 0.1.8 - 2016/07/12 +* allow `JETPACK_DEV_DEBUG` constant to take priority over filter. props @kopepasah +* added additional CSS for upcoming 4.6. change to upload tab. + +#### Version 0.1.7 - 2016/05/18 +* allow local HTTP calls with optional filter. props @johnbillion +* add back index.php link to main dashboard menu item +* bumped minimum WP version requirement to 4.4 + +#### Version 0.1.6 - 2016/04/25 +* minor tweak to include CSS for new icon font + +#### Version 0.1.5 - 2016/04/24 +* adding custom icon font for display and removing label. props @barryceelen + +#### Version 0.1.4 - 2016/02/26 +* better setup for blocked external assets. props @johnbillion + +#### Version 0.1.3 - 2016/02/22 +* modified CSS rules to fix media bulk actions bar from disappearing +* moved `airplane_mode_status_change` action to run before redirect, and now includes the status being run. + +#### Version 0.1.2 - 2016/01/09 +* added back HTTP count when inactive +* removed HTTP count completely when Query Monitor is active + +#### Version 0.1.1 - 2016/01/06 +* fixed incorrect nonce check that was breaking toggle +* changed CSS and JS checks to include all themes and plugins as well as core + +#### Version 0.1.0 - 2015/12/30 +* added `airplane_mode_purge_transients` filter to bypass transient purge + +#### Version 0.0.9 - 2015/12/07 +* changed from colored circle to actual airplane icon for usability +* fixed dashboard link icon for multisite +* changed to exclude all external stylesheets, not just Open Sans +* added language files for translateable goodness +* general cleanup for WP coding standards + +#### Version 0.0.8 - 2015/05/18 +* added `class_exists` as now included in DesktopServer and collisions could result +* fixed `if ( ! defined ...` for `AIRMDE_BASE` constant +* add `.gitattributes` to remove certain files from updates + +#### Version 0.0.7 - 2015/04/21 +* fixed some CSS from hiding plugins page bar +* moved changelog to it's own file +* added `composer.json` +* added contributors to readme +* clarified license (MIT) + +#### Version 0.0.6 - 2015/04/02 +* version bump for GitHub updater + +#### Version 0.0.5 - 2015/04/02 +* fixed bug in update logic that was preventing checks when disabled (but activated). props @johnbillion + +#### Version 0.0.3 - 2015/01/23 +* added `airplane_mode_status_change` hook for functions to fire on status change +* purge update related transients on disable +* added WordPress formatted readme file + +#### Version 0.0.2 - 2015/01/21 +* added GitHub Updater support +* fixed update capabilities when status is disabled + +#### Version 0.0.1 - 2014/06/01 +* lots of stuff. I wasn't keeping a changelog. I apologize. diff --git a/includes/airplane-mode/LICENSE b/includes/airplane-mode/LICENSE new file mode 100755 index 000000000..fbee8163b --- /dev/null +++ b/includes/airplane-mode/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Norcross + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/includes/airplane-mode/README.md b/includes/airplane-mode/README.md new file mode 100755 index 000000000..3b1c3bcac --- /dev/null +++ b/includes/airplane-mode/README.md @@ -0,0 +1,34 @@ +Airplane Mode +======================== + +## Contributors +* [Andrew Norcross](https://github.com/norcross) +* [John Blackbourn](https://github.com/johnbillion) +* [Andy Fragen](https://github.com/afragen) +* [Viktor Szépe](https://github.com/szepeviktor) +* [Chris Christoff](https://github.com/chriscct7) +* [Mark Jaquith](https://github.com/markjaquith) + +## About +Control loading of external files when developing locally. WP loads certain external files (fonts, Gravatar, etc.) and makes external HTTP calls. This isn't usually an issue, unless you're working in an evironment without a web connection. This plugin removes/unhooks those actions to reduce load time and avoid errors due to missing files. + +## Current Actions +* removes external JS and CSS files from loading +* replaces all instances of Gravatar with a local image to remove external call +* removes all HTTP requests +* disables all WP update checks for core, languages, themes, and plugins +* includes toggle in admin bar for quick enable / disable + +## Changelog + +See [CHANGES.md](CHANGES.md). + +## Notes +If you need offline activation, see [this script](https://gist.github.com/solepixel/e1d03f4dcd1b9e86552b3cc6937325bf) written by [Brian DiChiara](https://github.com/solepixel) + +## Roadmap +* fine tune HTTP request removal +* find other calls from core +* add other requests from popular plugins + +#### [Pull requests](https://github.com/norcross/airplane-mode/pulls) are very much welcome and encouraged. diff --git a/includes/airplane-mode/airplane-mode-loader.php b/includes/airplane-mode/airplane-mode-loader.php new file mode 100644 index 000000000..97e7ec71f --- /dev/null +++ b/includes/airplane-mode/airplane-mode-loader.php @@ -0,0 +1,6 @@ +enabled() ) { + + // Allows locally defined JETPACK_DEV_DEBUG constant to override filter. + if ( ! defined( 'JETPACK_DEV_DEBUG' ) ) { + // Keep jetpack from attempting external requests. + add_filter( 'jetpack_development_mode', '__return_true', 9999 ); + } + + // Prevent BuddyPress from falling back to Gravatar avatars. + add_filter( 'bp_core_fetch_avatar_no_grav', '__return_true' ); + + // Disable automatic updater updates. + add_filter( 'automatic_updater_disabled', '__return_true' ); + + // Tell WordPress we are on a version control system to add additional blocks. + add_filter( 'automatic_updates_is_vcs_checkout', '__return_true' ); + + // Disable translation updates. + add_filter( 'auto_update_translation', '__return_false' ); + + // Disable minor core updates. + add_filter( 'allow_minor_auto_core_updates', '__return_false' ); + + // Disable major core updates. + add_filter( 'allow_major_auto_core_updates', '__return_false' ); + + // Disable dev core updates. + add_filter( 'allow_dev_auto_core_updates', '__return_false' ); + + // Disable overall core updates. + add_filter( 'auto_update_core', '__return_false' ); + add_filter( 'wp_auto_update_core', '__return_false' ); + + // Disable automatic plugin and theme updates (used by WP to force push security fixes). + add_filter( 'auto_update_plugin', '__return_false' ); + add_filter( 'auto_update_theme', '__return_false' ); + + // Disable debug emails (used by core for rollback alerts in automatic update deployment). + add_filter( 'automatic_updates_send_debug_email', '__return_false' ); + + // Disable update emails (for when we push the new WordPress versions manually) as well + // as the notification there is a new version emails. + add_filter( 'auto_core_update_send_email', '__return_false' ); + add_filter( 'send_core_update_notification_email', '__return_false' ); + add_filter( 'automatic_updates_send_debug_email ', '__return_false', 1 ); + + // Get rid of the version number in the footer. + add_filter( 'update_footer', '__return_empty_string', 11 ); + + // Filter out the pre core option. + add_filter( 'pre_option_update_core', '__return_null' ); + + // Remove some actions. + remove_action( 'admin_init', 'wp_plugin_update_rows' ); + remove_action( 'admin_init', 'wp_theme_update_rows' ); + remove_action( 'admin_notices', 'maintenance_nag' ); + remove_action( 'init', 'wp_schedule_update_checks' ); + + // Add back the upload tab. + add_action( 'install_themes_upload', 'install_themes_upload', 10, 0 ); + + // Define core contants for more protection. + if ( ! defined( 'AUTOMATIC_UPDATER_DISABLED' ) ) { + define( 'AUTOMATIC_UPDATER_DISABLED', true ); + } + if ( ! defined( 'WP_AUTO_UPDATE_CORE' ) ) { + define( 'WP_AUTO_UPDATE_CORE', false ); + } + } + } + + /** + * If an instance exists, this returns it. If not, it creates one and + * returns it. + * + * @return $instance + */ + public static function getInstance() { + if ( ! self::$instance ) { + self::$instance = new self; + } + + return self::$instance; + } + + /** + * Load our textdomain for localization. + * + * @return void + */ + public function textdomain() { + load_plugin_textdomain( 'airplane-mode', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); + } + + /** + * Set our initial airplane mode setting to 'on' on activation. + */ + public function create_setting() { + add_site_option( 'airplane-mode', 'on' ); + set_transient( 'wporg_theme_feature_list', array(), 999999999999 ); + } + + /** + * Remove our setting on plugin deactivation. + */ + public function remove_setting() { + delete_option( 'airplane-mode' ); + delete_site_option( 'airplane-mode' ); + delete_transient( 'wporg_theme_feature_list' ); + } + + /** + * Helper function to check the current status. + * + * @return bool True if status is 'on'; false if not. + */ + public function enabled() { + + // Bail if CLI. + if ( defined( 'WP_CLI' ) and WP_CLI ) { + return false; + } + + // Pull our status from the options table. + $option = get_site_option( 'airplane-mode' ); + + // Backup check for regular options table. + if ( false === $option ) { + $option = get_option( 'airplane-mode' ); + } + + // Return the option flag. + return 'on' === $option; + } + + /** + * Check the URL of a stylesheet and remove any that are not on the local URL. + * + * @param string $source The source URL of the CSS sheet. + * + * @return string $source The same URL, or null. + */ + public function block_style_load( $source ) { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return $source; + } + + // Parse the URL being passed to pull out the host. + $parsed = parse_url( $source, PHP_URL_HOST ); + + // First run the filter to allow a source host to get through. + if ( false === apply_filters( 'airplane_mode_parse_style', true, $parsed ) ) { + return $source; + } + + // If we don't share the same URL as the site itself, return null. Otherwise return the URL. + return isset( $parsed ) && false === strpos( home_url(), $parsed ) + ? new Airplane_Mode_WP_Error( 'airplane_mode_enabled', __( 'Airplane Mode blocked style', 'airplane-mode' ), array( + 'return' => '', + 'src' => $source, + ) ) + : $source; + } + + /** + * Check the URL of a JS file and remove any that are not on the local URL. + * + * @param string $source The source URL of the JS file. + * + * @return string $source The same URL, or null. + */ + public function block_script_load( $source ) { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return $source; + } + + // Parse the URL being passed to pull out the host. + $parsed = parse_url( $source, PHP_URL_HOST ); + + // First run the filter to allow a source host to get through. + if ( false === apply_filters( 'airplane_mode_parse_script', true, $parsed ) ) { + return $source; + } + + // If we don't share the same URL as the site itself, return null. Otherwise return the URL. + return isset( $parsed ) && false === strpos( home_url(), $parsed ) + ? new Airplane_Mode_WP_Error( 'airplane_mode_enabled', __( 'Airplane Mode blocked script', 'airplane-mode' ), array( + 'return' => '', + 'src' => $source, + ) ) + : $source; + } + + /** + * Use our existing filter to check for local assets. + * + * @param boolean $block Whether to block the specific asset. Defaults to 'true'. + * @param array $parsed The URL of the asset, parsed. + * + * @return boolean + */ + public function bypass_asset_block( $block, $parsed ) { + + // Create an array of the approved local domains. + $local = apply_filters( 'airplane_mode_local_hosts', array( 'localhost', '127.0.0.1' ) ); + + // If our parsed URL host is in that array, return false. Otherwise, return our blocking choice. + return ! empty( $local ) && in_array( $parsed, $local ) ? false : $block; + } + + /** + * Block oEmbeds from displaying. + * + * @param string $html The embed HTML. + * @param string $url The attempted embed URL. + * @param array $attr An array of shortcode attributes. + * @param int $post_ID Post ID. + * + * @return string + */ + public function block_oembed_html( $html, $url, $attr, $post_ID ) { + return $this->enabled() ? sprintf( '

%s

', sprintf( __( 'Airplane Mode is enabled. oEmbed blocked for %1$s.', 'airplane-mode' ), esc_url( $url ) ) ) : $html; + } + + /** + * Add body class to front-end pages and login based on plugin status. + * + * @param array $classes The existing array of body classes. + * + * @return array $classes The updated array of body classes. + */ + public function body_class( $classes ) { + + // Add the class based on the current status. + $classes[] = $this->enabled() ? 'airplane-mode-enabled' : 'airplane-mode-disabled'; + + // Also add in the margin setup for Query Monitor because I'm a perfectionist. + if ( ! class_exists( 'QueryMonitor' ) || defined( 'QM_DISABLED' ) && QM_DISABLED ) { + $classes[] = 'airplane-mode-no-qm'; + } + + // Return our array of classes. + return $classes; + } + + /** + * Add body class to admin pages based on plugin status. + * + * @param string $classes The existing space-separated list of CSS classes. + * + * @return string $classes The updated space-separated list of CSS classes. + */ + public function admin_body_class( $classes ) { + + // First add the standard set of classes based on status. + $classes .= $this->enabled() ? ' airplane-mode-enabled' : ' airplane-mode-disabled'; + + // Also add in the margin setup for Query Monitor because I'm a perfectionist. + if ( ! class_exists( 'QueryMonitor' ) || defined( 'QM_DISABLED' ) && QM_DISABLED ) { + $classes .= ' airplane-mode-no-qm'; + } + + // Return our string of classes. + return $classes; + } + + /** + * Remove menu items for updates from a standard WP install. + * + * @return null + */ + public function admin_menu_items() { + + // Bail if disabled, or on a multisite. + if ( ! $this->enabled() || is_multisite() ) { + return; + } + + // Remove our items. + remove_submenu_page( 'index.php', 'update-core.php' ); + } + + /** + * Remove menu items for updates from a multisite instance. + * + * @return null + */ + public function ms_admin_menu_items() { + + // Bail if disabled or not on our network admin. + if ( ! $this->enabled() || ! is_network_admin() ) { + return; + } + + // Remove the items. + remove_submenu_page( 'index.php', 'upgrade.php' ); + } + + /** + * Replace all instances of gravatar with a local image file + * to remove the call to remote service. + * + * @param string $avatar Image tag for the user's avatar. + * @param int|object|string $id_or_email A user ID, email address, or comment object. + * @param int $size Square avatar width and height in pixels to retrieve. + * @param string $default URL to a default image to use if no avatar is available. + * @param string $alt Alternative text to use in the avatar image tag. + * + * @return string `` tag for the user's avatar. + */ + public function replace_gravatar( $avatar, $id_or_email, $size, $default, $alt ) { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return $avatar; + } + + // Swap out the file for a base64 encoded image. + $image = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; + $avatar = "{$alt}"; + + // Return the avatar. + return $avatar; + } + + /** + * Remove avatar images from the default avatar list. + * + * @param string $avatar_list List of default avatars. + * + * @return string Updated list with images removed. + */ + public function default_avatar( $avatar_list ) { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return $avatar_list; + } + + // Remove images. + $avatar_list = preg_replace( '|]+)> |i', '', $avatar_list ); + + // Send back the list. + return $avatar_list; + } + + /** + * Disable all the HTTP requests being made with the action + * happening before the status check so others can allow certain + * items as desired. + * + * @param bool|array|WP_Error $status Whether to preempt an HTTP request return. Default false. + * @param array $args HTTP request arguments. + * @param string $url The request URL. + * + * @return bool|array|WP_Error A WP_Error object if Airplane Mode is enabled. Original $status if not. + */ + public function disable_http_reqs( $status = false, $args = array(), $url = '' ) { + + // Pass our data to the action to allow a bypass. + do_action( 'airplane_mode_http_args', $status, $args, $url ); + + if ( ! $this->enabled() ) { + return $status; + } + + $url_host = parse_url( $url, PHP_URL_HOST ); + + // Allow the request to pass through if the URL host matches the site's host. + if ( $url_host && parse_url( home_url(), PHP_URL_HOST ) === $url_host ) { + + // But allow this to be disabled via a filter. + if ( apply_filters( 'airplane_mode_allow_local_bypass', true, $url, $args ) ) { + return $status; + } + } + + // Allow certain HTTP API requests to pass through via a filter. + if ( apply_filters( 'airplane_mode_allow_http_api_request', false, $url, $args, $url_host ) ) { + return $status; + } + + // Disable the http requests if enabled. + return new WP_Error( 'airplane_mode_enabled', __( 'Airplane Mode is enabled', 'airplane-mode' ) ); + } + + /** + * Load our small CSS file for the toggle switch. + */ + public function toggle_css() { + + // Don't display CSS on the front-end if the admin bar is not loading. + if ( ! is_admin() && ! is_admin_bar_showing() ) { + return; + } + + // Set a suffix for loading the minified or normal. + $file = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? 'airplane-mode.css' : 'airplane-mode.min.css'; + + // Set a version for browser caching. + $vers = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? time() : AIRMDE_VER; + + // Load the CSS file itself. + wp_enqueue_style( 'airplane-mode', plugins_url( '/lib/css/' . $file, __FILE__ ), array(), $vers, 'all' ); + } + + /** + * Sets the mode. + * + * @param string $mode Desired mode ('on' or 'off'). + * + * @return bool Whether the setting changed. + */ + public function set_mode( $mode = 'on' ) { + + // Check what mode we're currently in, with "on" as a fallback. + if ( ! in_array( $mode, array( 'on', 'off' ) ) ) { + $mode = 'on'; + } + + // Update the setting. + $return = update_site_option( 'airplane-mode', $mode ); + + // Fire action to allow for functions to run on status change. + do_action( 'airplane_mode_status_change', $mode ); + + // And return the status we just set. + return $return; + } + + /** + * Enables airplane mode. + * + * @return bool Whether the setting changed. + */ + public function enable() { + return self::set_mode( 'on' ); + } + + /** + * Disables airplane mode. + * + * @return bool Whether the setting changed. + */ + public function disable() { + return self::set_mode( 'off' ); + } + + /** + * Check the user action from the toggle switch to set the option + * to 'on' or 'off'. + * + * @return void If any of the sanity checks fail and we bail early. + */ + public function toggle_check() { + + // Bail if current user doesn't have cap. + if ( ! current_user_can( 'manage_options' ) ) { + return; + } + + // Set a sanitized variable of our potential nonce and request. + $nonce = isset( $_GET['airmde_nonce'] ) ? sanitize_key( $_GET['airmde_nonce'] ) : ''; + $switch = isset( $_REQUEST['airplane-mode'] ) ? sanitize_key( $_REQUEST['airplane-mode'] ) : ''; + + // Check for our nonce. + if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'airmde_nonce' ) ) { + return; + } + + // Now check for our query string. + if ( empty( $switch ) || ! in_array( $switch, array( 'on', 'off' ) ) ) { + return; + } + + // Delete old per-site option. + delete_option( 'airplane-mode' ); + + // Set our mode based on the toggle action. + self::set_mode( $switch ); + + // And go about our business. + wp_redirect( self::get_redirect() ); + exit; + } + + /** + * Fetch the URL to redirect to after toggling Airplane Mode. + * + * @return string The URL to redirect to. + */ + protected static function get_redirect() { + + // Return the args for the actual redirect. + $redirect = remove_query_arg( array( + 'airplane-mode', + 'airmde_nonce', + 'user_switched', + 'switched_off', + 'switched_back', + 'message', + 'update', + 'updated', + 'settings-updated', + 'saved', + 'activated', + 'activate', + 'deactivate', + 'enabled', + 'disabled', + 'locked', + 'skipped', + 'deleted', + 'trashed', + 'untrashed', + 'force-check', + ) ); + + // Redirect away from the update core page. + $redirect = str_replace( 'update-core.php', '', $redirect ); + + // And return the redirect. + return apply_filters( 'airplane_mode_redirect_url', $redirect ); + } + + /** + * Add our quick toggle to the admin bar to enable / disable. + * + * @param WP_Admin_Bar $wp_admin_bar The admin bar object. + * + * @return void if current user can't manage options and we bail early. + */ + public function admin_bar_toggle( WP_Admin_Bar $wp_admin_bar ) { + + // Bail if current user doesn't have cap. + if ( ! current_user_can( 'manage_options' ) ) { + return; + } + + // Get the current status. + $status = $this->enabled(); + + // Set a title message (translatable). + $title = $status ? __( 'Airplane Mode is enabled.', 'airplane-mode' ) : __( 'Airplane Mode is disabled.', 'airplane-mode' ); + + // Set our toggle variable parameter (in reverse since we want the opposite action). + $toggle = $status ? 'off' : 'on'; + + // Set my HTTP request count label to a blank string for now. + $label = ''; + + // Get and display the HTTP count when Query Monitor isn't active. + if ( ! class_exists( 'QueryMonitor' ) || defined( 'QM_DISABLED' ) && QM_DISABLED ) { + + // Pull my HTTP count. + $count = ! empty( $this->http_count ) ? number_format_i18n( $this->http_count ) : 0; + + $count_label = sprintf( _n( 'There was %s HTTP request.', 'There were %s HTTP requests.', $count, 'airplane-mode' ), $count ); + + // Build the markup for my label. + $label = ''; + $label .= '' . esc_html( $count_label ) . ''; + + // Amend the tooltip title with the count. + $title .= ' ' . $count_label; + } + + // Get our link with the status parameter. + $link = wp_nonce_url( add_query_arg( 'airplane-mode', $toggle ), 'airmde_nonce', 'airmde_nonce' ); + + // Now add the admin bar link. + $wp_admin_bar->add_node( + array( + 'id' => 'airplane-mode-toggle', + 'title' => '' . $label, + 'href' => esc_url( $link ), + 'position' => 0, + 'meta' => array( + 'title' => $title, + ), + ) + ); + } + + /** + * Filter a user's meta capabilities to prevent auto-updates from being attempted. + * + * @param array $caps Returns the user's actual capabilities. + * @param string $cap Capability name. + * + * @return array The user's filtered capabilities. + */ + public function prevent_auto_updates( $caps, $cap ) { + + // Check for being enabled and look for specific cap requirements. + if ( $this->enabled() && in_array( $cap, array( 'update_plugins', 'update_themes', 'update_core' ) ) ) { + $caps[] = 'do_not_allow'; + } + + // Send back the data array. + return $caps; + } + + /** + * Check the new status after airplane mode has been enabled or + * disabled and purge related transients. + * + * @param boolean $force Whether to force the purge. + * + * @return void + */ + public function purge_transients( $force = false ) { + + // First check for the filter to avoid this action overall. + if ( empty( $force ) && false === $clear = apply_filters( 'airplane_mode_purge_transients', true ) ) { + return; + } + + // Purge the transients related to updates when disabled or the force is called. + if ( ! $this->enabled() || ! empty( $force ) ) { + delete_site_transient( 'update_core' ); + delete_site_transient( 'update_plugins' ); + delete_site_transient( 'update_themes' ); + delete_site_transient( 'wporg_theme_feature_list' ); + } + } + + /** + * Remove all the various places WP does the update checks. As you can see there are a lot of them. + * + * @return null + */ + public function remove_update_crons() { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return; + } + + // Do a quick check to make sure we can remove things. + if ( ! function_exists( 'remove_action' ) ) { + return; + } + + // Disable Theme Updates. + remove_action( 'load-update-core.php', 'wp_update_themes' ); + remove_action( 'load-themes.php', 'wp_update_themes' ); + remove_action( 'load-update.php', 'wp_update_themes' ); + remove_action( 'wp_update_themes', 'wp_update_themes' ); + remove_action( 'admin_init', '_maybe_update_themes' ); + + // Disable Plugin Updates. + remove_action( 'load-update-core.php', 'wp_update_plugins' ); + remove_action( 'load-plugins.php', 'wp_update_plugins' ); + remove_action( 'load-update.php', 'wp_update_plugins' ); + remove_action( 'wp_update_plugins', 'wp_update_plugins' ); + remove_action( 'admin_init', '_maybe_update_plugins' ); + + // Disable Core updates + + // Don't look for WordPress updates. Seriously! + remove_action( 'wp_version_check', 'wp_version_check' ); + remove_action( 'admin_init', '_maybe_update_core' ); + + // Not even maybe. + remove_action( 'wp_maybe_auto_update', 'wp_maybe_auto_update' ); + remove_action( 'admin_init', 'wp_maybe_auto_update' ); + remove_action( 'admin_init', 'wp_auto_update_core' ); + + // Don't forget when the language packs do it. + remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 ); + remove_action( 'upgrader_process_complete', 'wp_version_check' ); + remove_action( 'upgrader_process_complete', 'wp_update_plugins' ); + remove_action( 'upgrader_process_complete', 'wp_update_themes' ); + } + + /** + * Remove all the various schedule hooks for themes, plugins, etc. + * + * @return null + */ + public function remove_schedule_hook() { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return; + } + + // Clear all my hooks. + wp_clear_scheduled_hook( 'wp_update_themes' ); + wp_clear_scheduled_hook( 'wp_update_plugins' ); + wp_clear_scheduled_hook( 'wp_version_check' ); + wp_clear_scheduled_hook( 'wp_maybe_auto_update' ); + } + + /** + * Override the API call made for pulling themes from the .org repo. + * + * @param false|object|array $override Whether to override the WordPress.org Themes API. Default false. + * @param string $action Requested action. Likely values are 'theme_information', + * 'feature_list', or 'query_themes'. + * @param object $args Arguments used to query for installer pages from the Themes API. + * + * @return bool True if enabled, otherwise the existng value. + */ + public function bypass_theme_api_call( $override, $action, $args ) { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return $override; + } + + // Return false on feature list to avoid the API call. + return ! empty( $action ) && 'feature_list' === $action ? true : $override; + } + + /** + * Hijack the expected themes API result. + * + * @param array|object|WP_Error $res WordPress.org Themes API response. + * @param string $action Requested action. Likely values are 'theme_information', + * 'feature_list', or 'query_themes'. + * @param object $args Arguments used to query for installer pages from the WordPress.org Themes API. + * + * @return bool An empty array if enabled, otherwise the existng result. + */ + public function bypass_theme_api_result( $res, $action, $args ) { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return $res; + } + + // Return false on feature list to avoid the API call. + return ! empty( $action ) && in_array( $action, array( 'feature_list', 'query_themes' ) ) ? array() : $res; + } + + /** + * Always send back that the latest version of WordPress is the one we're running + * + * @return object the modified output with our information + */ + public function last_checked_core() { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return false; + } + + // Call the global WP version. + global $wp_version; + + // Return our object. + return (object) array( + 'last_checked' => time(), + 'updates' => array(), + 'version_checked' => $wp_version, + ); + } + + /** + * Always send back that the latest version of our theme is the one we're running + * + * @return object the modified output with our information + */ + public function last_checked_themes() { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return false; + } + + // Call the global WP version. + global $wp_version; + + // Set a blank data array. + $data = array(); + + // Build my theme data array. + foreach ( wp_get_themes() as $theme ) { + $data[ $theme->get_stylesheet() ] = $theme->get( 'Version' ); + } + + // Return our object. + return (object) array( + 'last_checked' => time(), + 'updates' => array(), + 'version_checked' => $wp_version, + 'checked' => $data, + ); + } + + /** + * Always send back that the latest version of our plugins are the one we're running + * + * @return object the modified output with our information + */ + public function last_checked_plugins() { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return false; + } + + // Call the global WP version. + global $wp_version; + + // Set a blank data array. + $data = array(); + + // Add our plugin file if we don't have it. + if ( ! function_exists( 'get_plugins' ) ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + } + + // Build my plugin data array. + foreach ( get_plugins() as $file => $pl ) { + $data[ $file ] = $pl['Version']; + } + + // Return our object. + return (object) array( + 'last_checked' => time(), + 'updates' => array(), + 'version_checked' => $wp_version, + 'checked' => $data, + ); + } + + /** + * Filter for languages list transient. Returns locally available translations + * to avoid request into wp.org translation API. + * + * @param mixed $translations Translation data returned from transient API. + * + * @return array List of available languages. + */ + public function available_translations( $translations ) { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return $translations; + } + + /** + * If transient still contains list of languages just use those. + * Otherwise fallback to mimicked data which we create here. + */ + if ( $translations && ! empty( $translations ) ) { + return $translations; + } else { + $installed_languages = get_available_languages(); + return $this->get_offline_languages( $installed_languages ); + } + } + + /** + * Returns list of languages installed locally with full mimicked meta data. + * + * @param array $installed_languages List of locally available languages. + * + * @return array List of available languages in offline mode. + */ + private function get_offline_languages( $installed_languages ) { + + // This is list of languages which are available from translations API. + $offline_languages = $this->get_offline_translation_information(); + + // Call the global WP version. + global $wp_version; + + // Tell WordPress that all translations are recent even though they can be old. + $date = date_i18n( 'Y-m-d H:is' , time() ); + + // Set an empty array of the available languages. + $available_languages = array(); + + // Loop through our installed languages. + foreach ( $installed_languages as $lang ) { + + // Try to mimick the data that WordPress puts into 'available_translations' transient. + $settings = array( + 'language' => $lang, + 'iso' => array( $lang ), + 'version' => $wp_version, + 'updated' => $date, + 'strings' => array( + 'continue' => __( 'Continue' ), + ), + 'package' => "https://downloads.wordpress.org/translation/core/{$wp_version}/{$lang}.zip", + ); + + // Combine the mimicked data with data we have stored in $offline_languages to give realistic output. + if ( isset( $offline_languages[ $lang ] ) ) { + $available_languages[ $lang ] = array_merge( $settings, $offline_languages[ $lang ] ); + } + } + + // And return our language sets. + return $available_languages; + } + + /** + * We can't use wp_get_available_translations() offine. + * This function tries to return something similiar. + * + * @return array List of wordpress language meta data. + */ + private function get_offline_translation_information() { + + // Build out the list of languages to use. + $languages = array( + 'af' => array( 'english_name' => 'Afrikaans', 'native_name' => 'Afrikaans' ), + 'ar' => array( 'english_name' => 'Arabic', 'native_name' => 'العربية' ), + 'ary' => array( 'english_name' => 'Moroccan Arabic', 'native_name' => 'العربية المغربية' ), + 'as' => array( 'english_name' => 'Assamese', 'native_name' => 'অসমীয়া' ), + 'az' => array( 'english_name' => 'Azerbaijani', 'native_name' => 'Azərbaycan dili' ), + 'azb' => array( 'english_name' => 'South Azerbaijani', 'native_name' => 'گؤنئی آذربایجان' ), + 'bel' => array( 'english_name' => 'Belarusian', 'native_name' => 'Беларуская мова' ), + 'bg_BG' => array( 'english_name' => 'Bulgarian', 'native_name' => 'Български' ), + 'bn_BD' => array( 'english_name' => 'Bengali', 'native_name' => 'বাংলা' ), + 'bo' => array( 'english_name' => 'Tibetan', 'native_name' => 'བོད་ཡིག' ), + 'bs_BA' => array( 'english_name' => 'Bosnian', 'native_name' => 'Bosanski' ), + 'ca' => array( 'english_name' => 'Catalan', 'native_name' => 'Català' ), + 'ceb' => array( 'english_name' => 'Cebuano', 'native_name' => 'Cebuano' ), + 'ckb' => array( 'english_name' => 'Kurdish (Sorani)', 'native_name' => 'كوردی‎' ), + 'cs_CZ' => array( 'english_name' => 'Czech', 'native_name' => 'Čeština‎' ), + 'cy' => array( 'english_name' => 'Welsh', 'native_name' => 'Cymraeg' ), + 'da_DK' => array( 'english_name' => 'Danish', 'native_name' => 'Dansk' ), + 'de_DE_formal' => array( 'english_name' => 'German (Formal)', 'native_name' => 'Deutsch (Sie)' ), + 'de_DE' => array( 'english_name' => 'German', 'native_name' => 'Deutsch' ), + 'de_CH_informal' => array( 'english_name' => 'German (Switzerland, Informal)', 'native_name' => 'Deutsch (Schweiz, Du)' ), + 'de_CH' => array( 'english_name' => 'German (Switzerland)', 'native_name' => 'Deutsch (Schweiz)' ), + 'dzo' => array( 'english_name' => 'Dzongkha', 'native_name' => 'རྫོང་ཁ' ), + 'el' => array( 'english_name' => 'Greek', 'native_name' => 'Ελληνικά' ), + 'en_CA' => array( 'english_name' => 'English (Canada)', 'native_name' => 'English (Canada)' ), + 'en_ZA' => array( 'english_name' => 'English (South Africa)', 'native_name' => 'English (South Africa)' ), + 'en_AU' => array( 'english_name' => 'English (Australia)', 'native_name' => 'English (Australia)' ), + 'en_NZ' => array( 'english_name' => 'English (New Zealand)', 'native_name' => 'English (New Zealand)' ), + 'en_GB' => array( 'english_name' => 'English (UK)', 'native_name' => 'English (UK)' ), + 'eo' => array( 'english_name' => 'Esperanto', 'native_name' => 'Esperanto' ), + 'es_CL' => array( 'english_name' => 'Spanish (Chile)', 'native_name' => 'Español de Chile' ), + 'es_AR' => array( 'english_name' => 'Spanish (Argentina)', 'native_name' => 'Español de Argentina' ), + 'es_PE' => array( 'english_name' => 'Spanish (Peru)', 'native_name' => 'Español de Perú' ), + 'es_MX' => array( 'english_name' => 'Spanish (Mexico)', 'native_name' => 'Español de México' ), + 'es_CO' => array( 'english_name' => 'Spanish (Colombia)', 'native_name' => 'Español de Colombia' ), + 'es_ES' => array( 'english_name' => 'Spanish (Spain)', 'native_name' => 'Español' ), + 'es_VE' => array( 'english_name' => 'Spanish (Venezuela)', 'native_name' => 'Español de Venezuela' ), + 'es_GT' => array( 'english_name' => 'Spanish (Guatemala)', 'native_name' => 'Español de Guatemala' ), + 'et' => array( 'english_name' => 'Estonian', 'native_name' => 'Eesti' ), + 'eu' => array( 'english_name' => 'Basque', 'native_name' => 'Euskara' ), + 'fa_IR' => array( 'english_name' => 'Persian', 'native_name' => 'فارسی' ), + 'fi' => array( 'english_name' => 'Finnish', 'native_name' => 'Suomi' ), + 'fr_BE' => array( 'english_name' => 'French (Belgium)', 'native_name' => 'Français de Belgique' ), + 'fr_FR' => array( 'english_name' => 'French (France)', 'native_name' => 'Français' ), + 'fr_CA' => array( 'english_name' => 'French (Canada)', 'native_name' => 'Français du Canada' ), + 'gd' => array( 'english_name' => 'Scottish Gaelic', 'native_name' => 'Gàidhlig' ), + 'gl_ES' => array( 'english_name' => 'Galician', 'native_name' => 'Galego' ), + 'gu' => array( 'english_name' => 'Gujarati', 'native_name' => 'ગુજરાતી' ), + 'haz' => array( 'english_name' => 'Hazaragi', 'native_name' => 'هزاره گی' ), + 'he_IL' => array( 'english_name' => 'Hebrew', 'native_name' => 'עִבְרִית' ), + 'hi_IN' => array( 'english_name' => 'Hindi', 'native_name' => 'हिन्दी' ), + 'hr' => array( 'english_name' => 'Croatian', 'native_name' => 'Hrvatski' ), + 'hu_HU' => array( 'english_name' => 'Hungarian', 'native_name' => 'Magyar' ), + 'hy' => array( 'english_name' => 'Armenian', 'native_name' => 'Հայերեն' ), + 'id_ID' => array( 'english_name' => 'Indonesian', 'native_name' => 'Bahasa Indonesia' ), + 'is_IS' => array( 'english_name' => 'Icelandic', 'native_name' => 'Íslenska' ), + 'it_IT' => array( 'english_name' => 'Italian', 'native_name' => 'Italiano' ), + 'ja' => array( 'english_name' => 'Japanese', 'native_name' => '日本語' ), + 'ka_GE' => array( 'english_name' => 'Georgian', 'native_name' => 'ქართული' ), + 'kab' => array( 'english_name' => 'Kabyle', 'native_name' => 'Taqbaylit' ), + 'km' => array( 'english_name' => 'Khmer', 'native_name' => 'ភាសាខ្មែរ' ), + 'ko_KR' => array( 'english_name' => 'Korean', 'native_name' => '한국어' ), + 'lo' => array( 'english_name' => 'Lao', 'native_name' => 'ພາສາລາວ' ), + 'lt_LT' => array( 'english_name' => 'Lithuanian', 'native_name' => 'Lietuvių kalba' ), + 'lv' => array( 'english_name' => 'Latvian', 'native_name' => 'Latviešu valoda' ), + 'mk_MK' => array( 'english_name' => 'Macedonian', 'native_name' => 'Македонски јазик' ), + 'ml_IN' => array( 'english_name' => 'Malayalam', 'native_name' => 'മലയാളം' ), + 'mn' => array( 'english_name' => 'Mongolian', 'native_name' => 'Монгол' ), + 'mr' => array( 'english_name' => 'Marathi', 'native_name' => 'मराठी' ), + 'ms_MY' => array( 'english_name' => 'Malay', 'native_name' => 'Bahasa Melayu' ), + 'my_MM' => array( 'english_name' => 'Myanmar (Burmese)', 'native_name' => 'ဗမာစာ' ), + 'nb_NO' => array( 'english_name' => 'Norwegian (Bokmål)', 'native_name' => 'Norsk bokmål' ), + 'ne_NP' => array( 'english_name' => 'Nepali', 'native_name' => 'नेपाली' ), + 'nl_BE' => array( 'english_name' => 'Dutch (Belgium)', 'native_name' => 'Nederlands (België)' ), + 'nl_NL' => array( 'english_name' => 'Dutch', 'native_name' => 'Nederlands' ), + 'nl_NL_formal' => array( 'english_name' => 'Dutch (Formal)', 'native_name' => 'Nederlands (Formeel)' ), + 'nn_NO' => array( 'english_name' => 'Norwegian (Nynorsk)', 'native_name' => 'Norsk nynorsk' ), + 'oci' => array( 'english_name' => 'Occitan', 'native_name' => 'Occitan' ), + 'pa_IN' => array( 'english_name' => 'Punjabi', 'native_name' => 'ਪੰਜਾਬੀ' ), + 'pl_PL' => array( 'english_name' => 'Polish', 'native_name' => 'Polski' ), + 'ps' => array( 'english_name' => 'Pashto', 'native_name' => 'پښتو' ), + 'pt_BR' => array( 'english_name' => 'Portuguese (Brazil)', 'native_name' => 'Português do Brasil' ), + 'pt_PT' => array( 'english_name' => 'Portuguese (Portugal)', 'native_name' => 'Português' ), + 'rhg' => array( 'english_name' => 'Rohingya', 'native_name' => 'Ruáinga' ), + 'ro_RO' => array( 'english_name' => 'Romanian', 'native_name' => 'Română' ), + 'ru_RU' => array( 'english_name' => 'Russian', 'native_name' => 'Русский' ), + 'sah' => array( 'english_name' => 'Sakha', 'native_name' => 'Сахалыы' ), + 'si_LK' => array( 'english_name' => 'Sinhala', 'native_name' => 'සිංහල' ), + 'sk_SK' => array( 'english_name' => 'Slovak', 'native_name' => 'Slovenčina' ), + 'sl_SI' => array( 'english_name' => 'Slovenian', 'native_name' => 'Slovenščina' ), + 'sq' => array( 'english_name' => 'Albanian', 'native_name' => 'Shqip' ), + 'sr_RS' => array( 'english_name' => 'Serbian', 'native_name' => 'Српски језик' ), + 'sv_SE' => array( 'english_name' => 'Swedish', 'native_name' => 'Svenska' ), + 'szl' => array( 'english_name' => 'Silesian', 'native_name' => 'Ślōnskŏ gŏdka' ), + 'ta_IN' => array( 'english_name' => 'Tamil', 'native_name' => 'தமிழ்' ), + 'tah' => array( 'english_name' => 'Tahitian', 'native_name' => 'Reo Tahiti' ), + 'te' => array( 'english_name' => 'Telugu', 'native_name' => 'తెలుగు' ), + 'th' => array( 'english_name' => 'Thai', 'native_name' => 'ไทย' ), + 'tl' => array( 'english_name' => 'Tagalog', 'native_name' => 'Tagalog' ), + 'tr_TR' => array( 'english_name' => 'Turkish', 'native_name' => 'Türkçe' ), + 'tt_RU' => array( 'english_name' => 'Tatar', 'native_name' => 'Татар теле' ), + 'ug_CN' => array( 'english_name' => 'Uighur', 'native_name' => 'Uyƣurqə' ), + 'uk' => array( 'english_name' => 'Ukrainian', 'native_name' => 'Українська' ), + 'ur' => array( 'english_name' => 'Urdu', 'native_name' => 'اردو' ), + 'uz_UZ' => array( 'english_name' => 'Uzbek', 'native_name' => 'O‘zbekcha' ), + 'vi' => array( 'english_name' => 'Vietnamese', 'native_name' => 'Tiếng Việt' ), + 'zh_CN' => array( 'english_name' => 'Chinese (China)', 'native_name' => '简体中文' ), + 'zh_HK' => array( 'english_name' => 'Chinese (Hong Kong)', 'native_name' => '香港中文版' ), + 'zh_TW' => array( 'english_name' => 'Chinese (Taiwan)', 'native_name' => '繁體中文' ), + ); + + // Allow adding or removing languages. + return apply_filters( 'airplane_mode_offline_languages', $languages ); + } + + /** + * Return an empty array of items requiring update for both themes and plugins + * + * @param array $items All the items being passed for update. + * + * @return array An empty array, or the original items if not enabled. + */ + public function remove_update_array( $items ) { + return ! $this->enabled() ? $items : array(); + } + + /** + * Remove the ability to update plugins/themes from single + * site and multisite bulk actions + * + * @param array $actions All the bulk actions. + * + * @return array $actions The remaining actions + */ + public function remove_bulk_actions( $actions ) { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return $actions; + } + + // Set an array of items to be removed with optional filter. + if ( false === $remove = apply_filters( 'airplane_mode_bulk_items', array( 'update-selected', 'update', 'upgrade' ) ) ) { + return $actions; + } + + // Loop the item array and unset each. + foreach ( $remove as $key ) { + unset( $actions[ $key ] ); + } + + // Return the remaining. + return $actions; + } + + /** + * Remove the tabs on the plugin page to add new items + * since they require the WP connection and will fail. + * + * @param array $nonmenu_tabs All the tabs displayed. + * @return array $nonmenu_tabs The remaining tabs. + */ + public function plugin_add_tabs( $nonmenu_tabs ) { + + // Bail if disabled. + if ( ! $this->enabled() ) { + return $nonmenu_tabs; + } + + // Set an array of tabs to be removed with optional filter. + if ( false === $remove = apply_filters( 'airplane_mode_bulk_items', array( 'featured', 'popular', 'recommended', 'favorites', 'beta' ) ) ) { + return $nonmenu_tabs; + } + + // Loop the item array and unset each. + foreach ( $remove as $key ) { + unset( $nonmenu_tabs[ $key ] ); + } + + // Return the tabs. + return $nonmenu_tabs; + } + + /** + * Increase HTTP request counter by one. + * + * @return void + */ + public function count_http_requests() { + $this->http_count++; + } + + // End class. + } + +} // End class_exists. + +if ( ! class_exists( 'Airplane_Mode_WP_Error' ) ) { + + /** + * Extend the WP_Error class to include our own. + */ + class Airplane_Mode_WP_Error extends WP_Error { + + /** + * Get our error data and return it. + * + * @return string + */ + public function __tostring() { + $data = $this->get_error_data(); + return $data['return']; + } + + // End class. + } + +} + +// Instantiate our class. +$Airplane_Mode_Core = Airplane_Mode_Core::getInstance(); diff --git a/includes/airplane-mode/inc/wp-cli.php b/includes/airplane-mode/inc/wp-cli.php new file mode 100755 index 000000000..a1962b4ff --- /dev/null +++ b/includes/airplane-mode/inc/wp-cli.php @@ -0,0 +1,66 @@ +enable(); + WP_CLI::success( __( 'Airplane mode was enabled', 'airplane-mode' ) ); + } + + /** + * Disables airplane mode. + * + * ## EXAMPLES + * + * wp airplane-mode disable + * + * @when after_wp_load + * @subcommand off + * @alias disable + */ + function disable() { + Airplane_Mode_Core::getInstance()->disable(); + WP_CLI::success( __( 'Airplane mode was disabled', 'airplane-mode' ) ); + } + + /** + * Provides the status of airplane mode. + * + * ## EXAMPLES + * + * wp airplane-mode status + * + * @when after_wp_load + */ + function status() { + $on = 'on' === get_site_option( 'airplane-mode' ); + WP_CLI::success( $on ? __( 'Airplane mode is enabled', 'airplane-mode' ) : __( 'Airplane mode is disabled', 'airplane-mode' ) ); + } + + /** + * Purge the transients set from airplane mode. + * + * ## EXAMPLES + * + * wp airplane-mode clean + * + * @when after_wp_load + */ + function clean() { + Airplane_Mode_Core::getInstance()->purge_transients( true ); + WP_CLI::success( __( 'Transients have been cleared', 'airplane-mode' ) ); + } +} + +WP_CLI::add_command( 'airplane-mode', 'Airplane_Mode_Command' ); diff --git a/includes/airplane-mode/languages/default.mo b/includes/airplane-mode/languages/default.mo new file mode 100755 index 000000000..e9b727133 Binary files /dev/null and b/includes/airplane-mode/languages/default.mo differ diff --git a/includes/airplane-mode/languages/default.po b/includes/airplane-mode/languages/default.po new file mode 100755 index 000000000..a8f37ed3d --- /dev/null +++ b/includes/airplane-mode/languages/default.po @@ -0,0 +1,47 @@ +msgid "" +msgstr "" +"Project-Id-Version: Airplane Mode\n" +"POT-Creation-Date: 2015-12-07 17:24-0500\n" +"PO-Revision-Date: 2015-12-07 17:25-0500\n" +"Last-Translator: Andrew Norcross \n" +"Language-Team: \n" +"Language: en_US\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 1.8.6\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: _;__;_e;_n\n" +"X-Poedit-SearchPath-0: .\n" + +#: airplane-mode.php:365 +#, php-format +msgid "Airplane Mode is enabled. oEmbed blocked for %1$s." +msgstr "Airplane Mode is enabled. oEmbed blocked for %1$s." + +#: airplane-mode.php:475 +msgid "Airplane Mode is enabled" +msgstr "Airplane Mode is enabled" + +#: airplane-mode.php:583 +msgid "Airplane Mode is enabled." +msgstr "Airplane Mode is enabled." + +#: airplane-mode.php:583 +msgid "Airplane Mode is disabled." +msgstr "Airplane Mode is disabled." + +#: airplane-mode.php:592 +msgid "Active" +msgstr "Active" + +#: airplane-mode.php:592 +msgid "Inactive" +msgstr "Inactive" + +#: airplane-mode.php:609 +#, php-format +msgid "There was %s HTTP request." +msgstr "There was %s HTTP request." diff --git a/includes/airplane-mode/lib/css/airplane-mode.css b/includes/airplane-mode/lib/css/airplane-mode.css new file mode 100755 index 000000000..34d53ff45 --- /dev/null +++ b/includes/airplane-mode/lib/css/airplane-mode.css @@ -0,0 +1,59 @@ +@font-face { + font-family: "airplanemodeicons"; + src:url("../fonts/airplanemodeicons.eot"); + src:url("../fonts/airplanemodeicons.eot?#iefix") format("embedded-opentype"), + url("../fonts/airplanemodeicons.woff") format("woff"), + url("../fonts/airplanemodeicons.ttf") format("truetype"), + url("../fonts/airplanemodeicons.svg#airplanemodeicons") format("svg"); + font-weight: normal; + font-style: normal; +} + +#wp-admin-bar-airplane-mode-toggle .ab-icon { + top: 1px; +} + +#wp-admin-bar-airplane-mode-toggle .ab-icon:before { + content: "\e000"; + font: normal 18px/1 airplanemodeicons; +} + +.airplane-mode-disabled #wp-admin-bar-airplane-mode-toggle .ab-icon:before { + content: "\e001"; +} + +#wpadminbar > #wp-toolbar > #wp-admin-bar-root-default > #wp-admin-bar-airplane-mode-toggle .ab-icon, +#wpadminbar #wp-admin-bar-airplane-mode-toggle .ab-icon, +#wpadminbar #wp-admin-bar-airplane-mode-toggle .ab-item::before { + margin-right: 0; +} + +.airplane-mode-no-qm #wpadminbar > #wp-toolbar > #wp-admin-bar-root-default > #wp-admin-bar-airplane-mode-toggle .ab-icon, +.airplane-mode-no-qm #wpadminbar #wp-admin-bar-airplane-mode-toggle .ab-icon, +.airplane-mode-no-qm #wpadminbar #wp-admin-bar-airplane-mode-toggle .ab-item::before { + margin-right: 6px; +} + + /* Set the opacity to mimic comment moderation queue. */ +.airplane-mode-disabled #wp-admin-bar-airplane-mode-toggle .ab-label { + /* Theoretically for IE 8 & 9 (more valid) */ + /* ...but not required as filter works too */ + /* should come BEFORE filter */ + -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; + + /* This works in IE 8 & 9 too */ + /* ... but also 5, 6, 7 */ + filter: alpha(opacity=50); /* IE 5-7 */ + + /* Modern Browsers */ + opacity: 0.5; +} + +.airplane-mode-enabled.plugin-install-php.branch-4-6 h1 a.upload-view-toggle, +.airplane-mode-enabled.plugin-install-php h1 a.upload, +.airplane-mode-enabled.plugin-install-php .wp-filter, +.airplane-mode-enabled.theme-install-php .wp-filter, +.airplane-mode-enabled .theme-browser.content-filterable.rendered, +.airplane-mode-enabled.theme-install-php a.browse-themes { + display: none !important; +} diff --git a/includes/airplane-mode/lib/css/airplane-mode.min.css b/includes/airplane-mode/lib/css/airplane-mode.min.css new file mode 100755 index 000000000..9cbe92d90 --- /dev/null +++ b/includes/airplane-mode/lib/css/airplane-mode.min.css @@ -0,0 +1 @@ +@font-face{font-family:airplanemodeicons;src:url(../fonts/airplanemodeicons.eot);src:url(../fonts/airplanemodeicons.eot?#iefix) format("embedded-opentype"),url(../fonts/airplanemodeicons.woff) format("woff"),url(../fonts/airplanemodeicons.ttf) format("truetype"),url(../fonts/airplanemodeicons.svg#airplanemodeicons) format("svg");font-weight:400;font-style:normal}#wp-admin-bar-airplane-mode-toggle .ab-icon{top:1px}#wp-admin-bar-airplane-mode-toggle .ab-icon:before{content:"\e000";font:400 18px/1 airplanemodeicons}.airplane-mode-disabled #wp-admin-bar-airplane-mode-toggle .ab-icon:before{content:"\e001"}#wpadminbar #wp-admin-bar-airplane-mode-toggle .ab-icon,#wpadminbar #wp-admin-bar-airplane-mode-toggle .ab-item::before,#wpadminbar>#wp-toolbar>#wp-admin-bar-root-default>#wp-admin-bar-airplane-mode-toggle .ab-icon{margin-right:0}.airplane-mode-no-qm #wpadminbar #wp-admin-bar-airplane-mode-toggle .ab-icon,.airplane-mode-no-qm #wpadminbar #wp-admin-bar-airplane-mode-toggle .ab-item::before,.airplane-mode-no-qm #wpadminbar>#wp-toolbar>#wp-admin-bar-root-default>#wp-admin-bar-airplane-mode-toggle .ab-icon{margin-right:6px}.airplane-mode-disabled #wp-admin-bar-airplane-mode-toggle .ab-label{-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";filter:alpha(opacity=50);opacity:.5}.airplane-mode-enabled .theme-browser.content-filterable.rendered,.airplane-mode-enabled.plugin-install-php .wp-filter,.airplane-mode-enabled.plugin-install-php h1 a.upload,.airplane-mode-enabled.plugin-install-php.branch-4-6 h1 a.upload-view-toggle,.airplane-mode-enabled.theme-install-php .wp-filter,.airplane-mode-enabled.theme-install-php a.browse-themes{display:none!important} \ No newline at end of file diff --git a/includes/airplane-mode/lib/fonts/airplanemodeicons.eot b/includes/airplane-mode/lib/fonts/airplanemodeicons.eot new file mode 100755 index 000000000..a41218217 Binary files /dev/null and b/includes/airplane-mode/lib/fonts/airplanemodeicons.eot differ diff --git a/includes/airplane-mode/lib/fonts/airplanemodeicons.svg b/includes/airplane-mode/lib/fonts/airplanemodeicons.svg new file mode 100755 index 000000000..93cbad254 --- /dev/null +++ b/includes/airplane-mode/lib/fonts/airplanemodeicons.svg @@ -0,0 +1,12 @@ + + + +Generated by Fontastic.me + + + + + + + + diff --git a/includes/airplane-mode/lib/fonts/airplanemodeicons.ttf b/includes/airplane-mode/lib/fonts/airplanemodeicons.ttf new file mode 100755 index 000000000..f5198174c Binary files /dev/null and b/includes/airplane-mode/lib/fonts/airplanemodeicons.ttf differ diff --git a/includes/airplane-mode/lib/fonts/airplanemodeicons.woff b/includes/airplane-mode/lib/fonts/airplanemodeicons.woff new file mode 100755 index 000000000..268417ed7 Binary files /dev/null and b/includes/airplane-mode/lib/fonts/airplanemodeicons.woff differ diff --git a/includes/airplane-mode/readme.txt b/includes/airplane-mode/readme.txt new file mode 100755 index 000000000..d9e1875ce --- /dev/null +++ b/includes/airplane-mode/readme.txt @@ -0,0 +1,151 @@ +=== Airplane Mode === +Contributors: norcross, johnbillion, afragen, szepeviktor, chriscct7, markjaquith +Website Link: https://github.com/norcross/airplane-mode +Donate link: https://andrewnorcross.com/donate +Tags: external calls, HTTP +Requires at least: 4.4 +Tested up to: 5.3 +Stable tag: 0.2.5 +License: MIT +License URI: http://norcross.mit-license.org/ + +Control loading of external files when developing locally + +== Description == + +Control loading of external files when developing locally. WP loads certain external files (fonts, gravatar, etc) and makes external HTTP calls. This isn't usually an issue, unless you're working in an evironment without a web connection. This plugin removes / unhooks those actions to reduce load time and avoid errors due to missing files. + +Features + +* removes external JS and CSS files from loading +* replaces all instances of Gravatar with a local image to remove external call +* removes all HTTP requests +* disables all WP update checks for core, themes, and plugins +* includes toggle in admin bar for quick enable / disable + +== Installation == + +This section describes how to install the plugin and get it working. + +1. Upload `airplane-mode` to the `/wp-content/plugins/` directory. +1. Activate the plugin through the 'Plugins' menu in WordPress. +1. Toggle users as needed + +If you need offline activation, see [this script](https://gist.github.com/solepixel/e1d03f4dcd1b9e86552b3cc6937325bf) written by [Brian DiChiara](https://github.com/solepixel) + +== Frequently Asked Questions == + += Why do I need this? = + +Because you are a jet set developer who needs to work without internet. + + +== Screenshots == + + +== Changelog == + += 0.2.5 - 2019/11/15 +* Remove usage of method that's been deprecated in WordPress trunk. props @johnbillion + += 0.2.4 - 2017/12/13 +* Added localhost bypass for loading CSS and JS files when hot reloading. props @shadyvb +* Added additional hook removals for new automated updates and language packs. +* Removed outdated `create_function` call for PHP 7.2 compatibility. props @geminorum +* General cleanup + += 0.2.3 - 2017/03/05 +* Adding option to force transient purge +* Adding `clean` action to WP-CLI functions + += 0.2.2 - 2016/12/07 +* Adding WP-CLI support. props @markjaquith + += 0.2.1 - 2016/10/19 +* Fix settings page language drowdown when used offline. props @onnimonni + += 0.2.0 - 2016/08/26 +* modify CSS loading for front-end, removed loading for login page. props @barryceelen +* fixed WP.org theme API call request to avoid `WP_Error` return. props @onnimonni + += 0.1.9 - 2016/07/25 +* Prevent BuddyPress from falling back to Gravatar. props @johnbillion + += 0.1.8 - 2016/07/12 +* allow `JETPACK_DEV_DEBUG` constant to take priority over filter. props @kopepasah +* added additional CSS for upcoming 4.6. change to upload tab. + += 0.1.7 - 2016/05/18 +* allow local HTTP calls with optional filter. props @johnbillion +* add back index.php link to main dashboard menu item +* bumped minimum WP version requirement to 4.4 + += 0.1.6 - 2016/04/25 +* minor tweak to include CSS for new icon font + += 0.1.5 - 2016/04/24 +* adding custom icon font for display and removing label. props @barryceelen + += 0.1.4 - 2016/02/26 +* better setup for blocked external assets. props @johnbillion + += 0.1.3 - 2016/02/22 +* modified CSS rules to fix media bulk actions bar from disappearing +* moved `airplane_mode_status_change` action to run before redirect, and now includes the status being run. + += 0.1.2 - 2016/01/09 +* added back HTTP count when inactive +* removed HTTP count completely when Query Monitor is active + += 0.1.1 - 2016/01/06 +* fixed incorrect nonce check that was breaking toggle +* changed CSS and JS checks to include all themes and plugins as well as core + += 0.1.0 - 2015/12/30 +* added `airplane_mode_purge_transients` filter to bypass transient purge + += 0.0.9 - 2015/12/07 +* changed from colored circle to actual airplane icon for usability +* fixed dashboard link icon for multisite +* changed to exclude all external stylesheets, not just Open Sans +* added language files for translateable goodness +* general cleanup for WP coding standards + += 0.0.8 - 2015/05/18 +* added `class_exists` as now included in DesktopServer and collisions could result +* fixed `if ( ! defined ...` for `AIRMDE_BASE` constant + += 0.0.7 - 2015/04/21 = +* fixed some CSS from hiding plugins page bar +* moved changelog to it's own file +* added `composer.json` +* added contributors to readme +* clarified license (MIT) + += 0.0.6 - 2015/04/02 = +* version bump for GitHub updater + += 0.0.5 - 2015/04/02 = +* fixed bug in update logic that was preventing checks when disabled (but activated). props @johnbillion + += 0.0.4 - 2015/04/02 = +* added multiple checks for all the various theme and plugin update calls. props @chriscct7 +* added HTTP counter on a per-page basis. props @szepeviktor + += 0.0.3 - 2015/01/23 = +* added `airplane_mode_status_change` hook for functions to fire on status change +* purge update related transients on disable +* added WordPress formatted readme file + += 0.0.2 - 2015/01/21 = +* added GitHub Updater support +* fixed update capabilities when status is disabled + += 0.0.1 - 2014/06/01 = +* lots of stuff. I wasn't keeping a changelog. I apologize. + + +== Upgrade Notice == + += 0.0.1 = +Initial release diff --git a/mkdocs.yml b/mkdocs.yml index 5f4307231..af55ebf91 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -9,10 +9,11 @@ watch: site_description: 'Documentation for the wp-browser WordPress testing framework.' site_author: 'Luca Tumedei' nav: - - Getting started: 'README.md' - - Migrating to newer versions: 'migration.md' - - Default configuration: 'default-configuration.md' - - Custom configuration: 'custom-configuration.md' + - Setup: + - Getting started: 'README.md' + - Migrating to newer versions: 'migration.md' + - Default configuration: 'default-configuration.md' + - Custom configuration: 'custom-configuration.md' - Modules: - WPBrowser: 'modules/WPBrowser.md' - WPCLI: 'modules/WPCLI.md' @@ -21,12 +22,14 @@ nav: - WPLoader: 'modules/WPLoader.md' - WPQueries: 'modules/WPQueries.md' - WPWebDriver: 'modules/WPWebDriver.md' + - Airplane Mode: 'modules/AirplaneMode.md' - Extensions: - PHP Built-in Server Controller: 'extensions#builtinservercontroller' - ChromeDriver Controller: 'extensions#chromedrivercontroller' - Docker Compose Controller: 'extensions#dockercomposecontroller' - Isolation Support: 'extensions#isolationsupport' - Commands: + - wpcept: 'wpcept' - run and codeception:run: 'commands#run-and-codeceptionrun' - dev:start: 'commands#devstart' - dev:stop: 'commands#devstop' @@ -44,13 +47,12 @@ nav: - generate:wpxmlrpc: 'commands#generatewpxmlrpc' - monkey:cache:path: 'commands#monkeycachepath' - monkey:cache:clear: 'commands#monkeycacheclear' - - Testing Helpers: + - Helpers: - UopzFunctions trait: 'traits/UopzFunctions.md' - Troubleshooting: 'troubleshooting.md' - - Sponsorship: 'https://github.com/sponsors/lucatume' - Changelog: 'https://github.com/lucatume/wp-browser/blob/master/CHANGELOG.md' - - Version 3 documentation: - - Welcome: v3/README.md + - v3: + - Welcome: v3/README.md - Frequently asked questions: v3/faq.md - Codeception, PHPUnit and wp-browser: v3/codeception-phpunit-and-wpbrowser.md - Using wp-browser with Codeception 4.0: v3/codeception-4-support.md @@ -90,6 +92,8 @@ theme: - navigation.instant.prefetch - navigation.tracking - navigation.top + - navigation.sections + - navigation.tabs - toc.follow - content.code.select - content.tabs.link diff --git a/src/Module/AirplaneMode.php b/src/Module/AirplaneMode.php new file mode 100644 index 000000000..d52a84886 --- /dev/null +++ b/src/Module/AirplaneMode.php @@ -0,0 +1,143 @@ + false + ]; + + protected function validateConfig(): void + { + parent::validateConfig(); + + $config = $this->config; + /** @var array{muPluginsDir: string, symlink: bool} $config */ + $config['symlink'] = (bool)$config['symlink']; + + if (!is_string($config['muPluginsDir'])) { + throw new ModuleConfigException( + __CLASS__, + 'The muPluginsDir configuration parameter must be a string.' + ); + } + + $muPluginsDir = $config['muPluginsDir']; + + if (is_file($muPluginsDir) && !is_dir($muPluginsDir)) { + throw new ModuleConfigException( + __CLASS__, + 'The muPluginsDir configuration parameter must be a directory.' + ); + } + } + + public function _initialize(): void + { + /** @var array{muPluginsDir: string, symlink: bool} $config */ + $config = $this->config; + $muPluginsDir = $config['muPluginsDir']; + + try { + FS::mkdirp($muPluginsDir, [], 0755); + } catch (\Exception $e) { + throw new ModuleException( + __CLASS__, + 'The muPluginsDir configuration parameter is not a directory and cannot be created.' + ); + } + + if (!$this->config['symlink']) { + $this->copyPlugin($muPluginsDir); + return; + } + + $this->symLinkPlugin($muPluginsDir); + } + + public function _afterSuite(): void + { + /** @var array{muPluginsDir: string, symlink: bool} $config */ + $config = $this->config; + $muPluginsDir = $config['muPluginsDir']; + $pluginDir = $muPluginsDir . '/airplane-mode'; + + if (!FS::rrmdir($pluginDir)) { + throw new ModuleException( + __CLASS__, + 'The airplane-mode plugin could not be removed from the mu-plugins directory.' + ); + } + + if (is_file($muPluginsDir . '/airplane-mode-loader.php') && !unlink( + $muPluginsDir . '/airplane-mode-loader.php' + )) { + throw new ModuleException( + __CLASS__, + 'The airplane-mode loader could not be removed from the mu-plugins directory.' + ); + } + + $this->debugSection('AirplaneMode', 'Airplane Mode plugin removed from mu-plugins directory.'); + } + + + private function copyPlugin(mixed $muPluginsDir): void + { + $pluginDir = dirname(__DIR__, 2) . '/includes/airplane-mode'; + $destination = $muPluginsDir . '/airplane-mode'; + + if (!FS::recurseCopy($pluginDir, $destination)) { + throw new ModuleException( + __CLASS__, + 'The airplane-mode plugin could not be copied to the mu-plugins directory.' + ); + } + + if (!rename($destination . '/airplane-mode-loader.php', $muPluginsDir . '/airplane-mode-loader.php')) { + throw new ModuleException( + __CLASS__, + 'The airplane-mode loader could not be moved to the mu-plugins directory.' + ); + } + + $this->debugSection('AirplaneMode', 'Airplane Mode plugin copied to mu-plugins directory.'); + } + + private function symLinkPlugin(mixed $muPluginsDir): void + { + $pluginDir = dirname(__DIR__, 2) . '/includes/airplane-mode'; + $destination = $muPluginsDir . '/airplane-mode'; + + if (!symlink($pluginDir, $destination)) { + throw new ModuleException( + __CLASS__, + 'The airplane-mode plugin could not be symlinked to the mu-plugins directory.' + ); + } + + if (!symlink($pluginDir . '/airplane-mode-loader.php', $muPluginsDir . '/airplane-mode-loader.php')) { + throw new ModuleException( + __CLASS__, + 'The airplane-mode loader could not be symlinked to the mu-plugins directory.' + ); + } + + $this->debugSection('AirplaneMode', 'Airplane Mode plugin symlinked to mu-plugins directory.'); + } +} diff --git a/tests/_support/_generated/AcceptanceTesterActions.php b/tests/_support/_generated/AcceptanceTesterActions.php index 66283270f..5989f54df 100644 --- a/tests/_support/_generated/AcceptanceTesterActions.php +++ b/tests/_support/_generated/AcceptanceTesterActions.php @@ -1,4 +1,4 @@ -mockModuleContainer = new ModuleContainer(new Di(), []); + + return new AirplaneMode($this->mockModuleContainer, $config); + } + + /** + * It should throw if muPluginsDir is not a string + * + * @test + * @dataProvider notStringDataProvider + */ + public function should_throw_if_mu_plugins_dir_is_not_a_string(mixed $muPluginsDir): void + { + $this->expectException(ModuleConfigException::class); + $this->expectExceptionMessage('The muPluginsDir configuration parameter must be a string.'); + + $module = $this->module(['muPluginsDir' => $muPluginsDir]); + } + + /** + * It should throw if muPluginsDir is a file + * + * @test + */ + public function should_throw_if_mu_plugins_dir_is_a_file(): void + { + $this->expectException(ModuleConfigException::class); + $this->expectExceptionMessage('The muPluginsDir configuration parameter must be a directory.'); + + $module = $this->module(['muPluginsDir' => __FILE__]); + } + + /** + * It should throw if muPluginsDir does not exist and cannot be created at init time + * + * @test + */ + public function should_throw_if_mu_plugins_dir_does_not_exist_and_cannot_be_created_at_init_time(): void + { + $this->setFunctionReturn('mkdir', false); + + $module = $this->module(['muPluginsDir' => __DIR__ . '/not-existing']); + + $this->expectException(ModuleException::class); + $this->expectExceptionMessage( + 'The muPluginsDir configuration parameter is not a directory and cannot be created.' + ); + + $module->_initialize(); + } + + /** + * It should throw if the plugin cannot be copied to the mu-plugins directory + * + * @test + */ + public function should_throw_if_the_plugin_cannot_be_copied_to_the_mu_plugins_directory(): void + { + $tmpDir = Filesystem::tmpDir('airplane-mode_'); + $module = $this->module(['muPluginsDir' => $tmpDir]); + + $this->setMethodReturn(Filesystem::class, 'recurseCopy', false); + + $this->expectException(ModuleException::class); + $this->expectExceptionMessage( + 'The airplane-mode plugin could not be copied to the mu-plugins directory.' + ); + + $module->_initialize(); + } + + /** + * It should throw if the loader cannot be moved in the mu-plugins directory + * + * @test + */ + public function should_throw_if_the_loader_cannot_be_moved_in_the_mu_plugins_directory(): void + { + $tmpDir = Filesystem::tmpDir('airplane-mode_'); + $module = $this->module(['muPluginsDir' => $tmpDir]); + + $this->setFunctionReturn('rename', false); + + $this->expectException(ModuleException::class); + $this->expectExceptionMessage( + 'The airplane-mode loader could not be moved to the mu-plugins directory.' + ); + + $module->_initialize(); + } + + /** + * It should copy the plugin to the mu-plugins directory if symlink parameter not set + * + * @test + */ + public function should_copy_the_plugin_to_the_mu_plugins_directory_if_symlink_parameter_not_set(): void + { + $tmpDir = Filesystem::tmpDir('airplane-mode_'); + + $module = $this->module(['muPluginsDir' => $tmpDir . '/mu-plugins']); + $module->_initialize(); + + $this->assertTrue(is_dir($tmpDir . '/mu-plugins/airplane-mode')); + $this->assertTrue(is_file($tmpDir . '/mu-plugins/airplane-mode-loader.php')); + $this->assertFalse(is_link($tmpDir . '/mu-plugins/airplane-mode')); + + $module->_afterSuite(); + + $this->assertFalse(is_dir($tmpDir . '/mu-plugins/airplane-mode')); + $this->assertFalse(is_file($tmpDir . '/mu-plugins/airplane-mode-loader.php')); + $this->assertTrue(is_dir($tmpDir . '/mu-plugins')); + } + + /** + * It should throw if the plugin cannot be symlinked to the mu-plugins directory + * + * @test + */ + public function should_throw_if_the_plugin_cannot_be_symlinked_to_the_mu_plugins_directory(): void + { + $tmpDir = Filesystem::tmpDir('airplane-mode_'); + $module = $this->module(['muPluginsDir' => $tmpDir, 'symlink' => true]); + + $this->setFunctionReturn('symlink', function ($target, $link) use ($tmpDir) { + return $link === $tmpDir . '/airplane-mode' ? false : symlink($target, $link); + }, true); + + $this->expectException(ModuleException::class); + $this->expectExceptionMessage( + 'The airplane-mode plugin could not be symlinked to the mu-plugins directory.' + ); + + $module->_initialize(); + } + + /** + * It should throw if the loader cannot be symlinked to the mu-plugins directory + * + * @test + */ + public function should_throw_if_the_loader_cannot_be_symlinked_to_the_mu_plugins_directory(): void + { + $tmpDir = Filesystem::tmpDir('airplane-mode_'); + $module = $this->module(['muPluginsDir' => $tmpDir, 'symlink' => true]); + + $this->setFunctionReturn('symlink', function ($target, $link) use ($tmpDir) { + return $link === $tmpDir . '/airplane-mode-loader.php' ? false : symlink($target, $link); + }, true); + + $this->expectException(ModuleException::class); + $this->expectExceptionMessage( + 'The airplane-mode loader could not be symlinked to the mu-plugins directory.' + ); + + $module->_initialize(); + } + + /** + * It should symlink the plugin to the mu-plugins directory if set to symlink + * + * @test + */ + public function should_symlink_the_plugin_to_the_mu_plugins_directory_if_set_to_symlink(): void + { + $tmpDir = Filesystem::tmpDir('airplane-mode_'); + + $module = $this->module(['muPluginsDir' => $tmpDir . '/mu-plugins', 'symlink' => true]); + $module->_initialize(); + + $this->assertTrue(is_dir($tmpDir . '/mu-plugins/airplane-mode')); + $this->assertTrue(is_file($tmpDir . '/mu-plugins/airplane-mode-loader.php')); + $this->assertTrue(is_link($tmpDir . '/mu-plugins/airplane-mode')); + $this->assertTrue(is_link($tmpDir . '/mu-plugins/airplane-mode-loader.php')); + + $module->_afterSuite(); + + $this->assertFalse(is_dir($tmpDir . '/mu-plugins/airplane-mode')); + $this->assertFalse(is_link($tmpDir . '/mu-plugins/airplane-mode')); + $this->assertFalse(is_file($tmpDir . '/mu-plugins/airplane-mode-loader.php')); + $this->assertFalse(is_link($tmpDir . '/mu-plugins/airplane-mode-loader.php')); + $this->assertTrue(is_dir($tmpDir . '/mu-plugins')); + } + + /** + * It should throw if plugin cannot be removed from the mu-plugins directory + * + * @test + */ + public function should_throw_if_plugin_cannot_be_removed_from_the_mu_plugins_directory(): void + { + $tmpDir = Filesystem::tmpDir('airplane-mode_'); + $module = $this->module(['muPluginsDir' => $tmpDir]); + + $module->_initialize(); + + $this->setMethodReturn(Filesystem::class, 'rrmdir', false); + + $this->expectException(ModuleException::class); + $this->expectExceptionMessage( + 'The airplane-mode plugin could not be removed from the mu-plugins directory.' + ); + + $module->_afterSuite(); + } + + /** + * It should throw if loader cannot be removed from the mu-plugins directory + * + * @test + */ + public function should_throw_if_loader_cannot_be_removed_from_the_mu_plugins_directory(): void + { + $tmpDir = Filesystem::tmpDir('airplane-mode_'); + $module = $this->module(['muPluginsDir' => $tmpDir]); + + $module->_initialize(); + + $this->setFunctionReturn('unlink', function (string $file) use ($tmpDir) { + if ($file === $tmpDir . '/airplane-mode-loader.php') { + return false; + } + return unlink($file); + }, true); + + $this->expectException(ModuleException::class); + $this->expectExceptionMessage( + 'The airplane-mode loader could not be removed from the mu-plugins directory.' + ); + + $module->_afterSuite(); + } + + public function notStringDataProvider(): array + { + return [ + 'null' => [null], + 'int' => [1], + 'float' => [1.1], + 'array' => [[]], + 'object' => [new \stdClass()], + 'bool' => [true], + ]; + } +} diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/Support/DbDumpTest.php b/tests/unit/lucatume/WPBrowser/Module/Support/DbDumpTest.php similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/Support/DbDumpTest.php rename to tests/unit/lucatume/WPBrowser/Module/Support/DbDumpTest.php diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/WPBrowserMethodsTest.php b/tests/unit/lucatume/WPBrowser/Module/WPBrowserMethodsTest.php similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/WPBrowserMethodsTest.php rename to tests/unit/lucatume/WPBrowser/Module/WPBrowserMethodsTest.php diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/WPCLITest.php b/tests/unit/lucatume/WPBrowser/Module/WPCLITest.php similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/WPCLITest.php rename to tests/unit/lucatume/WPBrowser/Module/WPCLITest.php diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/WPDbTest.php b/tests/unit/lucatume/WPBrowser/Module/WPDbTest.php similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/WPDbTest.php rename to tests/unit/lucatume/WPBrowser/Module/WPDbTest.php diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/WPFilesystemTest.php b/tests/unit/lucatume/WPBrowser/Module/WPFilesystemTest.php similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/WPFilesystemTest.php rename to tests/unit/lucatume/WPBrowser/Module/WPFilesystemTest.php diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/WPLoader/FiltersTest.php b/tests/unit/lucatume/WPBrowser/Module/WPLoader/FiltersTest.php similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/WPLoader/FiltersTest.php rename to tests/unit/lucatume/WPBrowser/Module/WPLoader/FiltersTest.php diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/WPLoaderTest.php b/tests/unit/lucatume/WPBrowser/Module/WPLoaderTest.php similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/WPLoaderTest.php rename to tests/unit/lucatume/WPBrowser/Module/WPLoaderTest.php diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/WPQueriesTest.php b/tests/unit/lucatume/WPBrowser/Module/WPQueriesTest.php similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/WPQueriesTest.php rename to tests/unit/lucatume/WPBrowser/Module/WPQueriesTest.php diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPCLITest__should_allow_running_commands_with_debug_or_not__0.snapshot.txt b/tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPCLITest__should_allow_running_commands_with_debug_or_not__0.snapshot.txt similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPCLITest__should_allow_running_commands_with_debug_or_not__0.snapshot.txt rename to tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPCLITest__should_allow_running_commands_with_debug_or_not__0.snapshot.txt diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__Db_module_loadOnly_false__0.snapshot.txt b/tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__Db_module_loadOnly_false__0.snapshot.txt similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__Db_module_loadOnly_false__0.snapshot.txt rename to tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__Db_module_loadOnly_false__0.snapshot.txt diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__Db_module_loadOnly_true__0.snapshot.txt b/tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__Db_module_loadOnly_true__0.snapshot.txt similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__Db_module_loadOnly_true__0.snapshot.txt rename to tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__Db_module_loadOnly_true__0.snapshot.txt diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__WPDb_module_loadOnly_false__0.snapshot.txt b/tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__WPDb_module_loadOnly_false__0.snapshot.txt similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__WPDb_module_loadOnly_false__0.snapshot.txt rename to tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__WPDb_module_loadOnly_false__0.snapshot.txt diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__WPDb_module_loadOnly_true__0.snapshot.txt b/tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__WPDb_module_loadOnly_true__0.snapshot.txt similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__WPDb_module_loadOnly_true__0.snapshot.txt rename to tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__WPDb_module_loadOnly_true__0.snapshot.txt diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__no_db_module_loadOnly_false__0.snapshot.txt b/tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__no_db_module_loadOnly_false__0.snapshot.txt similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__no_db_module_loadOnly_false__0.snapshot.txt rename to tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__no_db_module_loadOnly_false__0.snapshot.txt diff --git a/tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__no_db_module_loadOnly_true__0.snapshot.txt b/tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__no_db_module_loadOnly_true__0.snapshot.txt similarity index 100% rename from tests/unit/lucatume/WPBrowser/Events/Module/__snapshots__/WPLoaderTest__test_exit_messages__no_db_module_loadOnly_true__0.snapshot.txt rename to tests/unit/lucatume/WPBrowser/Module/__snapshots__/WPLoaderTest__test_exit_messages__no_db_module_loadOnly_true__0.snapshot.txt diff --git a/tests/webdriver.suite.dist.yml b/tests/webdriver.suite.dist.yml index 951bcda22..eae9cbc29 100644 --- a/tests/webdriver.suite.dist.yml +++ b/tests/webdriver.suite.dist.yml @@ -5,6 +5,7 @@ modules: - WPWebDriver - WPDb - WPFilesystem + - lucatume\WPBrowser\Module\AirplaneMode config: WPWebDriver: url: '%WORDPRESS_URL%' @@ -42,3 +43,6 @@ modules: plugins: '/wp-content/plugins' mu-plugins: '/wp-content/mu-plugins' uploads: '/wp-content/uploads' + lucatume\WPBrowser\Module\AirplaneMode: + muPluginsDir: '%WORDPRESS_ROOT_DIR%/wp-content/mu-plugins' + symlink: true