Prevent plugin from deleting important directories

I want to allow users to upload custom files to specific plugin directory. The problem is, obviously, that WP removes everything upon plugin version update.

I think that the upgrader_pre_install and upgrader_post_install hooks may be useful, but unfortunately so far I wasn’t able to find any info to help me.

Read More

In your opinion, can these hooks be used to retain a directory and if so, how?
Should I simply copy the directory elsewhere, like the uploads folder, and copy it back with upgrader_post_install?
What would be the best practice?

Thanks

Related posts

Leave a Reply

2 comments

  1. To answer my own question here is what I’ve found for the sake of keeping questions answered. What this does is copying the important directory before upgrade and recovering it after upgrade:

    function my_dir_copy($source, $dest)
    {
        if (is_link($source)) {
            return symlink(readlink($source), $dest);
        }
        if (is_file($source)) {
            return copy($source, $dest);
        }
        if (!is_dir($dest)) {
            mkdir($dest);
        }
        $dir = dir($source);
        while (false !== $entry = $dir->read()) {
            if ($entry == '.' || $entry == '..') {
                continue;
            }
            my_dir_copy("$source/$entry", "$dest/$entry");
        }
    
        $dir->close();
        return true;
    }
    
    
    function my_dir_rmdirr($dirname)
    {
    
        if (!file_exists($dirname)) {
            return false;
        }
    
    
        if (is_file($dirname)) {
            return unlink($dirname);
        }
    
    
        $dir = dir($dirname);
        while (false !== $entry = $dir->read()) {
    
            if ($entry == ‘.’ || $entry == ‘..’) {
            continue;
            }
            rmdirr(“$dirname/$entry”);
        }
    
    
        $dir->close();
        return rmdir($dirname);
    }
    
    
    function my_dir_backup()
    {
            $to = dirname(__FILE__)."/../igr_backup/";
            $from = dirname(__FILE__)."/whatever_directory_you_preserve/";
            my_dir_copy($from, $to);
    }
    function my_dir_recover()
    {
            $from = dirname(__FILE__)."/../igr_backup/";
            $to = dirname(__FILE__)."/whatever_directory_you_preserve/";
            my_dir_copy($from, $to);
            if (is_dir($from)) {
                    my_dir_rmdirr($from);
            }
    }
    add_filter('upgrader_pre_install', 'my_dir_backup', 10, 2);
    add_filter('upgrader_post_install', 'my_dir_recover', 10, 2);