From 7460b187b9b9e73c9bcad0709302a7683f956087 Mon Sep 17 00:00:00 2001 From: leocaseiro Date: Wed, 31 Aug 2016 08:03:05 +1000 Subject: [PATCH 1/5] wip(Import/Export): Missing ajax_nonce and checkbox for truncate database --- README.md | 6 ++ custom-options-plus.php | 118 ++++++++++++++++++++++++++++++---------- js/import-export.js | 87 +++++++++++++++++++++++++++++ readme.txt | 8 ++- 4 files changed, 189 insertions(+), 30 deletions(-) create mode 100644 js/import-export.js diff --git a/README.md b/README.md index cc9cef2..dd800e3 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,12 @@ FAQ (Frequently Asked Questions) Changelog -------------- +**1.7.0** + +* Add Settings link on Plugins Page +* Add Import and Export (Thanks @lucasbhjf for his contribution) + + **1.6** * Set all fields as required [Fix Issue #6](https://github.com/leocaseiro/Wordpress-Plugin-Custom-Options-Plus/issues/6) diff --git a/custom-options-plus.php b/custom-options-plus.php index d24c9dd..e8d2f92 100644 --- a/custom-options-plus.php +++ b/custom-options-plus.php @@ -40,7 +40,7 @@ //Added on 1.5 define( 'COP_OPTIONS_PREFIX', 'cop_' ); -define( 'COP_PLUGIN_VERSION', '1.6' ); +define( 'COP_PLUGIN_VERSION', '1.7.0' ); global $wpdb, $COP_TABLE; define( 'COP_TABLE', $wpdb->prefix . 'custom_options_plus' ); @@ -72,7 +72,17 @@ function cop_setup() { register_activation_hook( __FILE__, 'cop_setup' ); -//Create a Menu Custom Options Plus in Settings +// Add settings link to Plugins Page +function cop_plugin_add_settings_link( $links ) { + $settings_link = '' . __( 'Settings' ) . ''; + array_push( $links, $settings_link ); + return $links; +} +$plugin = plugin_basename( __FILE__ ); +add_filter( "plugin_action_links_$plugin", 'cop_plugin_add_settings_link' ); + + +// Create a Menu Custom Options Plus in Settings add_action('admin_menu', 'cop_add_menu'); function cop_add_menu() { @@ -81,63 +91,70 @@ function cop_add_menu() { } +// Insert JS and CSS function cop_load_js_and_css() { - wp_register_script( 'functions.js', COP_PLUGIN_DIR . 'functions.js', array('jquery'), COP_PLUGIN_VERSION ); - wp_register_script( 'jquery.stringToSlug.min.js', COP_PLUGIN_DIR . 'jquery.stringToSlug.min.js', array('jquery'), COP_PLUGIN_VERSION ); +// wp_register_script( 'jquery.stringToSlug.min.js', COP_PLUGIN_URL . '/js/jquery.stringToSlug.min.js', array('jquery'), COP_PLUGIN_VERSION, true ); +// wp_register_script( 'cop-functions', COP_PLUGIN_URL . '/js/functions.js', array('jquery', 'jquery.stringToSlug.min.js'), COP_PLUGIN_VERSION, true ); +// wp_register_script( 'cop-import-export', COP_PLUGIN_URL . '/js/import-export.js', array('jquery', ), null, true ); } -function cop_insert() { +// Insert on Database +function cop_insert( $row ) { global $wpdb; - $_POST['label'] = stripslashes_deep(filter_var($_POST['label'], FILTER_SANITIZE_SPECIAL_CHARS)); - $_POST['name'] = stripslashes_deep(filter_var($_POST['name'], FILTER_SANITIZE_SPECIAL_CHARS)); - $_POST['value'] = stripslashes_deep(filter_var($_POST['value'], FILTER_UNSAFE_RAW)); + $row['label'] = stripslashes_deep(filter_var($row['label'], FILTER_SANITIZE_SPECIAL_CHARS)); + $row['name'] = stripslashes_deep(filter_var($row['name'], FILTER_SANITIZE_SPECIAL_CHARS)); + $row['value'] = stripslashes_deep(filter_var($row['value'], FILTER_UNSAFE_RAW)); return $wpdb->insert( COP_TABLE, array( - 'label' => $_POST['label'], - 'name' => $_POST['name'], - 'value' => stripslashes($_POST['value']) + 'label' => $row['label'], + 'name' => $row['name'], + 'value' => stripslashes($row['value']) ), array('%s','%s','%s') ); } -function cop_update() { +// Update on Database +function cop_update( $row ) { global $wpdb; - $_POST['id'] = filter_var($_POST['id'], FILTER_VALIDATE_INT); - $_POST['label'] = stripslashes_deep(filter_var($_POST['label'], FILTER_SANITIZE_SPECIAL_CHARS)); - $_POST['name'] = stripslashes_deep(filter_var($_POST['name'], FILTER_SANITIZE_SPECIAL_CHARS)); - $_POST['value'] = stripslashes_deep(filter_var($_POST['value'], FILTER_UNSAFE_RAW)); + $row['id'] = filter_var($row['id'], FILTER_VALIDATE_INT); + $row['label'] = stripslashes_deep(filter_var($row['label'], FILTER_SANITIZE_SPECIAL_CHARS)); + $row['name'] = stripslashes_deep(filter_var($row['name'], FILTER_SANITIZE_SPECIAL_CHARS)); + $row['value'] = stripslashes_deep(filter_var($row['value'], FILTER_UNSAFE_RAW)); return $wpdb->update( COP_TABLE, array( - 'label' => $_POST['label'], - 'name' => $_POST['name'], - 'value' => stripslashes($_POST['value']) + 'label' => $row['label'], + 'name' => $row['name'], + 'value' => stripslashes($row['value']) ), - array ('id' => $_POST['id']), + array ('id' => $row['id']), array('%s','%s','%s'), array('%d') ); } +// Delete on Database function cop_delete( $id ) { global $wpdb, $COP_TABLE; return $wpdb->query($wpdb->prepare("DELETE FROM $COP_TABLE WHERE id = %d ", $id) ); } +// Get all options from Database function cop_get_options() { global $wpdb, $COP_TABLE; return $wpdb->get_results("SELECT id, label, name, value FROM $COP_TABLE ORDER BY label ASC"); } +// Get single option from Database function cop_get_option( $id ) { global $wpdb, $COP_TABLE; return $wpdb->get_row($wpdb->prepare("SELECT id, label, name, value FROM $COP_TABLE WHERE id = %d", $id )); @@ -145,15 +162,13 @@ function cop_get_option( $id ) { - - //Panel Admin function custom_options_plus_adm() { global $wpdb, $my_plugin_hook; wp_enqueue_script( 'stringToSlug', COP_PLUGIN_URL . '/js/jquery.stringToSlug.min.js', array('jquery'), '2.5.9' ); wp_enqueue_script( 'copFunctions', COP_PLUGIN_URL . '/js/functions.js', array('stringToSlug') ); - + wp_enqueue_script( 'cop-import-export', COP_PLUGIN_URL . '/js/import-export.js', array('jquery', ), null, true ); $id = ''; $label = ''; @@ -171,11 +186,11 @@ function custom_options_plus_adm() { elseif ( isset($_POST['id']) ) : if ($_POST['id'] == '') : - cop_insert(); + cop_insert( $_POST ); $message = '

' . __('Settings saved.') . '

'; elseif ($_POST['id'] > 0) : - cop_update(); + cop_update( $_POST ); $message = '

' . __('Settings saved.') . '

'; endif; @@ -243,6 +258,7 @@ function custom_options_plus_adm() {
+

Add new Custom Option

@@ -277,13 +293,28 @@ function custom_options_plus_adm() {

+ +
+

Import

+
+ + + + +
+ +
+

Export

+ + query("TRUNCATE TABLE $COP_TABLE"); + foreach($file_data as $row){ + cop_insert($row); + } + + wp_send_json_error(); +} +add_action( 'wp_ajax_cop/import', 'cop_import_data' ); diff --git a/js/import-export.js b/js/import-export.js new file mode 100644 index 0000000..e030e40 --- /dev/null +++ b/js/import-export.js @@ -0,0 +1,87 @@ +jQuery(document).ready(function ($) { + console.log('oooo'); + var importExport = { + + importSubmit: function () { + $('#cop-import-form').submit(function (e) { + var formData = new FormData(this); + formData.append('action', 'cop/import'); + console.log('formData', formData); + + $.ajax({ + url: ajaxurl, + type: 'POST', + data: formData, + processData: false, + contentType: false, + success: function (data) { + console.log('import', data); + + if ( ! data.success ) { + // location.reload(); + } else { + console.error('Error', data); + } + } + }); + + return false; + }); + }, + + fileImport: function () { + $('#cop-import').change(function (e) { + + var files = e.currentTarget.files; + + if (files.length == 1 && files[ 0 ].type == 'application/json') { + + var confirmImport = confirm('Are you sure do you want import this file? Current data will be overwriten!'); + + if (confirmImport) { + $('#cop-import-form').submit(); + } + + } else { + alert('Error on import file: not a json or more than a file uploaded!'); + } + + }); + }, + + fakeButton: function () { + $('.fake-button').click(function () { + $(this).parent().trigger('click'); + return false; + }); + + }, + ajaxExport: function () { + + $.post(ajaxurl, {action: 'export'}, function (data) { + var $link = $('download'); + $link.attr('download', 'cop.json'); + $link.attr('href', ajaxurl + '?action=cop/export'); + $('body').append($link); + $link.get(0).click(); + $link.remove(); + }); + }, + + clickExport: function () { + var that = this; + $('#cop-export').click(function () { + that.ajaxExport(); + }); + }, + + init: function () { + this.clickExport(); + this.fakeButton(); + this.fileImport(); + this.importSubmit(); + } + }; + + importExport.init(); +}); diff --git a/readme.txt b/readme.txt index 126d410..aed6db2 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Donate link: http://leocaseiro.com.br/contato/ Tags: configs, custom, custom configs, custom options, custom options plus, custom settings, leocaseiro, options, settings, wp_options Requires at least: 2.7 Tested up to: 4.6 -Stable tag: 1.6 +Stable tag: 1.7.0 License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html @@ -47,6 +47,12 @@ This Plugin was Based on Custom Settings (Custom Configs) which has been removal == Changelog == += 1.7.0 = + +* Add Settings link on Plugins Page +* Add Import and Export (Thanks @lucasbhjf for his contribution) + + = 1.6 = * Set all fields as required [Fix Issue #6](https://github.com/leocaseiro/Wordpress-Plugin-Custom-Options-Plus/issues/6) From 0c7d33618bf4e0c48de702faf5cf4f437fc21a43 Mon Sep 17 00:00:00 2001 From: leocaseiro Date: Sat, 10 Sep 2016 09:23:30 +1000 Subject: [PATCH 2/5] feature(Import): Truncate optional on import via checkbox --- custom-options-plus.php | 41 ++++++++++++++++++++++------------------- js/import-export.js | 40 +++++++++++++++++++++++----------------- 2 files changed, 45 insertions(+), 36 deletions(-) diff --git a/custom-options-plus.php b/custom-options-plus.php index e8d2f92..0b71264 100644 --- a/custom-options-plus.php +++ b/custom-options-plus.php @@ -91,14 +91,6 @@ function cop_add_menu() { } -// Insert JS and CSS -function cop_load_js_and_css() { -// wp_register_script( 'jquery.stringToSlug.min.js', COP_PLUGIN_URL . '/js/jquery.stringToSlug.min.js', array('jquery'), COP_PLUGIN_VERSION, true ); -// wp_register_script( 'cop-functions', COP_PLUGIN_URL . '/js/functions.js', array('jquery', 'jquery.stringToSlug.min.js'), COP_PLUGIN_VERSION, true ); -// wp_register_script( 'cop-import-export', COP_PLUGIN_URL . '/js/import-export.js', array('jquery', ), null, true ); -} - - // Insert on Database function cop_insert( $row ) { global $wpdb; @@ -162,7 +154,7 @@ function cop_get_option( $id ) { -//Panel Admin +// Panel Admin function custom_options_plus_adm() { global $wpdb, $my_plugin_hook; @@ -266,7 +258,7 @@ function custom_options_plus_adm() { - + @@ -282,7 +274,7 @@ function custom_options_plus_adm() { - + @@ -291,16 +283,18 @@ function custom_options_plus_adm() {

+

* required fields


Import

- +
+
@@ -347,7 +341,7 @@ function cop_plugin_help($contextual_help, $screen_id, $screen) { global $my_plugin_hook; if ($screen_id == $my_plugin_hook) { - $contextual_help = '
Use
' . htmlentities('') . '

or
' . htmlentities(' echo $name;
' . htmlentities('endforeach; ?>') . '

in your theme.'; + $contextual_help = '
Use
' . htmlentities('') . '

or
' . htmlentities(' echo $name;
' . htmlentities('endforeach; ?>') . '

in your theme.'; } return $contextual_help; } @@ -366,19 +360,28 @@ function cop_export_data() { function cop_import_data() { global $wpdb, $COP_TABLE; - if (! isset($_FILES['cop_file_import']) ) { + $truncate_table = filter_var($_POST['clear-table'], FILTER_VALIDATE_BOOLEAN); + + if (! isset( $_FILES['cop_file_import'] ) ) { wp_send_json_error(); } + if ($truncate_table) { + $wpdb->query( "TRUNCATE TABLE $COP_TABLE" ); + } + $file_obj = $_FILES['cop_file_import']; $file_content = file_get_contents($file_obj['tmp_name']); $file_data = json_decode($file_content, true); - $wpdb->query("TRUNCATE TABLE $COP_TABLE"); - foreach($file_data as $row){ - cop_insert($row); + + foreach( $file_data as $row ) { + if (! isset( $row['label'] ) || ! isset( $row['name'] ) || ! isset( $row['value'] ) ) { + wp_send_json_error(['message' => 'The JSON file is invalid']); + } + cop_insert( $row ); } - wp_send_json_error(); + wp_send_json_success(); } add_action( 'wp_ajax_cop/import', 'cop_import_data' ); diff --git a/js/import-export.js b/js/import-export.js index e030e40..6191524 100644 --- a/js/import-export.js +++ b/js/import-export.js @@ -1,12 +1,12 @@ jQuery(document).ready(function ($) { - console.log('oooo'); var importExport = { importSubmit: function () { $('#cop-import-form').submit(function (e) { + e.preventDefault(); + var formData = new FormData(this); formData.append('action', 'cop/import'); - console.log('formData', formData); $.ajax({ url: ajaxurl, @@ -14,36 +14,42 @@ jQuery(document).ready(function ($) { data: formData, processData: false, contentType: false, - success: function (data) { - console.log('import', data); - - if ( ! data.success ) { - // location.reload(); + success: function (response) { + console.log('import data', response); + if ( response.success ) { + window.location.reload(); + return true; + } else if ( response.data.message ) { + alert('Error: ' + response.data.message); + return false; } else { console.error('Error', data); + return false; } } }); - - return false; }); }, fileImport: function () { $('#cop-import').change(function (e) { + var shouldImport = false; var files = e.currentTarget.files; - if (files.length == 1 && files[ 0 ].type == 'application/json') { - - var confirmImport = confirm('Are you sure do you want import this file? Current data will be overwriten!'); + if ( files.length !== 1 || files[ 0 ].type !== 'application/json' ) { + alert('Error: invalid JSON format'); + return; + } - if (confirmImport) { - $('#cop-import-form').submit(); - } + if (! $('#should-clear-table').is(':checked') ) { + shouldImport = true; + } else if ( confirm( 'Are you sure you want to erase all data before import?\nThis action is irreversible.' ) ) { + shouldImport = true; + } - } else { - alert('Error on import file: not a json or more than a file uploaded!'); + if (shouldImport) { + $('#cop-import-form').submit(); } }); From 1f1c6454bc1fcdaf810799fc2775a0c7cabbb5a6 Mon Sep 17 00:00:00 2001 From: leocaseiro Date: Sat, 10 Sep 2016 09:28:27 +1000 Subject: [PATCH 3/5] chore(editorconfig): add .editorconfig with WordPress standards --- .editorconfig | 21 ++ custom-options-plus.php | 813 +++++++++++++++++++++------------------- js/functions.js | 7 +- js/import-export.js | 152 ++++---- 4 files changed, 526 insertions(+), 467 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..4596314 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,21 @@ +# This file is for unifying the coding style for different editors and IDEs +# editorconfig.org + +# WordPress Coding Standards +# http://make.wordpress.org/core/handbook/coding-standards/ + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = tab + +[*.json] +indent_style = space +indent_size = 2 + +[*.txt,wp-config-sample.php] +end_of_line = crlf diff --git a/custom-options-plus.php b/custom-options-plus.php index 0b71264..4f5b861 100644 --- a/custom-options-plus.php +++ b/custom-options-plus.php @@ -1,387 +1,426 @@ -prefix . 'custom_options_plus' ); - -//Added on 1.5 as GLOBAL -$COP_TABLE = COP_TABLE; - -//Create a table in MySQL database when activate plugin -function cop_setup() { - global $wpdb, $COP_TABLE; - - $sql = "CREATE TABLE IF NOT EXISTS $COP_TABLE ( - `id` int(5) NOT NULL AUTO_INCREMENT, - `label` varchar(100) NOT NULL, - `name` varchar(80) NOT NULL, - `value` text NOT NULL, - PRIMARY KEY (`id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; - "; - - require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); - - dbDelta($sql); - - - update_option(COP_OPTIONS_PREFIX . 'version', COP_PLUGIN_VERSION); -} - -register_activation_hook( __FILE__, 'cop_setup' ); - - -// Add settings link to Plugins Page -function cop_plugin_add_settings_link( $links ) { - $settings_link = '' . __( 'Settings' ) . ''; - array_push( $links, $settings_link ); - return $links; -} -$plugin = plugin_basename( __FILE__ ); -add_filter( "plugin_action_links_$plugin", 'cop_plugin_add_settings_link' ); - - -// Create a Menu Custom Options Plus in Settings -add_action('admin_menu', 'cop_add_menu'); -function cop_add_menu() { - - global $my_plugin_hook; - $my_plugin_hook = add_options_page('Custom Options Plus', 'Custom Options Plus', 'manage_options', 'custom_options_plus', 'custom_options_plus_adm'); - -} - -// Insert on Database -function cop_insert( $row ) { - global $wpdb; - - $row['label'] = stripslashes_deep(filter_var($row['label'], FILTER_SANITIZE_SPECIAL_CHARS)); - $row['name'] = stripslashes_deep(filter_var($row['name'], FILTER_SANITIZE_SPECIAL_CHARS)); - $row['value'] = stripslashes_deep(filter_var($row['value'], FILTER_UNSAFE_RAW)); - - return $wpdb->insert( - COP_TABLE, - array( - 'label' => $row['label'], - 'name' => $row['name'], - 'value' => stripslashes($row['value']) - ), - array('%s','%s','%s') - ); -} - -// Update on Database -function cop_update( $row ) { - global $wpdb; - - $row['id'] = filter_var($row['id'], FILTER_VALIDATE_INT); - $row['label'] = stripslashes_deep(filter_var($row['label'], FILTER_SANITIZE_SPECIAL_CHARS)); - $row['name'] = stripslashes_deep(filter_var($row['name'], FILTER_SANITIZE_SPECIAL_CHARS)); - $row['value'] = stripslashes_deep(filter_var($row['value'], FILTER_UNSAFE_RAW)); - - - return $wpdb->update( - COP_TABLE, - array( - 'label' => $row['label'], - 'name' => $row['name'], - 'value' => stripslashes($row['value']) - ), - array ('id' => $row['id']), - array('%s','%s','%s'), - array('%d') - ); - -} - -// Delete on Database -function cop_delete( $id ) { - global $wpdb, $COP_TABLE; - return $wpdb->query($wpdb->prepare("DELETE FROM $COP_TABLE WHERE id = %d ", $id) ); -} - -// Get all options from Database -function cop_get_options() { - global $wpdb, $COP_TABLE; - return $wpdb->get_results("SELECT id, label, name, value FROM $COP_TABLE ORDER BY label ASC"); -} - -// Get single option from Database -function cop_get_option( $id ) { - global $wpdb, $COP_TABLE; - return $wpdb->get_row($wpdb->prepare("SELECT id, label, name, value FROM $COP_TABLE WHERE id = %d", $id )); -} - - - -// Panel Admin -function custom_options_plus_adm() { - global $wpdb, $my_plugin_hook; - - wp_enqueue_script( 'stringToSlug', COP_PLUGIN_URL . '/js/jquery.stringToSlug.min.js', array('jquery'), '2.5.9' ); - wp_enqueue_script( 'copFunctions', COP_PLUGIN_URL . '/js/functions.js', array('stringToSlug') ); - wp_enqueue_script( 'cop-import-export', COP_PLUGIN_URL . '/js/import-export.js', array('jquery', ), null, true ); - - $id = ''; - $label = ''; - $name = ''; - $value = ''; - - $message = ''; - - if ( isset($_GET['del']) && $_GET['del'] > 0 ) : - if ( cop_delete( $_GET['del'] ) ) : - $message = '

' . __('Settings saved.') . '

'; - endif; - - - elseif ( isset($_POST['id']) ) : - - if ($_POST['id'] == '') : - cop_insert( $_POST ); - $message = '

' . __('Settings saved.') . '

'; - - elseif ($_POST['id'] > 0) : - cop_update( $_POST ); - $message = '

' . __('Settings saved.') . '

'; - - endif; - - - elseif ( isset($_GET['id']) && $_GET['id'] > 0 ) : - - $option = cop_get_option( $_GET['id'] ); - - $id = $option->id; - $label = $option->label; - $name = $option->name; - $value = $option->value; - - endif; - - $options = cop_get_options(); -?> - -
-

Custom Options Plus Add New

- - -
- 0 ) : ?> -
- - - - - - - - - - - - - - - - - - rowspan="2"> - - - - - - -
LabelNameValue
LabelNameValue
- label; ?> -
- Edit | - Delete -
-
- -
value; ?>
-
-
- - -
-
- -

Add new Custom Option

- - - - - - - - - - - - -
- - - - -
- - - - -
- - - - -
-

-

* required fields

-
- - -
-

Import

-
-
- - - - -
- -
-

Export

- - -
-get_var( $wpdb->prepare( "SELECT value FROM $COP_TABLE WHERE name = %s LIMIT 1", $name ) ); - else : - return false; - endif; -} - -// Get your array options -function get_customs( $name ) { - global $wpdb, $COP_TABLE; - if ( '' != $name ) : - $list = $wpdb->get_results( $wpdb->prepare( "SELECT value FROM $COP_TABLE WHERE name = %s ", $name ) , ARRAY_A); - $array = array(); - foreach ( $list as $key => $name ) : - $array[] = $name['value']; - endforeach; - return $array; - else : - return false; - endif; -} - - -//Tutorial on Help Button -function cop_plugin_help($contextual_help, $screen_id, $screen) { - - global $my_plugin_hook; - if ($screen_id == $my_plugin_hook) { - - $contextual_help = '
Use
' . htmlentities('') . '

or
' . htmlentities(' echo $name;
' . htmlentities('endforeach; ?>') . '

in your theme.'; - } - return $contextual_help; -} -add_filter('contextual_help', 'cop_plugin_help', 10, 3); - - -// Ajax Export Data -function cop_export_data() { - header('Content-type: application/json'); - echo json_encode( cop_get_options() ); exit; -// echo json_encode( cop_get_options() , JSON_PRETTY_PRINT ); exit; -} -add_action( 'wp_ajax_cop/export', 'cop_export_data' ); - -// Ajax Import Data -function cop_import_data() { - global $wpdb, $COP_TABLE; - - $truncate_table = filter_var($_POST['clear-table'], FILTER_VALIDATE_BOOLEAN); - - if (! isset( $_FILES['cop_file_import'] ) ) { - wp_send_json_error(); - } - - if ($truncate_table) { - $wpdb->query( "TRUNCATE TABLE $COP_TABLE" ); - } - - $file_obj = $_FILES['cop_file_import']; - $file_content = file_get_contents($file_obj['tmp_name']); - - $file_data = json_decode($file_content, true); - - foreach( $file_data as $row ) { - if (! isset( $row['label'] ) || ! isset( $row['name'] ) || ! isset( $row['value'] ) ) { - wp_send_json_error(['message' => 'The JSON file is invalid']); - } - cop_insert( $row ); - } - - wp_send_json_success(); -} -add_action( 'wp_ajax_cop/import', 'cop_import_data' ); +prefix . 'custom_options_plus'); + +//Added on 1.5 as GLOBAL +$COP_TABLE = COP_TABLE; + +//Create a table in MySQL database when activate plugin +function cop_setup() +{ + global $wpdb, $COP_TABLE; + + $sql = "CREATE TABLE IF NOT EXISTS $COP_TABLE ( + `id` int(5) NOT NULL AUTO_INCREMENT, + `label` varchar(100) NOT NULL, + `name` varchar(80) NOT NULL, + `value` text NOT NULL, + PRIMARY KEY (`id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; + "; + + require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); + + dbDelta($sql); + + + update_option(COP_OPTIONS_PREFIX . 'version', COP_PLUGIN_VERSION); +} + +register_activation_hook(__FILE__, 'cop_setup'); + + +// Add settings link to Plugins Page +function cop_plugin_add_settings_link($links) +{ + $settings_link = '' . __('Settings') . ''; + array_push($links, $settings_link); + return $links; +} + +$plugin = plugin_basename(__FILE__); +add_filter("plugin_action_links_$plugin", 'cop_plugin_add_settings_link'); + + +// Create a Menu Custom Options Plus in Settings +add_action('admin_menu', 'cop_add_menu'); +function cop_add_menu() +{ + + global $my_plugin_hook; + $my_plugin_hook = add_options_page('Custom Options Plus', 'Custom Options Plus', 'manage_options', 'custom_options_plus', 'custom_options_plus_adm'); + +} + +// Insert on Database +function cop_insert($row) +{ + global $wpdb; + + $row['label'] = stripslashes_deep(filter_var($row['label'], FILTER_SANITIZE_SPECIAL_CHARS)); + $row['name'] = stripslashes_deep(filter_var($row['name'], FILTER_SANITIZE_SPECIAL_CHARS)); + $row['value'] = stripslashes_deep(filter_var($row['value'], FILTER_UNSAFE_RAW)); + + return $wpdb->insert( + COP_TABLE, + array( + 'label' => $row['label'], + 'name' => $row['name'], + 'value' => stripslashes($row['value']) + ), + array('%s', '%s', '%s') + ); +} + +// Update on Database +function cop_update($row) +{ + global $wpdb; + + $row['id'] = filter_var($row['id'], FILTER_VALIDATE_INT); + $row['label'] = stripslashes_deep(filter_var($row['label'], FILTER_SANITIZE_SPECIAL_CHARS)); + $row['name'] = stripslashes_deep(filter_var($row['name'], FILTER_SANITIZE_SPECIAL_CHARS)); + $row['value'] = stripslashes_deep(filter_var($row['value'], FILTER_UNSAFE_RAW)); + + + return $wpdb->update( + COP_TABLE, + array( + 'label' => $row['label'], + 'name' => $row['name'], + 'value' => stripslashes($row['value']) + ), + array('id' => $row['id']), + array('%s', '%s', '%s'), + array('%d') + ); + +} + +// Delete on Database +function cop_delete($id) +{ + global $wpdb, $COP_TABLE; + return $wpdb->query($wpdb->prepare("DELETE FROM $COP_TABLE WHERE id = %d ", $id)); +} + +// Get all options from Database +function cop_get_options() +{ + global $wpdb, $COP_TABLE; + return $wpdb->get_results("SELECT id, label, name, value FROM $COP_TABLE ORDER BY label ASC"); +} + +// Get single option from Database +function cop_get_option($id) +{ + global $wpdb, $COP_TABLE; + return $wpdb->get_row($wpdb->prepare("SELECT id, label, name, value FROM $COP_TABLE WHERE id = %d", $id)); +} + + +// Panel Admin +function custom_options_plus_adm() +{ + global $wpdb, $my_plugin_hook; + + wp_enqueue_script('stringToSlug', COP_PLUGIN_URL . '/js/jquery.stringToSlug.min.js', array('jquery'), '2.5.9'); + wp_enqueue_script('copFunctions', COP_PLUGIN_URL . '/js/functions.js', array('stringToSlug')); + wp_enqueue_script('cop-import-export', COP_PLUGIN_URL . '/js/import-export.js', array('jquery',), null, true); + + $id = ''; + $label = ''; + $name = ''; + $value = ''; + + $message = ''; + + if (isset($_GET['del']) && $_GET['del'] > 0) : + if (cop_delete($_GET['del'])) : + $message = '

' . __('Settings saved.') . '

'; + endif; + + + elseif (isset($_POST['id'])) : + + if ($_POST['id'] == '') : + cop_insert($_POST); + $message = '

' . __('Settings saved.') . '

'; + + elseif ($_POST['id'] > 0) : + cop_update($_POST); + $message = '

' . __('Settings saved.') . '

'; + + endif; + + + elseif (isset($_GET['id']) && $_GET['id'] > 0) : + + $option = cop_get_option($_GET['id']); + + $id = $option->id; + $label = $option->label; + $name = $option->name; + $value = $option->value; + + endif; + + $options = cop_get_options(); + ?> + +
+
+

Custom Options Plus Add New

+ + +
+ 0) : ?> +
+ + + + + + + + + + + + + + + + + + rowspan="2"> + + + + + + +
LabelNameValue
LabelNameValue
+ label; ?> +
+ Edit | + Delete +
+
+ + +
value; ?>
+
+
+
+ + +
+
+ +

Add new Custom Option

+ + + + + + + + + + + + +
+ + + + +
+ + + + +
+ + + + +
+

+

+ * required fields +

+
+ + +
+

Import

+
+
+ + + + +
+ +
+

Export

+ + +
+ get_var($wpdb->prepare("SELECT value FROM $COP_TABLE WHERE name = %s LIMIT 1", $name)); + else : + return false; + endif; +} + +// Get your array options +function get_customs($name) +{ + global $wpdb, $COP_TABLE; + if ('' != $name) : + $list = $wpdb->get_results($wpdb->prepare("SELECT value FROM $COP_TABLE WHERE name = %s ", $name), ARRAY_A); + $array = array(); + foreach ($list as $key => $name) : + $array[] = $name['value']; + endforeach; + return $array; + else : + return false; + endif; +} + + +//Tutorial on Help Button +function cop_plugin_help($contextual_help, $screen_id, $screen) +{ + + global $my_plugin_hook; + if ($screen_id == $my_plugin_hook) { + + $contextual_help = '
Use
' . htmlentities('') . '

or
' . htmlentities(' echo $name;
' . htmlentities('endforeach; ?>') . '

in your theme.'; + } + return $contextual_help; +} + +add_filter('contextual_help', 'cop_plugin_help', 10, 3); + + +// Ajax Export Data +function cop_export_data() +{ + header('Content-type: application/json'); + echo json_encode(cop_get_options()); + exit; +// echo json_encode( cop_get_options() , JSON_PRETTY_PRINT ); exit; +} + +add_action('wp_ajax_cop/export', 'cop_export_data'); + +// Ajax Import Data +function cop_import_data() +{ + global $wpdb, $COP_TABLE; + + $truncate_table = filter_var($_POST['clear-table'], FILTER_VALIDATE_BOOLEAN); + + if (!isset($_FILES['cop_file_import'])) { + wp_send_json_error(); + } + + if ($truncate_table) { + $wpdb->query("TRUNCATE TABLE $COP_TABLE"); + } + + $file_obj = $_FILES['cop_file_import']; + $file_content = file_get_contents($file_obj['tmp_name']); + + $file_data = json_decode($file_content, true); + + foreach ($file_data as $row) { + if (!isset($row['label']) || !isset($row['name']) || !isset($row['value'])) { + wp_send_json_error(['message' => 'The JSON file is invalid']); + } + cop_insert($row); + } + + wp_send_json_success(); +} + +add_action('wp_ajax_cop/import', 'cop_import_data'); diff --git a/js/functions.js b/js/functions.js index 1849dcb..9ab9ddf 100644 --- a/js/functions.js +++ b/js/functions.js @@ -1,10 +1,9 @@ - -jQuery(document).ready( function($) { +jQuery(document).ready(function ($) { if ($("#name").val() === '') { - $("#label").stringToSlug({ + $("#label").stringToSlug({ setEvents: 'keyup keydown blur', getPut: '#name', space: '_' }); } -}); \ No newline at end of file +}); diff --git a/js/import-export.js b/js/import-export.js index 6191524..855759c 100644 --- a/js/import-export.js +++ b/js/import-export.js @@ -1,93 +1,93 @@ jQuery(document).ready(function ($) { - var importExport = { + var importExport = { - importSubmit: function () { - $('#cop-import-form').submit(function (e) { - e.preventDefault(); + importSubmit: function () { + $('#cop-import-form').submit(function (e) { + e.preventDefault(); - var formData = new FormData(this); - formData.append('action', 'cop/import'); + var formData = new FormData(this); + formData.append('action', 'cop/import'); - $.ajax({ - url: ajaxurl, - type: 'POST', - data: formData, - processData: false, - contentType: false, - success: function (response) { - console.log('import data', response); - if ( response.success ) { - window.location.reload(); - return true; - } else if ( response.data.message ) { - alert('Error: ' + response.data.message); - return false; - } else { - console.error('Error', data); - return false; - } - } - }); - }); - }, + $.ajax({ + url: ajaxurl, + type: 'POST', + data: formData, + processData: false, + contentType: false, + success: function (response) { + console.log('import data', response); + if (response.success) { + window.location.reload(); + return true; + } else if (response.data.message) { + alert('Error: ' + response.data.message); + return false; + } else { + console.error('Error', data); + return false; + } + } + }); + }); + }, - fileImport: function () { - $('#cop-import').change(function (e) { + fileImport: function () { + $('#cop-import').change(function (e) { - var shouldImport = false; - var files = e.currentTarget.files; + var shouldImport = false; + var files = e.currentTarget.files; - if ( files.length !== 1 || files[ 0 ].type !== 'application/json' ) { - alert('Error: invalid JSON format'); - return; - } + if (files.length !== 1 || files[ 0 ].type !== 'application/json') { + alert('Error: invalid JSON format'); + return; + } - if (! $('#should-clear-table').is(':checked') ) { - shouldImport = true; - } else if ( confirm( 'Are you sure you want to erase all data before import?\nThis action is irreversible.' ) ) { - shouldImport = true; - } + if (!$('#should-clear-table').is(':checked')) { + shouldImport = true; + } else if (confirm('Are you sure you want to erase all data before import?\nThis action is irreversible.')) { + shouldImport = true; + } - if (shouldImport) { - $('#cop-import-form').submit(); - } + if (shouldImport) { + $('#cop-import-form').submit(); + } - }); - }, + }); + }, - fakeButton: function () { - $('.fake-button').click(function () { - $(this).parent().trigger('click'); - return false; - }); + fakeButton: function () { + $('.fake-button').click(function () { + $(this).parent().trigger('click'); + return false; + }); - }, - ajaxExport: function () { + }, + ajaxExport: function () { - $.post(ajaxurl, {action: 'export'}, function (data) { - var $link = $('download'); - $link.attr('download', 'cop.json'); - $link.attr('href', ajaxurl + '?action=cop/export'); - $('body').append($link); - $link.get(0).click(); - $link.remove(); - }); - }, + $.post(ajaxurl, {action: 'export'}, function (data) { + var $link = $('download'); + $link.attr('download', 'cop.json'); + $link.attr('href', ajaxurl + '?action=cop/export'); + $('body').append($link); + $link.get(0).click(); + $link.remove(); + }); + }, - clickExport: function () { - var that = this; - $('#cop-export').click(function () { - that.ajaxExport(); - }); - }, + clickExport: function () { + var that = this; + $('#cop-export').click(function () { + that.ajaxExport(); + }); + }, - init: function () { - this.clickExport(); - this.fakeButton(); - this.fileImport(); - this.importSubmit(); - } - }; + init: function () { + this.clickExport(); + this.fakeButton(); + this.fileImport(); + this.importSubmit(); + } + }; - importExport.init(); + importExport.init(); }); From ff146f1ec2e9c88200ab12fccf4b7d0c80236730 Mon Sep 17 00:00:00 2001 From: leocaseiro Date: Sat, 10 Sep 2016 10:13:43 +1000 Subject: [PATCH 4/5] chore(jscs): format javascript following WP Standards --- .jscsrc | 51 +++++++++ custom-options-plus.php | 236 +++++++++++++++++++--------------------- js/functions.js | 6 +- js/import-export.js | 64 +++++------ 4 files changed, 200 insertions(+), 157 deletions(-) create mode 100644 .jscsrc diff --git a/.jscsrc b/.jscsrc new file mode 100644 index 0000000..641c40f --- /dev/null +++ b/.jscsrc @@ -0,0 +1,51 @@ +{ + "preset": "jquery", + "requireDotNotation": { + "allExcept": [ + "snake_case", + "keywords" + ] + }, + "disallowSpaceAfterPrefixUnaryOperators": [ + "++", + "--", + "+", + "-", + "~" + ], + "disallowSpaceBeforePostfixUnaryOperators": true, + "maximumLineLength": null, + "requireVarDeclFirst": true, + "requireSpaceAfterPrefixUnaryOperators": [ + "!" + ], + "requireSpacesInsideBrackets": null, + "requireSpacesInsideParentheses": { + "all": true, + "except": [ + "{", + "}", + "[", + "]", + "function" + ] + }, + "requireYodaConditions": [ + "==", + "!=", + "===", + "!==" + ], + "validateQuoteMarks": "'", + "requireCapitalizedComments": { + "allExcept": [ + "global", + "exported", + "jshint", + "eslint", + "jslint" + ] + }, + "requireCamelCaseOrUpperCaseIdentifiers": "ignoreProperties", + "requireBlocksOnNewline": true +} diff --git a/custom-options-plus.php b/custom-options-plus.php index 4f5b861..9f41a25 100644 --- a/custom-options-plus.php +++ b/custom-options-plus.php @@ -27,30 +27,29 @@ */ // Make sure we don't expose any info if called directly -if (!function_exists('add_action')) { +if ( ! function_exists( 'add_action' ) ) { echo 'Hi there! I\'m just a plugin, not much I can do when called directly.'; exit; } -define('COP_PLUGIN_BASENAME', plugin_basename(__FILE__)); -define('COP_PLUGIN_NAME', trim(dirname(COP_PLUGIN_BASENAME), '/')); -define('COP_PLUGIN_DIR', WP_PLUGIN_DIR . '/' . COP_PLUGIN_NAME); -define('COP_PLUGIN_URL', WP_PLUGIN_URL . '/' . COP_PLUGIN_NAME); +define( 'COP_PLUGIN_BASENAME', plugin_basename( __FILE__ ) ); +define( 'COP_PLUGIN_NAME', trim( dirname( COP_PLUGIN_BASENAME ), '/' ) ); +define( 'COP_PLUGIN_DIR', WP_PLUGIN_DIR . '/' . COP_PLUGIN_NAME ); +define( 'COP_PLUGIN_URL', WP_PLUGIN_URL . '/' . COP_PLUGIN_NAME ); //Added on 1.5 -define('COP_OPTIONS_PREFIX', 'cop_'); -define('COP_PLUGIN_VERSION', '1.7.0'); +define( 'COP_OPTIONS_PREFIX', 'cop_' ); +define( 'COP_PLUGIN_VERSION', '1.7.0' ); global $wpdb, $COP_TABLE; -define('COP_TABLE', $wpdb->prefix . 'custom_options_plus'); +define( 'COP_TABLE', $wpdb->prefix . 'custom_options_plus' ); //Added on 1.5 as GLOBAL $COP_TABLE = COP_TABLE; //Create a table in MySQL database when activate plugin -function cop_setup() -{ +function cop_setup() { global $wpdb, $COP_TABLE; $sql = "CREATE TABLE IF NOT EXISTS $COP_TABLE ( @@ -62,148 +61,144 @@ function cop_setup() ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; "; - require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); + require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); - dbDelta($sql); + dbDelta( $sql ); - update_option(COP_OPTIONS_PREFIX . 'version', COP_PLUGIN_VERSION); + update_option( COP_OPTIONS_PREFIX . 'version', COP_PLUGIN_VERSION ); } -register_activation_hook(__FILE__, 'cop_setup'); +register_activation_hook( __FILE__, 'cop_setup' ); // Add settings link to Plugins Page -function cop_plugin_add_settings_link($links) -{ - $settings_link = '' . __('Settings') . ''; - array_push($links, $settings_link); +function cop_plugin_add_settings_link( $links ) { + $settings_link = '' . __( 'Settings' ) . ''; + array_push( $links, $settings_link ); + return $links; } -$plugin = plugin_basename(__FILE__); -add_filter("plugin_action_links_$plugin", 'cop_plugin_add_settings_link'); +$plugin = plugin_basename( __FILE__ ); +add_filter( "plugin_action_links_$plugin", 'cop_plugin_add_settings_link' ); // Create a Menu Custom Options Plus in Settings -add_action('admin_menu', 'cop_add_menu'); -function cop_add_menu() -{ +add_action( 'admin_menu', 'cop_add_menu' ); +function cop_add_menu() { global $my_plugin_hook; - $my_plugin_hook = add_options_page('Custom Options Plus', 'Custom Options Plus', 'manage_options', 'custom_options_plus', 'custom_options_plus_adm'); + $my_plugin_hook = add_options_page( 'Custom Options Plus', 'Custom Options Plus', 'manage_options', 'custom_options_plus', 'custom_options_plus_adm' ); } // Insert on Database -function cop_insert($row) -{ +function cop_insert( $row ) { global $wpdb; - $row['label'] = stripslashes_deep(filter_var($row['label'], FILTER_SANITIZE_SPECIAL_CHARS)); - $row['name'] = stripslashes_deep(filter_var($row['name'], FILTER_SANITIZE_SPECIAL_CHARS)); - $row['value'] = stripslashes_deep(filter_var($row['value'], FILTER_UNSAFE_RAW)); + $row['label'] = stripslashes_deep( filter_var( $row['label'], FILTER_SANITIZE_SPECIAL_CHARS ) ); + $row['name'] = stripslashes_deep( filter_var( $row['name'], FILTER_SANITIZE_SPECIAL_CHARS ) ); + $row['value'] = stripslashes_deep( filter_var( $row['value'], FILTER_UNSAFE_RAW ) ); return $wpdb->insert( COP_TABLE, array( 'label' => $row['label'], - 'name' => $row['name'], - 'value' => stripslashes($row['value']) + 'name' => $row['name'], + 'value' => stripslashes( $row['value'] ) ), - array('%s', '%s', '%s') + array( '%s', '%s', '%s' ) ); } // Update on Database -function cop_update($row) -{ +function cop_update( $row ) { global $wpdb; - $row['id'] = filter_var($row['id'], FILTER_VALIDATE_INT); - $row['label'] = stripslashes_deep(filter_var($row['label'], FILTER_SANITIZE_SPECIAL_CHARS)); - $row['name'] = stripslashes_deep(filter_var($row['name'], FILTER_SANITIZE_SPECIAL_CHARS)); - $row['value'] = stripslashes_deep(filter_var($row['value'], FILTER_UNSAFE_RAW)); + $row['id'] = filter_var( $row['id'], FILTER_VALIDATE_INT ); + $row['label'] = stripslashes_deep( filter_var( $row['label'], FILTER_SANITIZE_SPECIAL_CHARS ) ); + $row['name'] = stripslashes_deep( filter_var( $row['name'], FILTER_SANITIZE_SPECIAL_CHARS ) ); + $row['value'] = stripslashes_deep( filter_var( $row['value'], FILTER_UNSAFE_RAW ) ); return $wpdb->update( COP_TABLE, array( 'label' => $row['label'], - 'name' => $row['name'], - 'value' => stripslashes($row['value']) + 'name' => $row['name'], + 'value' => stripslashes( $row['value'] ) ), - array('id' => $row['id']), - array('%s', '%s', '%s'), - array('%d') + array( 'id' => $row['id'] ), + array( '%s', '%s', '%s' ), + array( '%d' ) ); } // Delete on Database -function cop_delete($id) -{ +function cop_delete( $id ) { global $wpdb, $COP_TABLE; - return $wpdb->query($wpdb->prepare("DELETE FROM $COP_TABLE WHERE id = %d ", $id)); + + return $wpdb->query( $wpdb->prepare( "DELETE FROM $COP_TABLE WHERE id = %d ", $id ) ); } // Get all options from Database -function cop_get_options() -{ +function cop_get_options() { global $wpdb, $COP_TABLE; - return $wpdb->get_results("SELECT id, label, name, value FROM $COP_TABLE ORDER BY label ASC"); + + return $wpdb->get_results( "SELECT id, label, name, value FROM $COP_TABLE ORDER BY label ASC" ); } // Get single option from Database -function cop_get_option($id) -{ +function cop_get_option( $id ) { global $wpdb, $COP_TABLE; - return $wpdb->get_row($wpdb->prepare("SELECT id, label, name, value FROM $COP_TABLE WHERE id = %d", $id)); + + return $wpdb->get_row( $wpdb->prepare( "SELECT id, label, name, value FROM $COP_TABLE WHERE id = %d", $id ) ); } // Panel Admin -function custom_options_plus_adm() -{ +function custom_options_plus_adm() { global $wpdb, $my_plugin_hook; - wp_enqueue_script('stringToSlug', COP_PLUGIN_URL . '/js/jquery.stringToSlug.min.js', array('jquery'), '2.5.9'); - wp_enqueue_script('copFunctions', COP_PLUGIN_URL . '/js/functions.js', array('stringToSlug')); - wp_enqueue_script('cop-import-export', COP_PLUGIN_URL . '/js/import-export.js', array('jquery',), null, true); + wp_enqueue_script( 'stringToSlug', COP_PLUGIN_URL . '/js/jquery.stringToSlug.min.js', array( 'jquery' ), '2.5.9' ); + wp_enqueue_script( 'copFunctions', COP_PLUGIN_URL . '/js/functions.js', array( 'stringToSlug' ) ); + wp_enqueue_script( 'cop-import-export', COP_PLUGIN_URL . '/js/import-export.js', array( 'jquery', ), null, true ); - $id = ''; + $id = ''; $label = ''; - $name = ''; + $name = ''; $value = ''; $message = ''; - if (isset($_GET['del']) && $_GET['del'] > 0) : - if (cop_delete($_GET['del'])) : - $message = '

' . __('Settings saved.') . '

'; + if ( isset( $_GET['del'] ) && $_GET['del'] > 0 ) : + if ( cop_delete( $_GET['del'] ) ) : + $message = '

' . __( 'Settings saved.' ) . '

'; endif; - elseif (isset($_POST['id'])) : + elseif ( isset( $_POST['id'] ) ) : - if ($_POST['id'] == '') : - cop_insert($_POST); - $message = '

' . __('Settings saved.') . '

'; + if ( $_POST['id'] == '' ) : + cop_insert( $_POST ); + $message = '

' . __( 'Settings saved.' ) . '

'; - elseif ($_POST['id'] > 0) : - cop_update($_POST); - $message = '

' . __('Settings saved.') . '

'; + elseif ( $_POST['id'] > 0 ) : + cop_update( $_POST ); + $message = '

' . __( 'Settings saved.' ) . '

'; endif; - elseif (isset($_GET['id']) && $_GET['id'] > 0) : + elseif ( isset( $_GET['id'] ) && $_GET['id'] > 0 ) : - $option = cop_get_option($_GET['id']); + $option = cop_get_option( $_GET['id'] ); - $id = $option->id; + $id = $option->id; $label = $option->label; - $name = $option->name; + $name = $option->name; $value = $option->value; endif; @@ -214,12 +209,12 @@ function custom_options_plus_adm()

Custom Options Plus Add New


- 0) : ?> + 0 ) : ?>
@@ -238,24 +233,24 @@ class="add-new-h2">Add New rowspan="2"> - + - + @@ -283,7 +283,7 @@ class="regular-text">
label; ?>
Edit | + href="&id=id; ?>#new-custom-option">Edit | Delete + href="&del=id; ?>">Delete
+ onfocus="this.select();" readonly="readonly" + class="shortcode-in-list-table wp-ui-text-highlight code">name; ?>
na
-
+

Add new Custom Option

@@ -283,7 +278,7 @@ class="shortcode-in-list-table wp-ui-text-highlight code">na @@ -292,7 +287,7 @@ class="regular-text"> @@ -301,13 +296,13 @@ class="regular-text">
+ class="regular-text">
+ class="regular-text">
+ class="regular-text code">

+ value="">

* required fields

@@ -317,21 +312,21 @@ class="regular-text code">

Import

+ action="" method="post">
+ class="button-primary hidden" value=""/>

Export

- +
"/> // Get your single option -function get_custom($name) -{ +function get_custom( $name ) { global $wpdb, $COP_TABLE; - if ('' != $name) : - return $wpdb->get_var($wpdb->prepare("SELECT value FROM $COP_TABLE WHERE name = %s LIMIT 1", $name)); + if ( '' != $name ) : + return $wpdb->get_var( $wpdb->prepare( "SELECT value FROM $COP_TABLE WHERE name = %s LIMIT 1", $name ) ); else : return false; endif; } // Get your array options -function get_customs($name) -{ +function get_customs( $name ) { global $wpdb, $COP_TABLE; - if ('' != $name) : - $list = $wpdb->get_results($wpdb->prepare("SELECT value FROM $COP_TABLE WHERE name = %s ", $name), ARRAY_A); + if ( '' != $name ) : + $list = $wpdb->get_results( $wpdb->prepare( "SELECT value FROM $COP_TABLE WHERE name = %s ", $name ), ARRAY_A ); $array = array(); - foreach ($list as $key => $name) : + foreach ( $list as $key => $name ) : $array[] = $name['value']; endforeach; + return $array; else : return false; @@ -368,59 +362,57 @@ function get_customs($name) //Tutorial on Help Button -function cop_plugin_help($contextual_help, $screen_id, $screen) -{ +function cop_plugin_help( $contextual_help, $screen_id, $screen ) { global $my_plugin_hook; - if ($screen_id == $my_plugin_hook) { + if ( $screen_id == $my_plugin_hook ) { - $contextual_help = '
Use
' . htmlentities('') . '

or
' . htmlentities(' echo $name;
' . htmlentities('endforeach; ?>') . '

in your theme.'; + $contextual_help = '
Use
' . htmlentities( '' ) . '

or
' . htmlentities( ' echo $name;
' . htmlentities( 'endforeach; ?>' ) . '

in your theme.'; } + return $contextual_help; } -add_filter('contextual_help', 'cop_plugin_help', 10, 3); +add_filter( 'contextual_help', 'cop_plugin_help', 10, 3 ); // Ajax Export Data -function cop_export_data() -{ - header('Content-type: application/json'); - echo json_encode(cop_get_options()); +function cop_export_data() { + header( 'Content-type: application/json' ); + echo json_encode( cop_get_options() ); exit; // echo json_encode( cop_get_options() , JSON_PRETTY_PRINT ); exit; } -add_action('wp_ajax_cop/export', 'cop_export_data'); +add_action( 'wp_ajax_cop/export', 'cop_export_data' ); // Ajax Import Data -function cop_import_data() -{ +function cop_import_data() { global $wpdb, $COP_TABLE; - $truncate_table = filter_var($_POST['clear-table'], FILTER_VALIDATE_BOOLEAN); + $truncate_table = filter_var( $_POST['clear-table'], FILTER_VALIDATE_BOOLEAN ); - if (!isset($_FILES['cop_file_import'])) { + if ( ! isset( $_FILES['cop_file_import'] ) ) { wp_send_json_error(); } - if ($truncate_table) { - $wpdb->query("TRUNCATE TABLE $COP_TABLE"); + if ( $truncate_table ) { + $wpdb->query( "TRUNCATE TABLE $COP_TABLE" ); } - $file_obj = $_FILES['cop_file_import']; - $file_content = file_get_contents($file_obj['tmp_name']); + $file_obj = $_FILES['cop_file_import']; + $file_content = file_get_contents( $file_obj['tmp_name'] ); - $file_data = json_decode($file_content, true); + $file_data = json_decode( $file_content, true ); - foreach ($file_data as $row) { - if (!isset($row['label']) || !isset($row['name']) || !isset($row['value'])) { - wp_send_json_error(['message' => 'The JSON file is invalid']); + foreach ( $file_data as $row ) { + if ( ! isset( $row['label'] ) || ! isset( $row['name'] ) || ! isset( $row['value'] ) ) { + wp_send_json_error( [ 'message' => 'The JSON file is invalid' ] ); } - cop_insert($row); + cop_insert( $row ); } wp_send_json_success(); } -add_action('wp_ajax_cop/import', 'cop_import_data'); +add_action( 'wp_ajax_cop/import', 'cop_import_data' ); diff --git a/js/functions.js b/js/functions.js index 9ab9ddf..f3aceef 100644 --- a/js/functions.js +++ b/js/functions.js @@ -1,6 +1,6 @@ -jQuery(document).ready(function ($) { - if ($("#name").val() === '') { - $("#label").stringToSlug({ +jQuery( document ).ready(function( $ ) { + if ( '' === $( '#name' ).val() ) { + $( '#label' ).stringToSlug({ setEvents: 'keyup keydown blur', getPut: '#name', space: '_' diff --git a/js/import-export.js b/js/import-export.js index 855759c..353a2c7 100644 --- a/js/import-export.js +++ b/js/import-export.js @@ -1,12 +1,12 @@ -jQuery(document).ready(function ($) { +jQuery( document ).ready(function( $ ) { var importExport = { - importSubmit: function () { - $('#cop-import-form').submit(function (e) { + importSubmit: function() { + $( '#cop-import-form' ).submit(function( e ) { e.preventDefault(); - var formData = new FormData(this); - formData.append('action', 'cop/import'); + var formData = new FormData( this ); + formData.append( 'action', 'cop/import' ); $.ajax({ url: ajaxurl, @@ -14,16 +14,16 @@ jQuery(document).ready(function ($) { data: formData, processData: false, contentType: false, - success: function (response) { - console.log('import data', response); - if (response.success) { + success: function( response ) { + console.log( 'import data', response ); + if ( response.success ) { window.location.reload(); return true; - } else if (response.data.message) { - alert('Error: ' + response.data.message); + } else if ( response.data.message ) { + alert( 'Error: ' + response.data.message ); return false; } else { - console.error('Error', data); + console.error( 'Error', data ); return false; } } @@ -31,57 +31,57 @@ jQuery(document).ready(function ($) { }); }, - fileImport: function () { - $('#cop-import').change(function (e) { + fileImport: function() { + $( '#cop-import' ).change(function( e ) { var shouldImport = false; var files = e.currentTarget.files; - if (files.length !== 1 || files[ 0 ].type !== 'application/json') { - alert('Error: invalid JSON format'); + if ( files.length !== 1 || files[ 0 ].type !== 'application/json' ) { + alert( 'Error: invalid JSON format' ); return; } - if (!$('#should-clear-table').is(':checked')) { + if ( ! $( '#should-clear-table' ).is( ':checked' ) ) { shouldImport = true; - } else if (confirm('Are you sure you want to erase all data before import?\nThis action is irreversible.')) { + } else if ( confirm( 'Are you sure you want to erase all data before import?\nThis action is irreversible.' ) ) { shouldImport = true; } - if (shouldImport) { - $('#cop-import-form').submit(); + if ( shouldImport ) { + $( '#cop-import-form' ).submit(); } }); }, - fakeButton: function () { - $('.fake-button').click(function () { - $(this).parent().trigger('click'); + fakeButton: function() { + $( '.fake-button' ).click(function() { + $( this ).parent().trigger( 'click' ); return false; }); }, - ajaxExport: function () { + ajaxExport: function() { - $.post(ajaxurl, {action: 'export'}, function (data) { - var $link = $('download'); - $link.attr('download', 'cop.json'); - $link.attr('href', ajaxurl + '?action=cop/export'); - $('body').append($link); - $link.get(0).click(); + $.post( ajaxurl, { action: 'export' }, function( data ) { + var $link = $( 'download' ); + $link.attr( 'download', 'cop.json' ); + $link.attr( 'href', ajaxurl + '?action=cop/export' ); + $( 'body' ).append( $link ); + $link.get( 0 ).click(); $link.remove(); }); }, - clickExport: function () { + clickExport: function() { var that = this; - $('#cop-export').click(function () { + $( '#cop-export' ).click(function() { that.ajaxExport(); }); }, - init: function () { + init: function() { this.clickExport(); this.fakeButton(); this.fileImport(); From fe466a5e632b4f60d39363b012097fa94272b96f Mon Sep 17 00:00:00 2001 From: leocaseiro Date: Sat, 10 Sep 2016 11:17:51 +1000 Subject: [PATCH 5/5] feature(Import|Export): Implement Import and Export Thanks @lucasbhjf Fix #5 --- custom-options-plus.php | 30 ++++++++++++++++++++---------- js/import-export.js | 17 +++++++++++++---- 2 files changed, 33 insertions(+), 14 deletions(-) diff --git a/custom-options-plus.php b/custom-options-plus.php index 9f41a25..7e8c458 100644 --- a/custom-options-plus.php +++ b/custom-options-plus.php @@ -38,7 +38,7 @@ define( 'COP_PLUGIN_DIR', WP_PLUGIN_DIR . '/' . COP_PLUGIN_NAME ); define( 'COP_PLUGIN_URL', WP_PLUGIN_URL . '/' . COP_PLUGIN_NAME ); -//Added on 1.5 +// Added on 1.5 define( 'COP_OPTIONS_PREFIX', 'cop_' ); define( 'COP_PLUGIN_VERSION', '1.7.0' ); @@ -50,7 +50,7 @@ //Create a table in MySQL database when activate plugin function cop_setup() { - global $wpdb, $COP_TABLE; + global $COP_TABLE; $sql = "CREATE TABLE IF NOT EXISTS $COP_TABLE ( `id` int(5) NOT NULL AUTO_INCREMENT, @@ -220,14 +220,14 @@ class="add-new-h2">Add New
LabelNameKey Value
LabelNameKey Value
- + +

Export

+ Use
' . htmlentities( '' ) . '

or
' . htmlentities( ' echo $name;
' . htmlentities( 'endforeach; ?>' ) . '

in your theme.'; + $contextual_help = '
Use
' . htmlentities( '' ) . '

or
' . htmlentities( ' echo $name;
' . htmlentities( 'endforeach; ?>' ) . '

in your theme.'; } return $contextual_help; @@ -376,20 +378,28 @@ function cop_plugin_help( $contextual_help, $screen_id, $screen ) { add_filter( 'contextual_help', 'cop_plugin_help', 10, 3 ); -// Ajax Export Data +// Ajax Export Data (Added on 1.7) function cop_export_data() { + if ( ! wp_verify_nonce( $_REQUEST['security_cop_ajax_export'], 'cop_ajax_export_nonce' ) ) { + wp_send_json_error( [ 'message' => 'Access Denied!' ] ); + } + header( 'Content-type: application/json' ); + echo json_encode( cop_get_options() ); exit; -// echo json_encode( cop_get_options() , JSON_PRETTY_PRINT ); exit; } add_action( 'wp_ajax_cop/export', 'cop_export_data' ); -// Ajax Import Data +// Ajax Import Data (Added on 1.7) function cop_import_data() { global $wpdb, $COP_TABLE; + if ( ! wp_verify_nonce( $_POST['security_cop_ajax_import'], 'cop_ajax_import_nonce' ) ) { + wp_send_json_error( [ 'message' => 'Access Denied!' ] ); + } + $truncate_table = filter_var( $_POST['clear-table'], FILTER_VALIDATE_BOOLEAN ); if ( ! isset( $_FILES['cop_file_import'] ) ) { diff --git a/js/import-export.js b/js/import-export.js index 353a2c7..8eb7764 100644 --- a/js/import-export.js +++ b/js/import-export.js @@ -7,6 +7,7 @@ jQuery( document ).ready(function( $ ) { var formData = new FormData( this ); formData.append( 'action', 'cop/import' ); + formData.append( 'security_cop_ajax_import', $( '#security_cop_ajax_import' ).val() ); $.ajax({ url: ajaxurl, @@ -15,7 +16,6 @@ jQuery( document ).ready(function( $ ) { processData: false, contentType: false, success: function( response ) { - console.log( 'import data', response ); if ( response.success ) { window.location.reload(); return true; @@ -63,11 +63,20 @@ jQuery( document ).ready(function( $ ) { }, ajaxExport: function() { + var exportAction = 'cop/export'; + var exportNonce = $( '#security_cop_ajax_export' ).val(); + $.post( ajaxurl, { + action: exportAction, + 'security_cop_ajax_export': exportNonce + }, function( response ) { + if ( response.hasOwnProperty( 'success' ) && false == response.success ) { + alert( response.data.message ); + return false; + } - $.post( ajaxurl, { action: 'export' }, function( data ) { var $link = $( 'download' ); - $link.attr( 'download', 'cop.json' ); - $link.attr( 'href', ajaxurl + '?action=cop/export' ); + $link.attr( 'download', 'custom-options-plu.json' ); + $link.attr( 'href', ajaxurl + '?action=' + exportAction + '&security_cop_ajax_export=' + exportNonce ); $( 'body' ).append( $link ); $link.get( 0 ).click(); $link.remove();