prefix . "addefend" ); require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); // create the addefend table register_activation_hook(ADDEFEND_PLUGIN_PHP_FILE, 'addefend_create_table'); function addefend_create_table() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE ".ADDEFEND_TABLE_NAME." ( id mediumint(9) NOT NULL, script text NOT NULL, PRIMARY KEY (id) ) $charset_collate;"; dbDelta( $sql ); } // add custom cron schedules add_filter( 'cron_schedules', 'addefend_add_script_update_frequency'); function addefend_add_script_update_frequency($schedules ) { $schedules['everyfiveminutes'] = array( 'interval' => 300, 'display' => __('Every Five Minutes') ); // this is for testing $schedules['every10seconds'] = array( 'interval' => 10, 'display' => __('Every ten Seconds') ); return $schedules; } // activate the scheduling when the plugin is activated register_activation_hook(ADDEFEND_PLUGIN_PHP_FILE, 'addefend_activate_scheduling'); function addefend_activate_scheduling() { if ( !wp_next_scheduled( 'out_of_date_script' ) ) { wp_schedule_event( time(), 'everyfiveminutes', 'out_of_date_script'); } } // the new script is being stored in a dedicated table in the wordpress database add_action('out_of_date_script', 'download_addefend_script'); function download_addefend_script() { addefend_log('ADDEFEND -- TRACE : 5 minutes have passed !'); $script_URL = get_option( 'addefend_script_URL' ); // API call $response = wp_remote_get($script_URL); // handling the response if (is_wp_error( $response ) || wp_remote_retrieve_response_code($response) == 404){ if ( is_wp_error( $response ) ) { $error_string = $response->get_error_message(); addefend_log('ADDEFEND -- ERROR : Script download error :' . $error_string); }else { addefend_log('ADDEFEND -- ERROR : 404 script not found'); } addefend_log('ADDEFEND -- ERROR : Sticking with the old script'); }else{ addefend_log('ADDEFEND -- INFO : Script is successfully downloaded'); $new_script = wp_remote_retrieve_body($response); global $wpdb; $script_inserted = $wpdb->replace( ADDEFEND_TABLE_NAME, array( 'id' => '1', 'script' => $new_script ) ); if(!$script_inserted){ addefend_log('ADDEFEND -- ERROR : script couldn\'t be saved in the database'); } else{ addefend_log('ADDEFEND -- INFO : script is successfully saved in the database'); } } } // inject the script in the footer add_action('wp_footer', 'inject_addefend_script'); function inject_addefend_script(){ global $wpdb; $addefend_script = $wpdb->get_var("SELECT script FROM ".ADDEFEND_TABLE_NAME." WHERE (id = '1')"); echo ''; addefend_log('ADDEFEND -- TRACE : Script injected in the footer'); } // desactivate the scheduling and clear the cache when the plugin is deactivated register_deactivation_hook(ADDEFEND_PLUGIN_PHP_FILE, 'addefend_deactivate_scheduling'); function addefend_deactivate_scheduling() { wp_clear_scheduled_hook('out_of_date_script'); global $wpdb; $wpdb->delete( ADDEFEND_TABLE_NAME, array( 'ID' => 1 ) ); }