Skip to content

Instantly share code, notes, and snippets.

@jbrinley
Last active August 20, 2019 18:38
Show Gist options
  • Save jbrinley/9e14c6b1a4f66c982893d7b17302075b to your computer and use it in GitHub Desktop.
Save jbrinley/9e14c6b1a4f66c982893d7b17302075b to your computer and use it in GitHub Desktop.
WordPress plugin to disable the deletion of plugin files when running the uninstaller. Drop this in your mu-plugins directory before running the uninstaller.
<?php
/**
* Plugin Name: Disable Plugin Deletion
* Description: Disables the deletion of plugin files when running the uninstaller
* Author: Jonathan Brinley
* Version: 1.0.0
* Author URI: https://xplus3.net/
* License: GPLv2 or later
*/
namespace No_Delete_Filesystem;
/**
* Prevents the plugin uninstaller from deleting the actual plugin files.
*
* Works by overriding the global $wp_filesystem object with a wrapper.
* Any call to delete a file will do nothing. Everything else is passed
* through to the original object.
*/
class No_Delete_Filesystem {
/** @var \WP_Filesystem_Base */
private $filesystem;
public function __construct( \WP_Filesystem_Base $filesystem ) {
$this->filesystem = $filesystem;
}
/**
* Delegate everything to the wrapped filesystem
*/
public function __call( $method, $args ) {
return call_user_func_array( [ $this->filesystem, $method ], $args );
}
/**
* Just pretend that deletion worked, but don't do anything
*/
public function delete( $file, $recursive = false, $type = false ) {
return true;
}
public function override_global_filesystem() {
$GLOBALS['wp_filesystem'] = $this;
}
public function reset_global_filesystem() {
$GLOBALS['wp_filesystem'] = $this->filesystem;
}
}
/**
* Get the global singleton instance
*
* @return No_Delete_Filesystem
*/
function get_no_delete_filesystem() {
static $filesystem;
if ( ! $filesystem ) {
$filesystem = new No_Delete_Filesystem( $GLOBALS['wp_filesystem'] );
}
return $filesystem;
}
function tear_down() {
get_no_delete_filesystem()->reset_global_filesystem();
remove_action( 'deleted_plugin', __FUNCTION__, 10 );
}
add_action( 'delete_plugin', function () {
get_no_delete_filesystem()->override_global_filesystem();
add_action( 'deleted_plugin', __NAMESPACE__ . '\\tear_down', 10, 0 );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment