Server : LiteSpeed
System : Linux premium92.web-hosting.com 4.18.0-553.44.1.lve.el8.x86_64 #1 SMP Thu Mar 13 14:29:12 UTC 2025 x86_64
User : rbnsfqys ( 805)
PHP Version : 8.1.33
Disable Function : NONE
Directory :  /home/rbnsfqys/ali.rbn.services/wp-content/plugins/Repairplugin-pro/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]


Current File : /home/rbnsfqys/ali.rbn.services/wp-content/plugins/Repairplugin-pro/backups.php
<?php

// Exit if accessed directly

defined( 'ABSPATH' ) || exit;

if(!defined('RP_BACKUPS_PLUGIN_FILE')) {

    define( 'RP_BACKUPS_PLUGIN_FILE', __FILE__ );

    define( 'RP_BACKUPS_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );

    define( 'RP_BACKUPS_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );

    define( 'RP_BACKUPS_PLUGIN_URL', plugin_dir_url( __FILE__ ) );

    define( 'RP_BACKUPS_ASSETS_CACHE_V', WP_REPAIR_ASSETS_CACHE_V );

    define( 'RP_BACKUPS_BASE_SERVER_URL', WP_REPAIR_BASE_SERVER_URL );

    if( !empty( $_REQUEST['rpbkp_quick_get_progress'] ?? '0' ) == '1' ) {

        define( 'RP_BACKUPS_MAX_PROCESS_TIMEOUT', 1 ); // seconds

    } else {

        define( 'RP_BACKUPS_MAX_PROCESS_TIMEOUT', 3 ); // seconds

    }

}

function rp_create_unique_random_id() {

    return md5( 'rpbkp_' . time() . '_' . rand( 100000, 999999 ). uniqid() );

}

// alternate of php built-in current() function
function rp_current_func_alternate( $obj = null ) {

    $result = '';

    foreach( $obj as $key => $value ) {

        $result = $value;

        break;

    }

    return $result;

}

function rp_get_all_database_tables_starting_with_rs_prefix() {

    global $wpdb;

    $tables = $wpdb->get_results("SHOW TABLES LIKE '{$wpdb->prefix}rs%'");

    $tables = array_map('rp_current_func_alternate', $tables);

    return $tables;

}

// loop through all files directly under the directory
// and try to find a line that has 
// rp_get_option
// rp_update_option
// rp_delete_option
// rp_add_option
function rp_find_defined_repairplugin_options() {
    
    $all_files = rp_get_all_project_files( dirname( __FILE__ ) );

    $all_files = rp_filter_only_php_files( $all_files );

    $matchingLines = array();

    $issueMatching = array();

    $matchingConditions = array(
        'rp_get_option',
        'rp_update_option',
        'rp_add_option',
        'rp_delete_option'
    );

    foreach( $all_files as $theFile ) {

        if (is_file($theFile)) {

            // if file is same as this file, skip it
            if( strpos( $theFile, 'backups.php' ) !== FALSE ) {

                // Skip current file
                continue;

            }

            $file_content = file_get_contents($theFile);

            $lines = explode("\n", $file_content);

            foreach ($lines as $linNum => $line) {

                $anyConditionMet = false;

                foreach( $matchingConditions as $condition ) {

                    if( strpos( $line, $condition ) !== FALSE ) {

                        $anyConditionMet = true;

                    }

                }

                if( $anyConditionMet == true ) {

                    $matchingOptions = find_all_matches_in_line( $line );

                    if( !empty( $matchingOptions ) ) {

                        foreach( $matchingOptions as $matchingOption ) {

                            $matchingLines[] = $matchingOption;

                        }

                    } else {

                        $issueMatching[] = $line;

                    }

                }

            }

        }

    }

    return $matchingLines;

}

function find_all_matches_in_line( $line = '' ) {

    // regex = (get|update|delete|add)_option(\s){0,}(\()(\s){0,}(\'|\")([a-zA-Z0-9\_\-])+(\s){0,}(\"|\')

    $matches = array();

    while( preg_match( '/(get|update|delete|add)_option(\s){0,}(\()(\s){0,}(\'|\")([a-zA-Z0-9\_\-])+(\s){0,}(\"|\')/', $line, $match ) ) {

        $matches[] = $match;

        $line = str_replace( $match[0], '', $line );

    }

    $fixMatches = array();

    if( !empty( $matches ) ) {

        foreach( $matches as $match ) {

            if( !empty( $match ) && !empty( $match[0] ?? '' ) ) {

                $fixMatches[] = $match[0];

            }
    
        }

    }

    return $fixMatches;

}

function rp_get_all_excluded_directories() {

    $rp_plugin_path = RP_BACKUPS_PLUGIN_PATH;

    $excluded_directories = array(
        '{rp_plugin_path}/html/front_end/dompdf',
        '{rp_plugin_path}/html/front_end/php_mailer'
    );
    
    // loop through all excluded directories 
    foreach( $excluded_directories as $dir_key => $dir_value ) {
    
        $dir_value = str_replace('{rp_plugin_path}/', $rp_plugin_path, $dir_value);
    
        // trim ending slash
        $dir_value = rtrim( $dir_value, DIRECTORY_SEPARATOR );
    
        $dir_value = rtrim( $dir_value, '/' );
    
        // replace / with DIRECTORY_SEPARATOR
        $dir_value = str_replace( '/', DIRECTORY_SEPARATOR, $dir_value );
    
        $excluded_directories[ $dir_key ] = $dir_value;
    
    }

    return $excluded_directories;

}

function rp_is_excluded_dir( $file = '', $excluded_directories = array() ) {

    if( empty( $file ) || empty( $excluded_directories ) ) {

        return false;

    }

    foreach( $excluded_directories as $dir ) {

        if( strpos( $file, $dir ) !== FALSE ) {

            return true;

        }

    }

    return false;

}

function rp_get_all_project_files( $dir = '' ) {
    
    $excluded_directories = rp_get_all_excluded_directories();

    if( $dir == '' ) {

        $dir = dirname(__FILE__);

    }

    $all_files = array();

    // loop through all files in the current directory
    foreach (glob( $dir . DIRECTORY_SEPARATOR . '*') as $file) {

        // continue if the file is in excluded directories
        if( rp_is_excluded_dir( $file, $excluded_directories ) ) {
            continue;
        }

        // if it is a directory, then repeat the process by calling this function again
        if (is_dir($file)) {
            $all_files = array_merge($all_files, rp_get_all_project_files($file));
        } else {
            $all_files[] = $file;
        }
    }

    return $all_files;

}

function rp_filter_only_php_files( $all_files = array() ) {

    $filteredFiles = array();

    foreach( $all_files as $fileValue ) {

        if( strpos( $fileValue, '.php' ) !== FALSE ) {

            $filteredFiles[] = $fileValue;

        }

    }

    return $filteredFiles;

}

// loop through all files directly under the directory
// and try to find a line that starts with CREATE TABLE
function rp_find_defined_database_tables() {

    global $wpdb;

    $dbTables = dbsh_get_database_structure_handler()->get_only_registered_tables();

    $filtered = array();

    // loop through all and remove $wpdb->prefix from the start
    foreach( $dbTables as $dbTable ) {

        if( strpos( $dbTable, $wpdb->prefix ) !== FALSE ) {

            // get everything after length of $wpdb->prefix
            $dbTable = substr( $dbTable, strlen( $wpdb->prefix ) );

            $filtered[] = $dbTable;

        }

    }

    return $filtered;
    
}

// Use this function to get all repair plugin tables
// available in the database
function rp_filter_only_repair_plugin_tables() {

    $rpTables = _rp_filter_only_repair_plugin_tables();

    $tableRowsCount = array();

    foreach( $rpTables as $rpTable ) {

        $tableRowsCount[ $rpTable ] = rp_count_rows_of_table( $rpTable );

    }

    // sort by table rows count
    // lowest to highest
    asort( $tableRowsCount );

    $tableRowsCount = array_keys( $tableRowsCount );

    return $tableRowsCount;

}

function _rp_filter_only_repair_plugin_tables() {

    global $wpdb;

    $rpTables = rp_find_defined_database_tables();

    $dbTables = rp_get_all_database_tables_starting_with_rs_prefix();

    $onlyRpTables = array();

    foreach( $dbTables as $dbTable ) {

        foreach( $rpTables as $rpTable ) {

            if( trim( $dbTable ) == trim( $wpdb->prefix . $rpTable ) ) {

                $onlyRpTables[] = $dbTable;

            }

        }

    }

    $onlyRpTables = array_unique( $onlyRpTables );

    $onlyRpTables = array_values( $onlyRpTables );

    $rpTables = $onlyRpTables;

    return $rpTables;

}

function rp_get_all_options_starting_with_rp_prefix() {

    global $wpdb;

    $options_table = $wpdb->prefix . 'options';

    $rpOptions = $wpdb->get_results("SELECT * FROM {$options_table} WHERE (`option_name` LIKE 'rp_%' OR `option_name` LIKE 'set_default_wp_repair_email_templates' OR `option_name` LIKE 'wp_repair_%') AND (`option_name` NOT LIKE 'rpbkp_%' AND `option_name` NOT LIKE 'rp_dp_finished_cron_processing' AND `option_name` NOT LIKE 'rp_dp_long_process%')");

    return $rpOptions;

}

function rp_delete_all_options_starting_with_rp_prefix() {

    global $wpdb;

    $options_table = $wpdb->prefix . 'options';

    $rpOptions = $wpdb->query("DELETE FROM {$options_table} WHERE (`option_name` LIKE 'rp_%' OR `option_name` LIKE 'set_default_wp_repair_email_templates' OR `option_name` LIKE 'wp_repair_%') AND (`option_name` NOT LIKE 'rpbkp_%' AND `option_name` NOT LIKE 'rp_dp_finished_cron_processing' AND `option_name` NOT LIKE 'rp_dp_long_process%')");

    return $rpOptions;

}

function rp_count_all_options_starting_with_rp_prefix() {

    global $wpdb;

    $options_table = $wpdb->prefix . 'options';

    $rpOptions = $wpdb->get_results("SELECT COUNT(*) AS `total` FROM {$options_table} WHERE (`option_name` LIKE 'rp_%' OR `option_name` LIKE 'set_default_wp_repair_email_templates' OR `option_name` LIKE 'wp_repair_%') AND (`option_name` NOT LIKE 'rpbkp_%' AND `option_name` NOT LIKE 'rp_dp_finished_cron_processing' AND `option_name` NOT LIKE 'rp_dp_long_process%')");

    return $rpOptions;

}

function rp_bkp_reset_dynamic_pricing_cron_options_on_import() {

    // rp_dp_finished_cron_processing
    // rp_dp_long_process
    global $wpdb;

    $options_table = $wpdb->prefix . 'options';

    $rpOptions = $wpdb->query("DELETE FROM {$options_table} WHERE `option_name` LIKE 'rp_dp_finished_cron_processing' OR `option_name` LIKE 'rp_dp_long_process%'");

    return $rpOptions;

}

function rp_create_directory_if_not_exists( $dir = '' ) {

    if( !is_dir( $dir ) ) {

        mkdir( $dir, 0777 );

    }

    return true;

}

function rp_do_file_put_contents( $file = '', $content = '' ) {

    // if file does not exist, create it
    if( !file_exists( $file ) ) {

        file_put_contents( $file, '' );

    }

    // open file in append mode

    $fileHandler = fopen( $file, 'a' );

    fwrite( $fileHandler, $content );

    fclose( $fileHandler );

    return true;

}

function rp_bkp_get_backup_dir() {

    $upload_dir = wp_upload_dir();

    return str_replace( array( '/', '\\' ), DIRECTORY_SEPARATOR, $upload_dir['basedir']) . DIRECTORY_SEPARATOR . 'repair-plugin-backups';

}

function rp_bkp_get_all_backup_files() {

    $backup_dir = rp_bkp_get_backup_dir();

    if( rp_create_directory_if_not_exists( $backup_dir ) == false ) {

        return false;

    }

    $files = glob( $backup_dir . DIRECTORY_SEPARATOR . '*.rpdata' );

    // create array like: url, last modified, file name, file size (mb)
    $result_array = array();

    foreach( $files as $file ) {

        if( strpos($file,'rp_backup_') == false ) {
            continue;
        }

        $file_name = basename( $file );

        $abspath = rtrim( ABSPATH, '/' );

        $abspath = rtrim( $abspath, '\\' );

        $abspath = str_replace( '\\', '/', $abspath);

        $abspath = str_replace( '/', DIRECTORY_SEPARATOR, $abspath );

        $file_url = str_replace( $abspath, '{rpbkp_site_url}', $file );

        $site_url = rp_get_site_url_while_import();

        $file_url = str_replace( '{rpbkp_site_url}', $site_url, $file_url );

        $file_url = str_replace( DIRECTORY_SEPARATOR, '/', $file_url );

        $file_size = filesize( $file );

        $file_size = round( $file_size / 1024 / 1024, 2 );

        $file_last_modified = filemtime( $file );

        $file_last_modified = date( 'Y-m-d H:i:s', $file_last_modified );

        $backup_status = rp_bkp_get_backup_file_status( $file );

        $result_array[] = array(
            'status' => $backup_status, // processing, success, failed, unknown
            'url' => $file_url,
            'last_modified' => $file_last_modified,
            'file_name' => $file_name,
            'file_size' => $file_size
        );

    }

    // sort by last modified (latest first)
    usort( $result_array, function( $a, $b ) {

        return strtotime( $b['last_modified'] ) <=> strtotime( $a['last_modified'] );

    });

    return $result_array;

}

function rp_get_pending_processing_images_file() {

    $backup_dir = rp_bkp_get_backup_dir();

    if( rp_create_directory_if_not_exists( $backup_dir ) == false ) {

        return false;

    }

    $imageProcessingFileName = 'pending_processing_images.rpdata';

    $imageProcessingFile = $backup_dir . DIRECTORY_SEPARATOR . $imageProcessingFileName;

    return $imageProcessingFile;

}

function rp_bkp_is_valid_image_file( $string = '' ) {

    $image_files = array( 'jpg', 'jpeg', 'png', 'gif', 'svg' );

    $hasImgExt = false;

    foreach( $image_files as $imgExt ) {

        if( strpos( $string, '.' . $imgExt ) !== FALSE ) {

            $hasImgExt = true;

            break;

        }

    }

    if( $hasImgExt == false ) {

        return false;

    }

    if( strpos( $string, 'plugins/Repairplugin-pro' ) !== FALSE ) {

        // it's image from Repairplugin-pro plugin
        return false;

    }

    // make sure the file has uploads directory in it
    if( strpos( $string, 'uploads' ) === FALSE ) {

        return false;

    }

    // make sure image has {rpbkp_site_url} in it
    if( strpos( $string, '{rpbkp_site_url}' ) === FALSE ) {

        return false;

    }

    // trim / from end of ABSPATH
    $abspath = rtrim( ABSPATH, '/' );

    $abspath = rtrim( $abspath, '\\' );

    $abspath = str_replace( '\\', '/', $abspath);

    $string = str_replace( '{rpbkp_site_url}', $abspath, $string );
    
    $string = str_replace( '/', DIRECTORY_SEPARATOR, $string );

    if( file_exists( $string ) ) {

        return true;

    }

    return false;

}

function rp_bkp_get_image_file_for_export( $string = '' ) {

    if( empty( $string ) ) {

        return false;

    }

    // trim / from end of ABSPATH
    $abspath = rtrim( ABSPATH, '/' );

    $abspath = rtrim( $abspath, '\\' );

    $abspath = str_replace( '\\', '/', $abspath);

    $string = str_replace( '{rpbkp_site_url}', $abspath, $string );
    
    $string = str_replace( '/', DIRECTORY_SEPARATOR, $string );

    if( file_exists( $string ) ) {

        return file_get_contents( $string );

    }

    return false;

}

function rp_find_and_add_images_from_all_columns( $obj = null ) {

    if( $obj == null ) {

        return $obj;

    }

    foreach( $obj as $key => $value ) {

        if( is_string( $value ) ) {

            rp_add_to_pending_processing_image( $value );

        }

    }

    return $obj;

}

function rp_add_to_pending_processing_image( $string = '' ) {

    if( rp_bkp_is_valid_image_file( $string ) == TRUE ) {

        $processing_images_file = rp_get_pending_processing_images_file();

        // create file if not exists
        if( !file_exists( $processing_images_file ) ) {

            file_put_contents( $processing_images_file, '' );

        }

        // add to file
        $string = "\n" . $string;

        file_put_contents( $processing_images_file, $string, FILE_APPEND );

    }

}

function rp_get_unique_backup_file( $custom_name = '' ) {

    $backup_dir = rp_bkp_get_backup_dir();

    if( rp_create_directory_if_not_exists( $backup_dir ) == false ) {

        return false;

    }

    $backupFileName = 'rp_backup_'. $custom_name . date('Y_m_d_H_i_s') . '.rpdata';

    $backupFile = $backup_dir . DIRECTORY_SEPARATOR . $backupFileName;

    return $backupFile;

}

function rp_replace_site_url_from_all_columns( $obj = null ) {

    if( $obj == null ) {

        return $obj;

    }

    foreach( $obj as $key => $value ) {

        if( is_string( $value ) ) {

            $obj->$key = rp_bkp_find_and_replace_site_url( $value );

        }

    }

    return $obj;

}

function rp_get_encryption_password() {

    $token = rp_get_option('rpbkp_export_unique_backup_pass', '');

    if( empty( $token ) ) {

        throw new Exception('Unexpected Error. Backup unique token not found');

    }

    return $token;

}

function rp_encrypt_the_text( $text = '', $password = '' ) {

    $encrypted = openssl_encrypt($text, "AES-128-ECB", $password);

    return $encrypted;

}

function rp_decrypt_the_text( $text = '', $password = '' ) {

    $decrypted = openssl_decrypt($text, "AES-128-ECB", $password);

    return $decrypted;

}

function rp_bkp_uncompress_process( $obj, $password = '' ) {

    if( empty( trim( $obj ) ) ) {

        return '';

    }

    $obj = str_replace( '0rpbrl0', "\r", $obj );

    $obj = str_replace( '0rpbnl0', "\n", $obj );

    // $obj = gzdecode( $obj );

    if( !empty( $password ) ) {

        $obj = rp_decrypt_the_text( $obj, $password );

    }

    $obj = unserialize( $obj );

    return $obj;

}

function rp_bkp_compression_process( $obj, $password = '' ) {

    $obj = serialize( $obj );

    if( !empty( $password ) ) {

        $obj = rp_encrypt_the_text( $obj, $password );

    }

    // $obj = gzencode( $obj );

    $obj = str_replace( "\n", '0rpbnl0', $obj );

    $obj = str_replace( "\r", '0rpbrl0', $obj );

    return $obj;

}

function rp_create_backup_of_rp_options( $backupFile = '', $offset = 0, $limit = 100 ) {

    global $wpdb;

    $options_table = $wpdb->prefix . 'options';

    $rpOptions = $wpdb->get_results("SELECT * FROM {$options_table} WHERE (`option_name` LIKE 'rp_%' OR `option_name` LIKE 'set_default_wp_repair_email_templates' OR `option_name` LIKE 'wp_repair_%')
    AND (`option_name` NOT LIKE 'rpbkp_%' AND `option_name` NOT LIKE 'rp_dp_finished_cron_processing' AND `option_name` NOT LIKE 'rp_dp_long_process%') LIMIT {$offset}, {$limit}");

    if( empty( $rpOptions ) ) {

        return 0;

    }

    $backUpFileContent = '';

    $processedRows = 0;

    // loop through all options and add every option to a new line
    foreach( $rpOptions as $option ) {

        $option = rp_replace_site_url_from_all_columns( $option );

        rp_find_and_add_images_from_all_columns( $option );

        $option->backup_type = 'options';

        $serializedString = rp_bkp_compression_process( $option, rp_get_encryption_password() );

        $backUpFileContent .= 'renc>' . $serializedString . "\n";

        $processedRows++;

    }

    $backUpFileContent = "\n". $backUpFileContent;

    // add to file

    rp_do_file_put_contents( $backupFile, $backUpFileContent );

    return $processedRows;

}

function rp_create_backup_of_table( $backupFile = '', $table_name = '', $offset = 0, $limit = 100 ) {

    global $wpdb;

    $sql = "SELECT * FROM {$table_name} LIMIT {$offset}, {$limit}";

    $results = $wpdb->get_results( $sql );

    if( empty( $results ) ) {

        return 0;

    }

    $backUpFileContent = '';

    $processedRows = 0;

    // loop through all results and add every result to a new line
    foreach( $results as $result ) {

        $result = rp_replace_site_url_from_all_columns( $result );

        rp_find_and_add_images_from_all_columns( $result );

        $result->backup_type = 'table';

        $result->backup_table_name = $table_name;

        $serializedString = rp_bkp_compression_process( $result, rp_get_encryption_password() );

        $backUpFileContent .= 'renc>' . $serializedString . "\n";

        $processedRows++;

    }

    $backUpFileContent = "\n". $backUpFileContent;

    // add to file

    rp_do_file_put_contents( $backupFile, $backUpFileContent );

    return $processedRows;

}

function rp_count_rows_of_table( $table_name = '' ) {

    global $wpdb;

    $sql = "SELECT COUNT(*) AS `total` FROM {$table_name}";

    $results = $wpdb->get_results( $sql );

    if( !empty( $results ) ) {

        return $results[0]->total;

    }

    return 0;

}

function rp_read_file_line_by_line( $file = '', $startingLineIndex = 0, $linesLimit = 100 ) {

    $handler = fopen( $file, 'r' );

    $lines = array();

    $lineIndex = 0;

    while( !feof( $handler ) ) {

        $line = fgets( $handler );

        if( $lineIndex >= $startingLineIndex ) {

            $lines[] = $line;

        }

        $lineIndex++;

        if( $lineIndex >= $startingLineIndex + $linesLimit ) {

            break;

        }

    }

    fclose( $handler );

    return $lines;

}

function rp_remove_rpbkp_table_offets() {

    global $wpdb;

    $options_table = $wpdb->prefix . 'options';

    $sql = "DELETE FROM {$options_table} WHERE `option_name` LIKE 'rpbkp_table_offset_%'";

    return $wpdb->query( $sql );

}

function rp_get_site_url_while_import() {

    $site_url = get_site_url();

    // remove / from the end
    $site_url = rtrim( $site_url, '/' );

    $site_url = str_replace('.transurl.nl', '', $site_url);

    $site_url = str_replace(':443', '', $site_url);

    return $site_url;

}

function rp_bkp_get_site_url_while_export() {

    $site_url = get_site_url();
    
    $site_url = explode( '://', $site_url );

    $site_url = $site_url[1] ?? '';

    // remove / from the end
    $site_url = rtrim( $site_url, '/' );

    $site_url = str_replace('.transurl.nl', '', $site_url);

    $site_url = str_replace(':443', '', $site_url);

    return $site_url;

}

function rp_bkp_find_and_replace_site_url( $string = '' ) {

    $with_https = 'https://' . rp_bkp_get_site_url_while_export();

    $with_http = 'http://' . rp_bkp_get_site_url_while_export();

    $string = str_replace( $with_https, '{rpbkp_site_url}', $string );

    $string = str_replace( $with_http, '{rpbkp_site_url}', $string );

    return $string;

}

function rpbkp_fix_site_url_in_all_import_columns( $row ) {

    foreach( $row as $col => $val ) {

        if( is_string( $val ) ) {

            $row->$col = str_replace( '{rpbkp_site_url}', rp_get_site_url_while_import(), $val );

        }

    }

    return $row;

}

function rp_get_existing_table_indexes_import_export( $table_name = '' ) {

    global $rpQuery;

    $indexes = $rpQuery->get_results("SELECT * FROM information_schema.statistics WHERE `table_schema` = '".DB_NAME."' AND `table_name` = '".rp_escape_sql($table_name)."'");

    $filtered = array();

    $alreadyAdded = array();

    foreach( $indexes as $index ) {

          $hash = md5( $table_name . $index->INDEX_NAME );

          if( in_array( $hash, $alreadyAdded ) ) {

                continue;

          }

          $alreadyAdded[] = $hash;

          $filtered[] = $index;

    }

    return $filtered;

}

function rp_remove_all_indexes_from_table_except_primary_import_export( $table_name = '' ) {

    if( empty( $table_name ) ) {

        return;

    }

    global $rpQuery;

    $indexes = rp_get_existing_table_indexes_import_export( $table_name );

    if( !empty( $indexes ) ) {

        foreach( $indexes as $key => $index ) {

            if( strtoupper( $index->INDEX_NAME ) == 'PRIMARY' ) {

                continue;

            }

            if( $index->Key_name != 'PRIMARY' ) {

                $rpQuery->query("ALTER TABLE `$table_name` DROP INDEX `".($index->INDEX_NAME)."`");

            }

        }

    }

}

$rpbkp_has_truncated_table_cached = array();

function rpbkp_truncate_the_table( $table_name = '' ) {

    global $rpbkp_has_truncated_table_cached;

    if( !rpbkp_has_truncated_table( $table_name ) ) {

        global $wpdb;

        $sql = "TRUNCATE TABLE {$table_name}";

        $wpdb->query( $sql );

        rp_remove_all_indexes_from_table_except_primary_import_export( $table_name );

        $truncated_tables = rp_get_option('rpbkp_import_truncated_tables', array());

        if( !is_array( $truncated_tables ) ) {

            $truncated_tables = array();

        }

        $truncated_tables[] = $table_name;

        rp_update_option( 'rpbkp_import_truncated_tables', $truncated_tables );

        $rpbkp_has_truncated_table_cached[ $table_name ] = true;

        // Clear cache because we have truncated the table
        // looks like object cache does not get cleared 
        // when we truncate a table
        rp_safe_wp_cache_flush();

    }

}

function rpbkp_has_truncated_table( $table_name = '' ) {

    global $rpbkp_has_truncated_table_cached;

    if( array_key_exists( $table_name, $rpbkp_has_truncated_table_cached ) && $rpbkp_has_truncated_table_cached[ $table_name ] == true ) {

        return $rpbkp_has_truncated_table_cached[ $table_name ];

    }

    $truncated_tables = rp_get_option('rpbkp_import_truncated_tables', array());

    if( !is_array( $truncated_tables ) ) {

        $truncated_tables = array();

    }

    if( in_array( $table_name, $truncated_tables ) ) {

        $rpbkp_has_truncated_table_cached[ $table_name ] = true;

        return true;

    }

    $rpbkp_has_truncated_table_cached[ $table_name ] = false;

    return false;

}

function rpbkp_process_single_image_import_row( $row ) {
    
    $imageName = $row->image_basename;

    $imagePath = str_replace( '{rpbkp_site_url}', '', $row->image_path );

    // lenght of imageName
    $imageNameLength = strlen( $imageName );

    // remove length of image name from the end of image path
    $imagePath = substr( $imagePath, 0, -$imageNameLength );

    $imagePath = str_replace('\\', '/', $imagePath);

    $folders = explode( "/", $imagePath );

    $abspath = rtrim( ABSPATH, '/' );

    $abspath = rtrim( $abspath, '\\' );

    $fullPath = $abspath . DIRECTORY_SEPARATOR;

    foreach( $folders as $folder ) {

        if( !empty( trim( $folder ) ) ) {

            $fullPath .= $folder . DIRECTORY_SEPARATOR;

            if( !file_exists( $fullPath ) ) {

                mkdir( $fullPath, 0777 );

            }

        }

    }

    $finalImagePath = $fullPath . $imageName;

    // save image
    file_put_contents( $finalImagePath, base64_decode( $row->image_value ) );

}

function rpbkp_process_single_table_import_row( $row ) {

    global $rpQuery;

    $backup_table_name = $row->backup_table_name;

    // check if has _rs_ in it
    if( strpos( $backup_table_name, '_rs_' ) !== FALSE ) {

        // explode by _rs_ and get the second part so wp_rs_brand will be brand
        $backup_table_name = explode( '_rs_', $backup_table_name );

        $backup_table_name = $backup_table_name[1]; // brand

        // prefix it again with rs_ so it will be rs_brand
        $backup_table_name = 'rs_' . $backup_table_name; // rs_brand

        // now prefix it with wp prefix so it will be {prefix}_rs_brand
        $backup_table_name = $rpQuery->prefix . $backup_table_name; // wp_rs_brand

    }

    // if backup has rs_sessions in it, skip it
    if( strpos( $backup_table_name, 'rs_sessions' ) !== FALSE ) {

        return;

    }

    $row = rpbkp_fix_site_url_in_all_import_columns( $row );

    rpbkp_truncate_the_table( $backup_table_name );

    unset( $row->backup_table_name );

    unset( $row->backup_type );

    // create key value pairs for insertion
    $keys = array();

    $values = array();

    foreach( $row as $key => $value ) {

        $keys[] = '`' . $key . '`';

        $values[] = "'" . rp_escape_sql( $value ) . "'";

    }

    $keys = implode( ', ', $keys );

    $values = implode( ', ', $values );

    $sql = "INSERT INTO {$backup_table_name} ({$keys}) VALUES ({$values})";

    $rpQuery->query( $sql );

}

function rpbkp_process_single_options_import_row( $row ) {

    $row = rpbkp_fix_site_url_in_all_import_columns( $row );

    // process saving the option
    rp_update_option( $row->option_name, $row->option_value );

}

function rpbkp_process_single_import_row( $row = null ) {

    if( empty( $row ) ) {

        return;

    }

    if( ($row->backup_type ?? '') == 'image' ) {

        rpbkp_process_single_image_import_row( $row );

    } else if( ($row->backup_type ?? '') == 'table' ) {

        rpbkp_process_single_table_import_row( $row );

    } else if( ($row->backup_type ?? '') == 'options' ) {

        rpbkp_process_single_options_import_row( $row );

    } else {

        // do nothing

    }

}

function rpbkp_validate_exported_file( $exportedFilePath = '' ) {

    if( file_exists( $exportedFilePath ) ) {

        $contentToSearch = new stdClass();

        $contentToSearch->status = 'success';

        $contentToSearch = rp_bkp_compression_process( $contentToSearch );

        $contentToSearchLength = strlen( $contentToSearch ) + 2;

        // read last $contentToSearchLength characters from the file
        $handler = fopen( $exportedFilePath, 'r' );

        fseek( $handler, -$contentToSearchLength, SEEK_END );

        // check if any line matches $contentToSearch
        while( !feof( $handler ) ) {

            $line = fgets( $handler );

            if( strpos( $line, $contentToSearch ) !== FALSE ) {

                fclose( $handler );

                return true;

            }

        }

        fclose( $handler );

    }

    return false;

}

function rpbkp_mark_file_as_successfully_exported( $backupFile = '' ) {

    if( !rpbkp_validate_exported_file( $backupFile ) ) {

        $successContent = new stdClass();

        $successContent->status = 'success';

        $successContent = rp_bkp_compression_process( $successContent );

        $successContent = "\n" . $successContent . "\n";

        rp_do_file_put_contents( $backupFile, $successContent );

    }

}

function rpbkp_is_running_any_process() {

    $rpBackupExportProcess = new RP_Easy_LongProcess('export');

    $rpBackupImportProcess = new RP_Easy_LongProcess('import');

    if( $rpBackupExportProcess->is_already_running() || $rpBackupImportProcess->is_already_running() ) {

        return true;

    }

    return false;

}

function rp_bkp_update_backup_file_status( $backupFile = '', $status = 0 ) {

    $allBackupFiles = rp_get_option( 'rpbkp_exported_files_status', array() );

    if( !is_array( $allBackupFiles ) ) {

        $allBackupFiles = array();

    }

    $allBackupFiles[ $backupFile ] = $status;

    rp_update_option( 'rpbkp_exported_files_status', $allBackupFiles );

}

function rp_bkp_get_in_process_backup_file() {

    static $inProcessBackupFile = false;

    if( $inProcessBackupFile !== false ) {

        return $inProcessBackupFile;

    }

    $inProcessBackupFile = '';

    $rpBackupExportProcess = new RP_Easy_LongProcess('export');

    if( $rpBackupExportProcess->is_already_running() ) {

        $uniqueBackupFileName = rp_get_option( 'rpbkp_export_unique_backup_file_name', '' );

        if( !empty( $uniqueBackupFileName ) ) {

            $inProcessBackupFile = $uniqueBackupFileName;

            return $inProcessBackupFile;

        }

    }

    return $inProcessBackupFile;

}

function rp_delete_files_starting_with_rp_import_prefix() {

    $backup_dir = rp_bkp_get_backup_dir();

    if( rp_create_directory_if_not_exists( $backup_dir ) == false ) {

        return false;

    }

    $files = glob( $backup_dir . DIRECTORY_SEPARATOR . 'rp_import_*' );

    foreach( $files as $file ) {

        if( is_file( $file ) ) {

            unlink( $file );

        }

    }

    return true;

}

function rp_bkp_get_backup_file_status( $backupFile = '' ) {

    $allBackupFiles = rp_get_option( 'rpbkp_exported_files_status', array() );

    if( !is_array( $allBackupFiles ) ) {

        $allBackupFiles = array();

    }

    $status = 'unknown';

    if( array_key_exists( $backupFile, $allBackupFiles ) ) {

        $status =  $allBackupFiles[ $backupFile ] == 1 ? 'success' : 'failed';

    }

    $inProcessBackupFile = rp_bkp_get_in_process_backup_file();

    if( $inProcessBackupFile == $backupFile ) {

        $status = 'processing';

    }

    if( $status == 'unknown' ) {
        
        $valid = rpbkp_validate_exported_file( $backupFile );

        if( $valid ) {

            rp_bkp_update_backup_file_status( $backupFile, 1 );

            $status = 'success';

        } else {

            rp_bkp_update_backup_file_status( $backupFile, 0 );

            $status = 'failed';

        }

    }

    return $status;

}

function rp_bkp_register_import_processes() {

    $rpBackupImportProcess = new RP_Easy_LongProcess('import');

    $rpBackupImportProcess->register_process('wp_cache_flush', function(){

        rp_safe_wp_cache_flush();

        return TRUE;

    });

    $rpBackupImportProcess->register_process('disable_smart_cache', function(){

        $org_status = rp_get_option( 'rp_smart_query_cache_status', '0' );

        // Disable Smart Query Cache
        rp_update_option( 'rp_smart_query_cache_status', '0' );

        // Save original status
        rp_update_option( 'rpbkp_import_original_smart_cache_status', $org_status );

        return TRUE;

    });

    $rpBackupImportProcess->register_process('clear_smart_cache', function(){

        global $rpQuery;

        $rpQuery->_clear_all_cache();

        return TRUE;

    });

    $rpBackupImportProcess->register_process('initialize_imported_file', function(){

        $imported_file = rp_bkp_get_last_importing_file();

        if( empty( $imported_file ) ) {

            throw new Exception('No file to import');

        }

        $maxSeek = filesize( $imported_file );

        // read first line
        // comebackfast
        list( $token, $lastSeek ) = read_file_line_by_line( $imported_file, 0 );

        if( empty( $token ) ) {

            throw new Exception('Unexpected Error. Backup unique token not found');

        }

        $encryption_key = rp_get_encyption_key_of_backup_from_base( trim($token) );

        if( empty( $encryption_key ) ) {

            $error_info = rp_get_last_base_request_error();

            $message = $error_info['message'] ?? '';

            throw new Exception('Unexpected Error. Failed to get encryption key from base. ' . $message);

        }

        rp_update_option( 'rpbkp_export_unique_backup_pass', $encryption_key );

        rp_update_option('rpbkp_import_imported_file_initialized', array(
            'file' => $imported_file,
            'max_seek' => $maxSeek,
            'last_seek' => $lastSeek
        ));

        return TRUE;

    });

    $rpBackupImportProcess->register_process('initializing_import', function(){

        // Empty process just to send initial progress
        sleep(1);

        return TRUE;

    });

    $rpBackupImportProcess->register_process('stopping_all_background_jobs', function(){

        // Empty process so that any background jobs that are running
        // can be stopped
        sleep(3);

        return TRUE;

    });

    $rpBackupImportProcess->register_process('delete_all_rp_options', function(){

        rp_delete_all_options_starting_with_rp_prefix();

        return TRUE;

    });

    $rpBackupImportProcess->register_process('processing_imported_file', function( $currentCls ){

        if( empty( $initialized_imported_file = $currentCls->get_cached('rpbkp_import_imported_file_initialized') ) ) {

            $initialized_imported_file = rp_get_option('rpbkp_import_imported_file_initialized', array());

            $currentCls->store_cache('rpbkp_import_imported_file_initialized', $initialized_imported_file);

        }

        if( empty( $initialized_imported_file ) ) {

            return TRUE;

        }

        $imported_file = $initialized_imported_file['file'] ?? '';

        $maxSeek = $initialized_imported_file['max_seek'] ?? 0;

        $lastSeek = $initialized_imported_file['last_seek'] ?? 0;

        if( $lastSeek < $maxSeek ) {

            $readLine = read_file_line_by_line( $imported_file, $lastSeek );

            if( $readLine == FALSE ) {

                // End of file reached
                return TRUE;

            }

            list( $line, $lastSeek ) = $readLine;

            // check if $line starts with $findPrefix
            $findPrefix = 'renc>';

            if( substr( $line, 0, strlen( $findPrefix ) ) == $findPrefix ) {

                $line = substr($line, strlen( $findPrefix ) );

                $line = rp_bkp_uncompress_process( $line, rp_get_encryption_password() );

            } else {

                $line = rp_bkp_uncompress_process( $line );

            }

            if( !empty( $line ) && !empty( $line->backup_type ?? '' ) ) {

                // do the single item processing here!
                rpbkp_process_single_import_row( $line );

            }

            $currentCls->store_cache('rpbkp_import_imported_file_initialized', array(
                'file' => $imported_file,
                'max_seek' => $maxSeek,
                'last_seek' => $lastSeek
            ));

            return FALSE;

        }

        return TRUE;

    });

    $rpBackupImportProcess->register_process('truncate_remaining_database_tables', function(){
    
        $rpTables = rp_filter_only_repair_plugin_tables();

        $truncated_tables = rp_get_option('rpbkp_import_truncated_tables', array());

        // loop through all tables, if table is not rs_sessions and not in the truncated_tables array, truncate it
        foreach( $rpTables as $theTable ) {

            // if table is rs_sessions, skip it
            if( strpos( $theTable, 'rs_sessions' ) !== FALSE ) {

                continue;

            }

            // If not already truncated, truncate it
            if( !in_array( $theTable, $truncated_tables ) ) {

                rpbkp_truncate_the_table( $theTable );

            }

        }
    
        return TRUE;
    
    });

    $rpBackupImportProcess->register_process('re_adding_indexes_to_all_tables', function(){
    
        // Fix Database Structure Automatically.
        dbsh_get_database_structure_handler()->auto_fix_database_structure();

        if( dbsh_get_database_structure_handler()->get_structure_status() === 'OK' ) {

            // Everything good. So this job will close automatically.
            return TRUE;

        } else {

            // It's partial meaning some indexes will add in the next request.
            return FALSE;

        }
    
    });

    $rpBackupImportProcess->register_process('import_is_done', function(){

        rp_delete_files_starting_with_rp_import_prefix();

        rp_update_option( 'rpbkp_export_unique_backup_pass', '' );

        rp_update_option( 'rpbkp_import_last_importing_file', '' );

        rp_update_option( 'rpbkp_import_current_process_start_trigger', '' );

        rp_update_option( 'rpbkp_import_current_process', '' );

        rp_update_option( 'rpbkp_import_unique_id', '' );

        rp_update_option('rpbkp_import_truncated_tables', array());

        rp_update_option('rpbkp_import_imported_file_initialized', array());

        rp_bkp_reset_dynamic_pricing_cron_options_on_import();

        _rp_separate_default_repair_translations_based_on_model_category();

        // Import is done

        return TRUE;

    });

    $rpBackupImportProcess->register_process('revert_smart_cache_status', function(){

        $org_status = rp_get_option( 'rpbkp_import_original_smart_cache_status', '0' );

        // Revert Smart Query Cache
        rp_update_option( 'rp_smart_query_cache_status', $org_status );

        return TRUE;

    });

    $rpBackupImportProcess->register_process('wp_cache_flush_on_success', function(){

        rp_safe_wp_cache_flush();

        return TRUE;

    });

    $rpBackupImportProcess->register_clear_process_callback(function(){

        rp_update_option( 'rpbkp_export_unique_backup_pass', '' );
    
        rp_update_option( 'rpbkp_import_current_process_start_trigger', '' );

        rp_update_option( 'rpbkp_import_current_process', '' );

        rp_update_option( 'rpbkp_import_unique_id', '' );

        rp_update_option( 'rpbkp_import_truncated_tables', array());
    
    });

    $rpBackupImportProcess->register_callback_on_timeout(function( $currentCls ){

        if( !empty( $initialized_imported_file = $currentCls->get_cached('rpbkp_import_imported_file_initialized') ) ) {

            $imported_file = $initialized_imported_file['file'] ?? '';

            $maxSeek = $initialized_imported_file['max_seek'] ?? 0;

            $lastSeek = $initialized_imported_file['last_seek'] ?? 0;

            // update last seek
            rp_update_option('rpbkp_import_imported_file_initialized', array(
                'file' => $imported_file,
                'max_seek' => $maxSeek,
                'last_seek' => $lastSeek
            ));

        }

    });

    return $rpBackupImportProcess;

}

function rp_bkp_register_export_processes() {

    $rpBackupExportProcess = new RP_Easy_LongProcess('export');

    $rpBackupExportProcess->register_process('wp_cache_flush', function(){

        rp_safe_wp_cache_flush();

        return TRUE;

    });

    $rpBackupExportProcess->register_process('disable_smart_cache', function(){

        $org_status = rp_get_option( 'rp_smart_query_cache_status', '0' );

        // Disable Smart Query Cache
        rp_update_option( 'rp_smart_query_cache_status', '0' );

        // Save original status
        rp_update_option( 'rpbkp_export_original_smart_cache_status', $org_status );

        return TRUE;

    });

    $rpBackupExportProcess->register_process('clear_smart_cache', function(){

        global $rpQuery;

        $rpQuery->_clear_all_cache();

        return TRUE;

    });

    $rpBackupExportProcess->register_process('get_unique_backup_file_name', function(){
    
        $uniqueBackupFileName = rp_get_unique_backup_file();
    
        rp_update_option( 'rpbkp_export_unique_backup_file_name', $uniqueBackupFileName );

        rp_bkp_update_backup_file_status( $uniqueBackupFileName, 0 );
    
        return TRUE;
    
    });

    $rpBackupExportProcess->register_process('save_token_info_in_file', function(){

        $backup_key = rp_get_option('rpbkp_export_unique_backup_key', '');

        if( empty( $backup_key ) ) {

            throw new Exception('Unexpected Error. Backup key not found');

        }

        $uniqueBackupFileName = rp_get_option( 'rpbkp_export_unique_backup_file_name', '' );

        if( empty( $uniqueBackupFileName ) ) {

            throw new Exception('Unexpected Error. Backup file name not found');

        }

        rp_do_file_put_contents( $uniqueBackupFileName, $backup_key );

        return TRUE;

    });

    $rpBackupExportProcess->register_process('initializing_export', function(){

        // Empty process just to send initial progress
        sleep(1);

        return TRUE;

    });

    $rpBackupExportProcess->register_process('stopping_all_background_jobs', function(){

        // Empty process so that any background jobs that are running
        // can be stopped
        sleep(3);

        return TRUE;

    });
    
    $rpBackupExportProcess->register_process('count_all_rp_options', function(){
        
        $rpOptions = rp_count_all_options_starting_with_rp_prefix();
    
        rp_update_option( 'rpbkp_export_total_db_rows', ($rpOptions[0]->total ?? 0) );
    
        return TRUE;
        
    });
    
    $rpBackupExportProcess->register_process('get_all_repairplugin_tables', function(){
    
        $rpTables = rp_filter_only_repair_plugin_tables();
    
        rp_update_option( 'rpbkp_export_all_rp_tables', $rpTables );
    
        return TRUE;
    
    });
    
    $rpBackupExportProcess->register_process('count_all_repairplugin_table_rows', function(){
    
        // get first table
        $rpTables = rp_get_option( 'rpbkp_export_all_rp_tables', array() );
    
        if( !is_array( $rpTables ) ) {
    
            $rpTables = array();
    
        }
    
        if( empty( $rpTables ) ) {
    
            return TRUE;
    
        }
    
        $firstTable = $rpTables[0] ?? '';
    
        $totalRows = rp_count_rows_of_table( $firstTable );
    
        $existingTableRowsCount = rp_get_option( 'rpbkp_export_total_db_rows', 0 );
    
        $newTableRowsCount = $existingTableRowsCount + $totalRows;
    
        rp_update_option( 'rpbkp_export_total_db_rows', $newTableRowsCount );
    
        // remove first table from the list
        unset( $rpTables[0] );
    
        $rpTables = array_values( $rpTables );
    
        rp_update_option( 'rpbkp_export_all_rp_tables', $rpTables );
    
        return FALSE;
    
    });
    
    $rpBackupExportProcess->register_process('create_backup_of_rp_options', function(){
    
        $offset = rp_get_option( 'rpbkp_export_options_table_offset', 0 );
    
        $uniqueBackupFileName = rp_get_option( 'rpbkp_export_unique_backup_file_name', '' );
    
        $limit = 100;
    
        $processedRows = rp_create_backup_of_rp_options( $uniqueBackupFileName, $offset, $limit);
    
        if( $processedRows == 0 ) {
    
            // No more rows to process
            return TRUE;
    
        }
    
        // update offset
        $offset = $offset + $limit;
    
        rp_update_option( 'rpbkp_export_options_table_offset', $offset );
    
        $processed_rows_opt = (int) rp_get_option( 'rpbkp_export_processed_rows', 0 );
    
        $processed_rows_opt = $processed_rows_opt + $processedRows;
    
        rp_update_option( 'rpbkp_export_processed_rows', $processed_rows_opt );
    
        return FALSE;
    
    });
    
    $rpBackupExportProcess->register_process('pending_process_tables', function(){
    
        $rpTables = rp_filter_only_repair_plugin_tables();
    
        rp_update_option( 'rpbkp_export_all_rp_tables', $rpTables );
    
        return TRUE;
    
    });
    
    $rpBackupExportProcess->register_process('do_table_rows_processing', function(){

        // get first pending table
        $rpTables = rp_get_option( 'rpbkp_export_all_rp_tables', array() );
    
        if( !is_array( $rpTables ) ) {
    
            $rpTables = array();
    
        }
    
        if( empty( $rpTables ) ) {
    
            // no more tables to process
            return TRUE;
    
        }
    
        $firstTable = $rpTables[0] ?? '';
    
        $offset = rp_get_option( 'rpbkp_table_offset_' . $firstTable, 0 );
    
        $limit = 100;
    
        $uniqueBackupFileName = rp_get_option( 'rpbkp_export_unique_backup_file_name', '' );
    
        $processedRows = rp_create_backup_of_table( $uniqueBackupFileName, $firstTable, $offset, $limit);
    
        if( $processedRows == 0 ) {
    
            // No more rows to process
            // remove first table from the list
            unset( $rpTables[0] );
    
            $rpTables = array_values( $rpTables );
    
            rp_update_option( 'rpbkp_export_all_rp_tables', $rpTables );
    
            return FALSE;
    
        }
    
        // update offset
        $offset = $offset + $limit;
    
        rp_update_option( 'rpbkp_table_offset_' . $firstTable, $offset );
    
        $processed_rows_opt = (int) rp_get_option( 'rpbkp_export_processed_rows', 0 );
    
        $processed_rows_opt = $processed_rows_opt + $processedRows;
    
        rp_update_option( 'rpbkp_export_processed_rows', $processed_rows_opt );
    
        return FALSE;
    
    });

    $rpBackupExportProcess->register_process('count_pending_processing_images', function(){
        
        $imageProcessingFile = rp_get_pending_processing_images_file();

        $totalImages = 0;
    
        if( file_exists( $imageProcessingFile ) ) {
            
            $file = file( $imageProcessingFile );
    
            $file = array_filter( $file, function( $value ) {
        
                return !empty( trim( $value ) );
        
            });
        
            $file = array_unique( $file );
        
            $file = array_values( $file );
        
            $totalImages = count( $file );
    
        }

        rp_update_option('rpbkp_total_pending_processing_images', $totalImages);

        return TRUE;

    });
    
    $rpBackupExportProcess->register_process('process_pending_images', function(){
    
        $imageProcessingFile = rp_get_pending_processing_images_file();
    
        if( !file_exists( $imageProcessingFile ) ) {
    
            // Looks like nothing to process
            return TRUE;
    
        }
        
        $file = file( $imageProcessingFile );
    
        $file = array_filter( $file, function( $value ) {
    
            return !empty( trim( $value ) );
    
        });
    
        $file = array_unique( $file );
    
        $file = array_values( $file );
    
        if( empty( $file ) ) {
    
            // Looks like nothing to process
            return TRUE;
    
        }
    
        $file = array_map( 'trim', $file );
    
        $imageContent = rp_bkp_get_image_file_for_export( $file[0] );
    
        if( $imageContent !== false ) {
    
            $uniqueBackupFileName = rp_get_option( 'rpbkp_export_unique_backup_file_name', '' );
    
            $imageBackup = new stdClass();
    
            $imageBackup->backup_type = 'image';
    
            $imageBackup->image_basename = basename( $file[0] );
    
            $imageBackup->image_path = $file[0];
    
            $imageBackup->image_value = base64_encode( $imageContent );
    
            $imageContent = rp_bkp_compression_process( $imageBackup );
    
            $imageContent = "\n" . $imageContent . "\n";
    
            rp_do_file_put_contents( $uniqueBackupFileName, $imageContent );
            
        }
    
        // remove first line from the file
        unset( $file[0] );
    
        $file = array_values( $file );
    
        $file = implode( "\n", $file );
    
        file_put_contents( $imageProcessingFile, $file );
    
        return FALSE;
        
    });

    $rpBackupExportProcess->register_process('mark_file_as_successfully_exported', function(){

        // mark file as valid using rpbkp_mark_file_as_successfully_exported()
        $uniqueBackupFileName = rp_get_option( 'rpbkp_export_unique_backup_file_name', '' );
    
        if( !empty( $uniqueBackupFileName ) ) {
    
            rpbkp_mark_file_as_successfully_exported( $uniqueBackupFileName );
    
        }

        rp_update_option( 'rpbkp_export_last_exported_file', $uniqueBackupFileName );

        rp_bkp_update_backup_file_status( $uniqueBackupFileName, 1 );

        return TRUE;

    });

    $rpBackupExportProcess->register_process('revert_smart_cache_status', function(){

        $org_status = rp_get_option( 'rpbkp_export_original_smart_cache_status', '0' );

        // Revert Smart Query Cache
        rp_update_option( 'rp_smart_query_cache_status', $org_status );

        return TRUE;

    });

    $rpBackupExportProcess->register_process('wp_cache_flush_on_success', function(){

        rp_safe_wp_cache_flush();

        return TRUE;

    });
    
    $rpBackupExportProcess->register_clear_process_callback(function(){
    
        rpbkp_clear_export_process_callback();
    
    });

    return $rpBackupExportProcess;

}

function rpbkp_clear_export_process_callback() {

    rp_update_option( 'rpbkp_export_unique_backup_key', '' );

    rp_update_option( 'rpbkp_export_unique_backup_pass', '' );

    rp_update_option( 'rpbkp_export_current_process_start_trigger', '' );
    
    rp_update_option( 'rpbkp_export_current_process', '' );

    rp_update_option( 'rpbkp_export_unique_id', '' );

    rp_update_option( 'rpbkp_export_unique_backup_file_name', '' );

    rp_update_option( 'rpbkp_export_total_db_rows', 0 );

    rp_update_option( 'rpbkp_export_processed_rows', 0 );

    rp_update_option( 'rpbkp_export_options_table_offset', 0 );

    rp_update_option( 'rpbkp_export_all_rp_tables', array() );

    rp_update_option( 'rpbkp_total_pending_processing_images', 0 );

    $imageProcessingFile = rp_get_pending_processing_images_file();

    if( !empty( $imageProcessingFile ) ) {

        if( file_exists( $imageProcessingFile ) ) {

            unlink( $imageProcessingFile );

        }

    }

    rp_remove_rpbkp_table_offets();

}

// ------------ EXPORT PROCESS -------------- 

// $rpBackupExportProcess->safe_run();

// echo "<pre>";

// print_r( $rpBackupExportProcess->get_errors() );

// echo "</pre>";

// $rpBackupExportProcess->clear_errors();

// exit;

// ------------ IMPORT PROCESS -------------- 

function read_file_line_by_line( $file = '', $seek = 0 ) {

    $handler = fopen( $file, 'r' );

    fseek( $handler, $seek );

    $totalCharsRead = 0;

    $line = '';

    if( !feof( $handler ) ) {

        $line = fgets( $handler );

        $totalCharsRead = strlen( $line );

    } else {

        return FALSE;

    }

    fclose( $handler );

    $lastSeek = $seek + $totalCharsRead;

    return array(
        $line,
        $lastSeek
    );

}

function rp_bkp_get_last_importing_file() {

    $last_importing_file = rp_get_option('rpbkp_import_last_importing_file', '');

    if( empty( $last_importing_file ) ) {

        return '';

    }

    $testbackup_file = rp_bkp_get_backup_dir() . DIRECTORY_SEPARATOR . $last_importing_file;

    return $testbackup_file;

}

function rp_start_export_process_repairplugin() {

    if(!current_user_can('activate_plugins')) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'You are not allowed to do this!'
  
        ));

        exit;

    }

    rp_verify_csrf_token_for_ajax('backups');

    if( empty( $_POST['start'] ?? '' ) ) {
        
        // invalid request
        echo json_encode(array(

            'status' => false,
  
            'message' => 'Invalid request'
  
        ));

        exit;

    }

    if( rpbkp_is_running_any_process() == true ) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'Backup or Import process is already running!'
  
        ));

        exit;

    }

    $tokens = rp_get_unique_backup_tokens_from_base();

    if( empty( $tokens ) ) {

        $error_info = rp_get_last_base_request_error();

        $message = $error_info['message'] ?? 'Something went wrong!';

        echo json_encode(array(

            'status' => false,
  
            'message' => $message
  
        ));

        exit;

    }

    $rpBackupExportProcess = rp_bkp_register_export_processes();

    $uniqueId = rp_create_unique_random_id();

    $rpBackupExportProcess->trigger_start( $uniqueId );

    rp_update_option('rpbkp_export_unique_backup_key', $tokens['token_1']);

    rp_update_option('rpbkp_export_unique_backup_pass', $tokens['token_2']);

    echo json_encode(array(

        'status' => true,

        'message' => 'Backup process started!'

    ));

    exit;

}

rp_ajax_for_admin('rp_start_export_process_repairplugin', 'rp_start_export_process_repairplugin');

function rp_bkp_create_download_url( $backupFile = '' ) {
    
    $abspath = rtrim( ABSPATH, '/' );

    $abspath = rtrim( $abspath, '\\' );

    $abspath = str_replace( '\\', '/', $abspath);

    $abspath = str_replace( '/', DIRECTORY_SEPARATOR, $abspath );

    $file_url = str_replace( $abspath, '{rpbkp_site_url}', $backupFile );

    $site_url = rp_get_site_url_while_import();

    $file_url = str_replace( '{rpbkp_site_url}', $site_url, $file_url );

    $file_url = str_replace( DIRECTORY_SEPARATOR, '/', $file_url );

    return $file_url;

}

function rp_get_export_process_progress_repairplugin() {

    rp_verify_csrf_token_for_ajax('backups');

    $rpBackupExportProcess = rp_bkp_register_export_processes();

    if( !$rpBackupExportProcess->is_already_running() ) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'Looks like no export process is running'
  
        ));

        exit;

    }

    // Here we can run the process!

    $rpBackupExportProcess->safe_run();

    $lastError = $rpBackupExportProcess->last_error;

    if( empty( $lastError ) ) {
        
        // Everything is good

        // get_unique_backup_file_name
        // count_all_rp_options
        // get_all_repairplugin_tables
        // count_all_repairplugin_table_rows
        // create_backup_of_rp_options
        // pending_process_tables
        // do_table_rows_processing
        // count_pending_processing_images
        // process_pending_images

        $currentProcess = rp_get_option('rpbkp_export_current_process', '');

        $percent = 5;

        $total_rows = 0;

        $done_rows = 0;

        if( $currentProcess == 'do_table_rows_processing' ) {

            $processed_rows_opt = (int) rp_get_option( 'rpbkp_export_processed_rows', 0 );

            $total_rows = (int) rp_get_option( 'rpbkp_export_total_db_rows' , 0 );

            $percent = 5 + ( ( $processed_rows_opt / $total_rows ) * 95 );

            $done_rows = $processed_rows_opt;

        }

        if( $currentProcess == 'process_pending_images' ) {

            $imageProcessingFile = rp_get_pending_processing_images_file();

            $pendingImages = 0;
        
            if( file_exists( $imageProcessingFile ) ) {
                
                $file = file( $imageProcessingFile );
        
                $file = array_filter( $file, function( $value ) {
            
                    return !empty( trim( $value ) );
            
                });
            
                $file = array_unique( $file );
            
                $file = array_values( $file );
            
                $pendingImages = count( $file );
        
            }

            $totalImages = rp_get_option('rpbkp_total_pending_processing_images', 0);

            $doneImages = $totalImages - $pendingImages;

            $percent = 5 + ( ( $doneImages / $totalImages ) * 95 );

            $total_rows = $totalImages;

            $done_rows = $doneImages;

        }

        if( empty( $currentProcess ) ) {

            $last_exported_file = rp_get_option('rpbkp_export_last_exported_file', '');

            $link = '#';

            if( !empty( $last_exported_file ) && file_exists( $last_exported_file ) ) {

                $link = rp_bkp_create_download_url( $last_exported_file );

            }

            _rp_set_default_tiemzone();

            $allBackupFiles = rp_bkp_get_all_backup_files();

            ob_start();

            require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'html' . DIRECTORY_SEPARATOR . 'import_export_table_markup.php';

            $html_markup = ob_get_clean();

            // Everything is done!

            echo json_encode(array(

                'status' => true,
      
                'type' => 'done',

                'file_url' => $link,

                'html_markup' => $html_markup,
      
            ));

        } else {

            echo json_encode(array(

                'status' => true,
      
                'type' => 'processing',

                'process' => $currentProcess,

                'percent' => $percent,

                'total_rows' => $total_rows,

                'done_rows' => $done_rows
      
            ));

        }

        exit;

    } else {

        $lastErrorMessage = $lastError['message'] . " on line " . $lastError['line'] . " in file " . $lastError['file'] . " the running process was " . $lastError['error_at_process'];

        echo json_encode(array(

            'status' => false,
  
            'message' => $lastErrorMessage
  
        ));

        exit;

    }

}

rp_add_quick_ajax_for_admin('rp_get_export_process_progress_repairplugin', 'rp_get_export_process_progress_repairplugin');

function rp_remove_exported_file_repairplugin() {

    if(!current_user_can('activate_plugins')) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'You are not allowed to do this!'
  
        ));

        exit;

    }

    rp_verify_csrf_token_for_ajax('backups');

    if( empty( $_POST['remove'] ?? '' ) || empty( $_POST['file_name'] ?? '' ) ) {
        
        // invalid request
        echo json_encode(array(

            'status' => false,
  
            'message' => 'Invalid request'
  
        ));

        exit;

    }

    $file_name = $_POST['file_name'] ?? '';

    $required_in_filename = array(
        'rp_backup_',
        '.rpdata'
    );

    foreach( $required_in_filename as $required ) {

        if( strpos( $file_name, $required ) === FALSE ) {

            echo json_encode(array(

                'status' => false,
      
                'message' => 'Invalid file name'
      
            ));
    
            exit;

        }

    }

    $prettifyFileName = str_replace( array( '/', '\\' ), '', $file_name );

    $backup_dir = rp_bkp_get_backup_dir();

    $file_path = $backup_dir . DIRECTORY_SEPARATOR . $prettifyFileName;

    if( !file_exists( $file_path ) ) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'File does not exists'
  
        ));

        exit;

    }

    @unlink( $file_path );

    _rp_set_default_tiemzone();

    $allBackupFiles = rp_bkp_get_all_backup_files();

    ob_start();

    require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'html' . DIRECTORY_SEPARATOR . 'import_export_table_markup.php';

    $html_markup = ob_get_clean();

    echo json_encode(array(

        'status' => true,

        'message' => 'File removed successfully!',

        'html_markup' => $html_markup

    ));

    exit;

}

rp_ajax_for_admin('rp_remove_exported_file_repairplugin', 'rp_remove_exported_file_repairplugin');

function rp_restore_exported_file_repairplugin() {

    if(!current_user_can('activate_plugins')) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'You are not allowed to do this!'
  
        ));

        exit;

    }

    rp_verify_csrf_token_for_ajax('backups');

    if( empty( $_POST['restore'] ?? '' ) || empty( $_POST['file_name'] ?? '' ) ) {
        
        // invalid request
        echo json_encode(array(

            'status' => false,
  
            'message' => 'Invalid request'
  
        ));

        exit;

    }

    $file_name = $_POST['file_name'] ?? '';

    $required_in_filename = array(
        'rp_backup_',
        '.rpdata'
    );

    foreach( $required_in_filename as $required ) {

        if( strpos( $file_name, $required ) === FALSE ) {

            echo json_encode(array(

                'status' => false,
      
                'message' => 'Invalid file name'
      
            ));
    
            exit;

        }

    }

    $prettifyFileName = str_replace( array( '/', '\\' ), '', $file_name );

    $backup_dir = rp_bkp_get_backup_dir();

    $file_path = $backup_dir . DIRECTORY_SEPARATOR . $prettifyFileName;

    if( !file_exists( $file_path ) ) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'File does not exists'
  
        ));

        exit;

    }

    // file exists
    $uniqueImportFileName = rp_create_unique_import_file();

    $uniqueImportFile = $backup_dir . DIRECTORY_SEPARATOR . $uniqueImportFileName;

    // copy content from $file_path to $uniqueImportFile
    copy( $file_path, $uniqueImportFile );

    if( !rpbkp_validate_exported_file( $uniqueImportFile ) ) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'Looks like the imported file is not valid or corrupted'
  
        ));

        exit;

    }

    // file is successfully uploaded and validated
    // now start the import process

    $rpBackupImportProcess = rp_bkp_register_import_processes();

    $uniqueId = rp_create_unique_random_id();

    $rpBackupImportProcess->trigger_start( $uniqueId );

    rp_update_option( 'rpbkp_import_last_importing_file', $uniqueImportFileName );

    echo json_encode(array(

        'status' => true,

        'message' => 'Import process started!'

    ));

    exit;

}

rp_ajax_for_admin('rp_restore_exported_file_repairplugin', 'rp_restore_exported_file_repairplugin');

function rp_create_unique_import_file() {

    $uniqueImportFileName = 'rp_import_' . date('Y_m_d_H_i_s') . '.rpdata';

    return $uniqueImportFileName;

}

function rp_handle_import_file_upload_in_chunks() {
    
    if( (($_POST['image_status'] ?? '') != 'chunk') ) {

        return;

    }

    $import_file = $_FILES['import_file'] ?? array();

    if( !empty( $import_file ) ) {

        // move file 
        $backup_dir = rp_bkp_get_backup_dir();

        if( ($_POST['offset'] ?? 0) == 0 ) {
            
            // is first chunk
            $uniqueImportFileName = rp_create_unique_import_file();

            rp_update_option( 'rpbkp_unique_file_import_name_for_upload_chunk', $uniqueImportFileName );

        } else {

            $uniqueImportFileName = rp_get_option( 'rpbkp_unique_file_import_name_for_upload_chunk', '' );

        }

        if( empty( $uniqueImportFileName ) ) {

            echo json_encode(array(

                'status' => false,
      
                'message' => 'Invalid request'
      
            ));
    
            exit;

        }

        $uniqueChunkName = $uniqueImportFileName . '.part';

        $uniqueImportFile = $backup_dir . DIRECTORY_SEPARATOR . $uniqueImportFileName;

        $uniqueChunkFile = $backup_dir . DIRECTORY_SEPARATOR . $uniqueChunkName;

        if( !move_uploaded_file( $import_file['tmp_name'], $uniqueChunkFile ) ) {

            echo json_encode(array(

                'status' => false,
      
                'message' => 'Failed to move uploaded file'
      
            ));
    
            exit;

        }

        // read the file and append to the main file
        $chunkContent = file_get_contents( $uniqueChunkFile );

        if( file_exists( $uniqueImportFile ) ) {

            file_put_contents( $uniqueImportFile, $chunkContent, FILE_APPEND );

        } else {

            file_put_contents( $uniqueImportFile, $chunkContent );

        }

        // delete the chunk file
        unlink( $uniqueChunkFile );

        echo json_encode(array(

            'status' => true,
  
            'message' => 'Chunk uploaded successfully!',

            'import_file_name' => $uniqueImportFileName
  
        ));

        exit;

    }

    echo json_encode(array(

        'status' => false,

        'message' => 'Invalid request'

    ));

    exit;

}

function rp_upload_import_file_repairplugin() {

    if(!current_user_can('activate_plugins')) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'You are not allowed to do this!'
  
        ));

        exit;

    }

    rp_verify_csrf_token_for_ajax('backups');

    if( rpbkp_is_running_any_process() == true ) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'Backup or Import process is already running!'
  
        ));

        exit;

    }

    rp_handle_import_file_upload_in_chunks();

    $uploaded_filename = $_POST['import_file_name'] ?? '';

    if( empty( $uploaded_filename ) ) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'Please select a valid file'
  
        ));

        exit;

    }

    $required_in_filename = array(
        'rp_import_',
        '.rpdata'
    );

    foreach( $required_in_filename as $required ) {

        if( strpos( $uploaded_filename, $required ) === FALSE ) {

            echo json_encode(array(

                'status' => false,
      
                'message' => 'Invalid file name'
      
            ));
    
            exit;

        }

    }

    $backup_dir = rp_bkp_get_backup_dir();

    $uniqueImportFile = $backup_dir . DIRECTORY_SEPARATOR . $uploaded_filename;

    if( !rpbkp_validate_exported_file( $uniqueImportFile ) ) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'Looks like the imported file is not valid or corrupted'
  
        ));

        exit;

    }

    // file is successfully uploaded and validated
    // now start the import process

    $rpBackupImportProcess = rp_bkp_register_import_processes();

    $uniqueId = rp_create_unique_random_id();

    $rpBackupImportProcess->trigger_start( $uniqueId );

    rp_update_option( 'rpbkp_import_last_importing_file', $uploaded_filename );

    echo json_encode(array(

        'status' => true,

        'message' => 'Import process started!'

    ));

    exit;

}

rp_ajax_for_admin('rp_upload_import_file_repairplugin', 'rp_upload_import_file_repairplugin');

function rp_get_import_process_progress_repairplugin() {

    rp_verify_csrf_token_for_ajax('backups');

    $rpBackupImportProcess = rp_bkp_register_import_processes();

    if( !$rpBackupImportProcess->is_already_running() ) {

        echo json_encode(array(

            'status' => false,
  
            'message' => 'Looks like no import process is running'
  
        ));

        exit;

    }

    // Here we can run the process!

    $rpBackupImportProcess->safe_run();

    $lastError = $rpBackupImportProcess->last_error;

    if( empty( $lastError ) ) {
        
        // Everything is good

        // initialize_imported_file
        // initializing_import
        // stopping_all_background_jobs
        // delete_all_rp_options
        // processing_imported_file
        // import_is_done

        $currentProcess = rp_get_option('rpbkp_import_current_process', '');

        $percent = 5;

        $total_rows = 0;

        $done_rows = 0;

        if( $currentProcess == 'processing_imported_file' ) {

            $initialized_imported_file = rp_get_option('rpbkp_import_imported_file_initialized', array());

            $last_seek = $initialized_imported_file['last_seek'];

            $max_seek = $initialized_imported_file['max_seek'];

            $percent = 5 + ( ( $last_seek / $max_seek ) * 95 );

            $total_rows = $max_seek;

            $done_rows = $last_seek;

        }

        if( empty( $currentProcess ) ) {

            // Everything is done!

            echo json_encode(array(

                'status' => true,
      
                'type' => 'done'
      
            ));

        } else {

            echo json_encode(array(

                'status' => true,
      
                'type' => 'processing',

                'process' => $currentProcess,

                'percent' => $percent,

                'total_rows' => $total_rows,

                'done_rows' => $done_rows
      
            ));

        }

        exit;

    } else {

        $lastErrorMessage = $lastError['message'] . " on line " . $lastError['line'] . " in file " . $lastError['file'] . " the running process was " . $lastError['error_at_process'];

        echo json_encode(array(

            'status' => false,
  
            'message' => $lastErrorMessage
  
        ));

        exit;

    }

}

rp_add_quick_ajax_for_admin('rp_get_import_process_progress_repairplugin', 'rp_get_import_process_progress_repairplugin');

function rp_get_encyption_key_of_backup_from_base( $token = '' ) {

    $payload = array('backup_key' => $token);

    $uri = 'Endpoints/get_encyption_key_of_backup';

    $response = rp_create_request_to_base( $uri, $payload );

    if( empty( $response ) ) {

        return FALSE;

    }

    if( !property_exists( $response, 'encryption_key' ) ) {

        return FALSE;

    }

    return $response->encryption_key;

}

function rp_get_unique_backup_tokens_from_base() {

    $uri = 'Endpoints/get_unique_backup_tokens';

    $response = rp_create_request_to_base( $uri );

    if( empty( $response ) ) {

        return FALSE;

    }

    if( !property_exists( $response, 'token_1' ) || !property_exists( $response, 'token_2' ) ) {

        return FALSE;

    }

    return array(
        'token_1' => $response->token_1,
        'token_2' => $response->token_2
    );

}

function rp_get_last_base_request_error() {

    global $rp_request_to_base_error;
    global $rp_request_to_base_error_type;

    return array(
        'message' => $rp_request_to_base_error,
        'type' => $rp_request_to_base_error_type
    );

}

function rp_create_request_to_base( $uri = '', $payload = array() ) {

    global $rp_request_to_base_error;
    global $rp_request_to_base_error_type;

    $url = WP_REPAIR_BASE_SERVER_URL . $uri;

    $license_key = rp_get_option('Repairplugin_lic_Key', '');

    $license_email = rp_get_option('Repairplugin_lic_email', '');

    $license_key = trim( $license_key );
    
    // replace tab space from license key
    $license_key = str_replace("\t", "", $license_key);

    if(empty($license_key)) {

        $rp_request_to_base_error = 'License key is empty';

        $rp_request_to_base_error_type = 'request_error';
        
        return FALSE;

    }

    $rp_base_class = new RepairpluginBase(WP_REPAIR_PLUGIN_FILE);

    $license_app_version = $rp_base_class->getCurrentVersion();

    $domain = $rp_base_class->getDomain();

    $payload['license_key'] = $license_key;

    $payload['license_email'] = $license_email;

    $payload['license_app_version'] = $license_app_version;

    $payload['license_domain'] = $domain;

    $result = \rp_curl_post( $url, $payload, 15 ); // 15 seconds timeout

    if( empty( $result ) ) {

        $rp_request_to_base_error = 'Could not create request to server';

        $rp_request_to_base_error_type = 'request_error';

        return FALSE;

    }

    list( $info, $response, $error ) = $result;

    if($info['http_code'] != '200') {

        $rp_request_to_base_error = 'Request failed with status code ' . $info['http_code'];

        $rp_request_to_base_error_type = 'request_error';
        
        return FALSE;

    }

    $data = array();

    if(!empty($response)) {
        try {
            $data = json_decode($response);
        } catch (\Exception $e) {

        }
    }

    if(!empty($data) && property_exists($data, 'status') && ($data->status === TRUE || $data->status === 1)) {
        
        return $data;

    }

    if(!empty($data) && property_exists($data, 'message')) {

        $rp_request_to_base_error = $data->message;

        $rp_request_to_base_error_type = 'response_error';

        return FALSE;

    }

    $rp_request_to_base_error = 'Invalid response from server';

    $rp_request_to_base_error_type = 'response_error';
    
    return FALSE;

}

// 1. make sure file exists
// 2. get file contents
// 3. check first 10 lines line by line
// and find a line with Version:
function rp_read_version_of_file( $file = '' ) {

    if( !file_exists( $file ) ) {

        return FALSE;

    }

    $handler = fopen( $file, 'r' );

    $version = '';

    $line = '';

    $lineCount = 0;

    while( !feof( $handler ) ) {

        $line = fgets( $handler );

        $lineCount++;

        if( $lineCount > 10 ) {

            break;

        }

        if( strpos( $line, 'Version:' ) !== FALSE ) {

            $version = str_replace( 'Version:', '', $line );

            $version = trim( $version );

            break;

        }

    }

    fclose( $handler );

    return $version;

}

function _rp_keys_compression_algorithm( $data = null ) {

    if( empty( $data ) || !is_array( $data ) || !isset( $data[0] ) || !is_object( $data[0] ?? '' ) ) {

        if( !empty( $data ) && is_array( $data ) ) {

            $data = array_values( $data );
            
        } else {

            return array( $data, array() );

        }

    }

    $alphabets = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    $replaced_keys = array();

    $count = 0;

    $final_data = array();

    foreach( $data as $index => $row ) {

        $newRow = new stdClass();

        foreach( $row as $key => $value ) {

            if( ( $replacement = array_search( $key, $replaced_keys ) ) === FALSE ) {

                $replacement = $alphabets[$count];

                $replaced_keys[$replacement] = $key;

                $count++;

            }

            $newRow->{$replacement} = $value;

        }

        $final_data[] = $newRow;

    }

    return array( $final_data, $replaced_keys );

}

F1le Man4ger