PluginProbe
SQL Chart Builder / 3.0.3
SQL Chart Builder v3.0.3
3.0.5 3.0.4 3.0.3 3.0.2 3.0.1 trunk 1.0.2 1.0.3 2.2.2 2.3.0 2.3.1 2.3.2 2.3.3 2.3.4 2.3.5 2.3.6 2.3.7 2.3.7.1 2.3.7.2 2.3.8 3.0.0
← All changes | functions.php +1183 -293 1.0.33.0.3 View file →
@@ -1,21 +1,66 @@
1 1 <?php
2 -
2 +if (!defined('ABSPATH')) {
3 + die;
4 +}
3 5 //postinstall function
4 6 function guaven_sqlcharts_load_defaults()
5 7 {
6 - if (get_option("guaven_sqlcharts_already_installed") === false) {
7 - update_option("guaven_sqlcharts_already_installed", "1");
8 + if (get_option("guaven_sqlcharts_already_installed_2") === false) {
9 + update_option("guaven_sqlcharts_already_installed_2", "1");
8 10 guaven_sqlcharts_install_first_data();
11 +
9 12 }
10 13 }
11 14
15 +function guaven_sqlcharts_install_first_data()
16 +{
17 + require_once(dirname(__FILE__) . "/initial_data.php");
18 + gvn_chart_sample_nonxml_data();
19 +}
12 20
13 21
22 +function guaven_sqlcharts_recommended(){
23 + if(!class_exists('WooCommerce'))return;
24 + $uid=(int)get_current_user_id();
25 + if(isset($_GET["gvnsql_dismiss_recommendation"])){
26 + update_option('gvnsql_dismiss_recommendation_'.$uid,1);
27 + return;
28 + }
29 + if(get_option('gvnsql_dismiss_recommendation_'.$uid)!='')return;
30 + return '<table class="gf-alert gf-alert-info" style="margin-top:20px">
31 + <tbody><tr><td style="width: auto;vertical-align: top;padding: 20px;">
32 + <h2>WooCommerce Search Engine – INSTANT, RELEVANT AND SMART Search Box</h2>
33 + <h3>Turn your website search into Smart Search which find products by price, SKU, attributes, meta data, categorys, tags etc. </h3>
34 + <p>“WooCommerce Search Engine” is a very powerful and easy to use WooCommerce Search Plugin which turns a simple search box of your WooCommerce Store to the powerful multifunctional magic box which helps you to sell more products. The plugin UI is compatible with ALL THEMES.</p>
35 + <a target="_blank" style="border:0px solid #6200ee;border-radius:0px;color:white;font-weight:bold;background: #6200ee;" class="button button-secondary"
36 + href="https://codecanyon.net/item/woocommerce-search-box/15685698">Get the Search Box </a>
37 + </td><td style="position:relative">
38 + <a href="'.admin_url().'/edit.php?post_type=gvn_schart&gvnsql_dismiss_recommendation=1'.'" style="position: absolute;right: 0;top: -15px;right: -10px;">{svg}
39 + </a>
40 + <img src="'.plugin_dir_url( __FILE__ ) . 'asset/img/recommended1.jpg" style="max-width: 430px;"></td></tr>
41 + </tbody></table>';
42 +}
14 43
44 +
45 +
15 46 function guaven_sqlcharts_my_admin_notice()
16 47 {
17 48 global $post;
49 +
50 +
51 + if(
52 + (!empty($_SERVER["REQUEST_URI"]) and strpos(sanitize_text_field(wp_unslash($_SERVER["REQUEST_URI"])),'post_type=gvn_schart')!==false)
53 + or
54 + (!empty($post) and $post->post_type == 'gvn_schart')
55 + ){
56 + echo str_replace('{svg}','<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="11" height="14" viewBox="0 0 11 14">
57 + <path d="M10.141 10.328q0 0.312-0.219 0.531l-1.062 1.062q-0.219 0.219-0.531 0.219t-0.531-0.219l-2.297-2.297-2.297 2.297q-0.219 0.219-0.531 0.219t-0.531-0.219l-1.062-1.062q-0.219-0.219-0.219-0.531t0.219-0.531l2.297-2.297-2.297-2.297q-0.219-0.219-0.219-0.531t0.219-0.531l1.062-1.062q0.219-0.219 0.531-0.219t0.531 0.219l2.297 2.297 2.297-2.297q0.219-0.219 0.531-0.219t0.531 0.219l1.062 1.062q0.219 0.219 0.219 0.531t-0.219 0.531l-2.297 2.297 2.297 2.297q0.219 0.219 0.219 0.531z"></path>
58 + </svg>',wp_kses_post(guaven_sqlcharts_recommended(),[]));
59 + }
60 +
61 +
62 +
18 63 if (!empty($post) and $post->post_type == 'gvn_schart'):
19 64 if (!current_user_can('manage_options')) {
20 65 echo '<br><br>
21 66 <div class="updated gf-alert gf-alert-danger">Only administrators can manage this page</div>';
@@ -21,40 +66,127 @@
21 66 <div class="updated gf-alert gf-alert-danger">Only administrators can manage this page</div>';
22 67 die();
23 68 }
24 69 echo '<div class="updated gf-alert gf-alert-info">';
25 - if (empty($_GET["post"]) and strpos($_SERVER["REQUEST_URI"], "post-new") === false):
26 - $gf_message = 'Use <b>Add new</b> button above to create new sql report. And click on any existing rule names below
27 - to manage them. ';
28 - else:
29 - $gf_message = '
30 - 1. Give any name to your report.<br>
31 - 2. Choose chart type, type sql query, enter field names, labels and then press to Publish/Update<br>
32 - 3. After update you will see needed shortcode below. You can use that shortcode anywhere in your website: in pages, posts, widgets etc. <br>
33 - ';
34 -?>
35 - <?php
36 - endif;
37 - _e('<div style="float:left">' . $gf_message . '</div>', 'guaven_sqlcharts');
70 + if (empty($_GET["post"]) && strpos(sanitize_text_field(wp_unslash($_SERVER["REQUEST_URI"])), "post-new") === false) {
71 + $gf_message = __(
72 + 'Use <b>Add new</b> button above to create a new SQL report. And click on any existing rule names below to manage them.',
73 + 'guaven_sqlcharts'
74 + );
75 + } else {
76 + $gf_message = __(
77 + '1. Give any name to your report.<br>
78 + 2. Pick a chart type, build your SQL query with the visual builder (or type it — autocomplete will help), map the X/Y columns and press Publish/Update.<br>
79 + 3. After update, you will see the shortcode of this chart at the bottom of the page. You can use that shortcode anywhere in your website: in pages, posts, widgets, etc.',
80 + 'guaven_sqlcharts'
81 + );
82 + }
83 +
84 + echo '<div style="float:left;max-width:calc(100% - 345px)">';
85 + echo wp_kses_post( $gf_message );
86 + echo '</div>';
87 +
38 88 echo '<div style="float: right;
39 89 margin-top: 0px;
40 - padding-top: 0px;"><a class="button button-secondary" href="http://guaven.com/contact">Contact us for custom reports</a></div> </div>';
90 + padding-top: 0px;"><a target="_blank" style="text-align:center;border:0px solid #6200ee;border-radius:0px;color:white;font-weight:bold;background: #6200ee;"
91 + class="button button-secondary" href="https://guaven.com/contact/solution-request/">Get Premium Support </a>
92 + <span style="line-height: 30px;padding: 0 5px;">OR</span>
93 + <a target="_blank" style="text-align:center;border:0px solid #26b286;border-radius:0px;color:white;font-weight:bold;background: #26b286;"
94 + class="button button-secondary" href="https://guaven.com/service/small-thankyou-premium-support-service/">Make a Small Donation</a>
95 + </div> </div>';
41 96 endif;
42 97 }
43 98 add_action('admin_notices', 'guaven_sqlcharts_my_admin_notice');
44 99
100 +function guaven_sqlcharts_onboarding_notice(){
101 + if((function_exists('wp_doing_ajax') and wp_doing_ajax()) or get_option('guaven_sqlcharts_onboarding_notice_dismissed') == 1)
102 + return;
45 103
104 + printf('
105 + <div class="guaven-sqlcharts-notice notice notice-success is-dismissible" data-notice="onboarding_notice">
106 + <p>Welcome aboard on MySQL Charts!</p>
107 + </div>'
108 + );
109 +}
110 +add_action('admin_notices', 'guaven_sqlcharts_onboarding_notice');
46 111
112 +function guaven_sqlcharts_onboarding_notice_dismissed(){
113 + check_ajax_referer('notice_dismissed', 'nonce');
47 114
115 + if(empty($_POST['type']))return;
116 + switch ($_POST['type']){
117 + case 'onboarding_notice':
118 + update_option('guaven_sqlcharts_onboarding_notice_dismissed', 1);
119 + break;
120 + }
121 +}
122 +add_action('wp_ajax_guaven_sqlcharts_onboarding_notice_dismissed', 'guaven_sqlcharts_onboarding_notice_dismissed');
48 123
124 +function guaven_sqlcharts_enqueue_chart()
125 +{
126 + wp_enqueue_script('guaven_sqlcharts_chartjs', plugins_url('asset/chart.umd.min.js', __FILE__),array('jquery'),GVNSQLCHARTS_VERSION,false);
127 + wp_enqueue_script('guaven_sqlcharts_datepicker', plugins_url('asset/datepicker.min.js', __FILE__),array('jquery'),GVNSQLCHARTS_VERSION,false);
128 + wp_enqueue_script('guaven_sqlcharts_front', plugins_url('asset/front.js', __FILE__),array('jquery','guaven_sqlcharts_chartjs','guaven_sqlcharts_datepicker'),GVNSQLCHARTS_VERSION,false);
129 + wp_localize_script('guaven_sqlcharts_front', 'guaven_sqlcharts_notice_dismissed', array(
130 + 'action' => 'guaven_sqlcharts_onboarding_notice_dismissed',
131 + 'nonce' => wp_create_nonce('notice_dismissed')
132 + ));
49 133
134 +}
135 +add_action('wp_enqueue_scripts', 'guaven_sqlcharts_enqueue_chart');
136 +add_action('admin_enqueue_scripts', 'guaven_sqlcharts_enqueue_chart');
137 +
50 138 function guaven_sqlcharts_enqueue_main_style()
51 139 {
52 - wp_enqueue_style('guaven_sqlcharts_main_style', plugins_url('guaven_sqlcharts.css', __FILE__));
140 + wp_enqueue_style('guaven_sqlcharts_main_style', plugins_url('asset/guaven_sqlcharts.css', __FILE__),array(),GVNSQLCHARTS_VERSION);
53 141 }
142 +add_action('wp_enqueue_scripts', 'guaven_sqlcharts_enqueue_main_style');
143 +add_action('admin_enqueue_scripts', 'guaven_sqlcharts_enqueue_main_style');
54 144
55 -add_action('admin_enqueue_scripts', 'guaven_sqlcharts_enqueue_main_style');
145 +// admin-only assets: SQL builder, autocomplete, new metabox UI
146 +function guaven_sqlcharts_admin_assets($hook)
147 +{
148 + if (!in_array($hook, array('post.php', 'post-new.php'))) return;
149 + $screen = function_exists('get_current_screen') ? get_current_screen() : null;
150 + if (empty($screen->post_type) or $screen->post_type != 'gvn_schart') return;
151 + if (!current_user_can('manage_options')) return;
56 152
153 + wp_enqueue_style('guaven_sqlcharts_admin_style', plugins_url('asset/admin.css', __FILE__), array(), GVNSQLCHARTS_VERSION);
154 + wp_enqueue_script('guaven_sqlcharts_admin', plugins_url('asset/admin.js', __FILE__), array('jquery'), GVNSQLCHARTS_VERSION, true);
155 +
156 + global $wpdb;
157 + $tables = $wpdb->get_col('SHOW TABLES');
158 + if (!is_array($tables)) $tables = array();
159 + wp_localize_script('guaven_sqlcharts_admin', 'gvnSqlBuilder', array(
160 + 'ajaxurl' => admin_url('admin-ajax.php'),
161 + 'nonce' => wp_create_nonce('gvnsql_schema'),
162 + 'tables' => array_values($tables),
163 + 'prefix' => $wpdb->prefix,
164 + ));
165 +}
166 +add_action('admin_enqueue_scripts', 'guaven_sqlcharts_admin_assets');
167 +
168 +// returns column names of one table for the live SQL builder/autocomplete
169 +function guaven_sqlcharts_ajax_columns()
170 +{
171 + check_ajax_referer('gvnsql_schema', 'nonce');
172 + if (!current_user_can('manage_options')) wp_send_json_error('forbidden', 403);
173 + global $wpdb;
174 + $table = isset($_POST['table']) ? sanitize_text_field(wp_unslash($_POST['table'])) : '';
175 + $tables = $wpdb->get_col('SHOW TABLES');
176 + if (!is_array($tables) or !in_array($table, $tables, true)) wp_send_json_error('unknown table', 400);
177 + $cols = $wpdb->get_results('SHOW COLUMNS FROM `' . str_replace('`', '', $table) . '`');
178 + $out = array();
179 + if (is_array($cols)) {
180 + foreach ($cols as $col) {
181 + $out[] = array('name' => $col->Field, 'type' => $col->Type);
182 + }
183 + }
184 + wp_send_json_success($out);
185 +}
186 +add_action('wp_ajax_gvnsql_get_columns', 'guaven_sqlcharts_ajax_columns');
187 +
188 +
57 189 function guaven_sqlcharts_isJson($string)
58 190 {
59 191 json_decode($string);
60 192 return (json_last_error() == JSON_ERROR_NONE);
@@ -62,17 +194,39 @@
62 194
63 195 add_action('init', 'guaven_sqlcharts_register_post');
64 196 function guaven_sqlcharts_register_post()
65 197 {
66 - //register_taxonomy('guaven_update_push_tag', 'termin');
67 198 register_post_type('gvn_schart', array(
68 199 'labels' => array(
69 - 'name' => __('My SQL Charts'),
70 - 'singular_name' => __('My SQL chart')
200 + 'name' => __('My SQL Charts','guaven_sqlcharts'),
201 + 'singular_name' => __('SQL Chart','guaven_sqlcharts'),
202 + 'menu_name' => __('My SQL Charts','guaven_sqlcharts'),
203 + 'add_new' => __('Add Chart','guaven_sqlcharts'),
204 + 'add_new_item' => __('Add New Chart','guaven_sqlcharts'),
205 + 'edit_item' => __('Edit Chart','guaven_sqlcharts'),
206 + 'new_item' => __('New Chart','guaven_sqlcharts'),
207 + 'view_item' => __('View Chart','guaven_sqlcharts'),
208 + 'view_items' => __('View Charts','guaven_sqlcharts'),
209 + 'search_items' => __('Search Charts','guaven_sqlcharts'),
210 + 'not_found' => __('No charts found','guaven_sqlcharts'),
211 + 'not_found_in_trash' => __('No charts found in Trash','guaven_sqlcharts'),
212 + 'all_items' => __('All Charts','guaven_sqlcharts'),
213 + 'archives' => __('Chart Archives','guaven_sqlcharts'),
214 + 'attributes' => __('Chart Attributes','guaven_sqlcharts'),
215 + 'insert_into_item' => __('Insert into chart','guaven_sqlcharts'),
216 + 'uploaded_to_this_item' => __('Uploaded to this chart','guaven_sqlcharts'),
217 + 'filter_items_list' => __('Filter charts list','guaven_sqlcharts'),
218 + 'items_list_navigation' => __('Charts list navigation','guaven_sqlcharts'),
219 + 'items_list' => __('Charts list','guaven_sqlcharts'),
220 + 'item_published' => __('Chart published.','guaven_sqlcharts'),
221 + 'item_published_privately' => __('Chart published privately.','guaven_sqlcharts'),
222 + 'item_reverted_to_draft' => __('Chart reverted to draft.','guaven_sqlcharts'),
223 + 'item_scheduled' => __('Chart scheduled.','guaven_sqlcharts'),
224 + 'item_updated' => __('Chart updated.','guaven_sqlcharts'),
71 225 ),
72 -
226 +
73 227 'public' => true,
74 - //'taxonomies' => array('guaven_update_push_tag'),
228 + 'menu_icon' => 'dashicons-chart-pie',
75 229 'supports' => array(
76 230 'title',
77 231 'postmeta'
78 232 ),
@@ -77,12 +231,18 @@
77 231 'postmeta'
78 232 ),
79 233 'register_meta_box_cb' => 'guaven_sqlcharts_metabox_area'
80 234 ));
81 -
235 +
82 236 guaven_sqlcharts_load_defaults();
83 237 }
84 238
239 +// "Add title" placeholder on the chart edit screen
240 +add_filter('enter_title_here', function ($title, $post) {
241 + if (!empty($post) and $post->post_type == 'gvn_schart') return __('Chart name', 'guaven_sqlcharts');
242 + return $title;
243 +}, 10, 2);
244 +
85 245 add_action('admin_footer', 'guaven_sqlcharts_admin_front');
86 246
87 247
88 248 function guaven_sqlcharts_admin_front()
@@ -97,346 +257,1076 @@
97 257
98 258 // metabox for editor
99 259 function guaven_sqlcharts_metabox_area()
100 260 {
101 - add_meta_box('gvn_schart_metabox', 'Configure your graph chart', 'gvn_schart_metabox', 'gvn_schart', 'advanced', 'default');
261 + add_meta_box('guaven_sqlcharts_metabox', 'Chart Builder', 'guaven_sqlcharts_metabox', 'gvn_schart', 'advanced', 'default');
102 262 }
103 263
104 -function gvn_schart_metabox()
264 +function guaven_sqlcharts_metabox()
105 265 {
106 - global $post;
107 - wp_nonce_field('meta_box_nonce_action', 'meta_box_nonce_field');
108 -
109 -
110 -?>
111 -<h4>Choose your graph</h4>
112 -<p>
113 -<select name="guaven_sqlcharts_graphtype">
114 -<option value="pie" <?php
115 - $guaven_sqlcharts_graphtype = get_post_meta($post->ID, 'guaven_sqlcharts_graphtype', true);
116 - echo ($guaven_sqlcharts_graphtype == 'pie' ? 'selected' : '');
117 -?>>Pie Chart</option>
266 + require_once(dirname(__FILE__) . "/admin_metabox.php");
267 +}
118 268
119 - <option value="3dpie" <?php
120 - echo ($guaven_sqlcharts_graphtype == '3dpie' ? 'selected' : '');
121 -?>>3D Pie Chart</option>
269 +/**
270 + * Catalog of all supported chart types: label, group, per-type usage guide and example query.
271 + * Used by the admin UI to render the type cards and the contextual guides.
272 + */
273 +function guaven_sqlcharts_type_catalog()
274 +{
275 + global $wpdb;
276 + $p = $wpdb->posts;
277 + $u = $wpdb->users;
278 + return array(
279 + 'pie_l' => array(
280 + 'label' => 'Pie',
281 + 'group' => 'Circular',
282 + 'guide' => 'Best for showing how a total splits into a few parts (shares/percentages). Use one query that returns a label column (X) and a numeric value column (Y). Keep it under ~8 slices for readability.',
283 + 'example_sql' => "select count(*) postcount, SUBSTR(post_date,1,4) yearnum from $p group by yearnum order by yearnum asc limit 10",
284 + 'example_x' => 'yearnum', 'example_y' => 'postcount',
285 + ),
286 + 'donut_l' => array(
287 + 'label' => 'Doughnut',
288 + 'group' => 'Circular',
289 + 'guide' => 'Same as Pie but with a hole in the middle — slightly easier to compare slice sizes. One query: label column (X) + numeric column (Y).',
290 + 'example_sql' => "select count(*) postcount, post_type from $p group by post_type order by postcount desc limit 8",
291 + 'example_x' => 'post_type', 'example_y' => 'postcount',
292 + ),
293 + 'polar_l' => array(
294 + 'label' => 'Polar Area',
295 + 'group' => 'Circular',
296 + 'guide' => 'Like a pie, but every slice has the same angle and the value controls the radius. Good for cyclic data (months, weekdays). One query: label (X) + numeric value (Y).',
297 + 'example_sql' => "select count(*) postcount, SUBSTRING(post_date,6,2) monthnum from $p group by monthnum order by monthnum",
298 + 'example_x' => 'monthnum', 'example_y' => 'postcount',
299 + ),
300 + 'radar_l' => array(
301 + 'label' => 'Radar',
302 + 'group' => 'Circular',
303 + 'guide' => 'Compares one or more series across several categories arranged in a circle. Great for profiles/ratings. Use one query per series, separated with ";".',
304 + 'example_sql' => "select count(*) postcount, SUBSTRING(post_date,6,2) monthnum from $p where post_type=\"post\" group by monthnum order by monthnum",
305 + 'example_x' => 'monthnum', 'example_y' => 'postcount',
306 + ),
307 + 'line_l' => array(
308 + 'label' => 'Line',
309 + 'group' => 'Line',
310 + 'guide' => 'The classic choice for trends over time (per day/month/year). X should be an ordered value like a date. Add more queries separated with ";" for comparison lines.',
311 + 'example_sql' => "select count(*) postcount, SUBSTRING(post_date,1,7) monthandyear from $p group by monthandyear order by monthandyear",
312 + 'example_x' => 'monthandyear', 'example_y' => 'postcount',
313 + ),
314 + 'area_l' => array(
315 + 'label' => 'Area',
316 + 'group' => 'Line',
317 + 'guide' => 'A line chart with the region under the line filled — emphasizes volume/magnitude of a trend. Works well with 2 queries (";" separated) to compare filled regions.',
318 + 'example_sql' => "select count(*) postcount, SUBSTRING(post_date,1,7) monthandyear from $p where post_type=\"post\" group by monthandyear order by monthandyear;\nselect count(*) postcount, SUBSTRING(post_date,1,7) monthandyear from $p where post_type!=\"post\" group by monthandyear order by monthandyear",
319 + 'example_x' => 'monthandyear', 'example_y' => 'Posts;Other content',
320 + ),
321 + 'steppedline_l' => array(
322 + 'label' => 'Stepped Line',
323 + 'group' => 'Line',
324 + 'guide' => 'Line chart that moves in steps instead of slopes — perfect for values that change at discrete moments (prices, stock level, settings history).',
325 + 'example_sql' => "select count(*) postcount, SUBSTRING(post_date,1,4) yearnum from $p group by yearnum order by yearnum",
326 + 'example_x' => 'yearnum', 'example_y' => 'postcount',
327 + ),
328 + 'bar_l' => array(
329 + 'label' => 'Bar',
330 + 'group' => 'Bar',
331 + 'guide' => 'Compares values across categories with vertical bars. One query: category (X) + numeric value (Y). Multiple ";" separated queries become grouped/stacked bars.',
332 + 'example_sql' => "select count(*) postcount, SUBSTRING(post_date,1,7) monthandyear from $p group by monthandyear order by monthandyear",
333 + 'example_x' => 'monthandyear', 'example_y' => 'postcount',
334 + ),
335 + 'horizontalbar_l' => array(
336 + 'label' => 'Horizontal Bar',
337 + 'group' => 'Bar',
338 + 'guide' => 'Bar chart rotated 90° — the best pick when category names are long (user names, product titles).',
339 + 'example_sql' => "select count(*) as postcount, b.display_name as dname from $p a inner join $u b ON a.post_author=b.ID where a.post_status=\"publish\" group by a.post_author order by postcount desc limit 10",
340 + 'example_x' => 'dname', 'example_y' => 'postcount',
341 + ),
342 + 'stackedbar_l' => array(
343 + 'label' => 'Stacked Bar',
344 + 'group' => 'Bar',
345 + 'guide' => 'Shows how each category total is composed of parts. Use 2+ queries separated with ";" — each query becomes one segment color of the stack.',
346 + 'example_sql' => "select count(*) postcount, SUBSTRING(post_date,1,4) yearnum from $p where post_type=\"post\" group by yearnum order by yearnum;\nselect count(*) postcount, SUBSTRING(post_date,1,4) yearnum from $p where post_type!=\"post\" group by yearnum order by yearnum",
347 + 'example_x' => 'yearnum', 'example_y' => 'Posts;Other content',
348 + ),
349 + 'scatter_l' => array(
350 + 'label' => 'Scatter',
351 + 'group' => 'Other',
352 + 'guide' => 'Plots points on numeric X/Y axes to reveal correlation between two numbers. Both X and Y columns must be numeric (e.g. comment_count vs menu_order).',
353 + 'example_sql' => "select comment_count ccount, ID from $p where post_status=\"publish\" order by ID limit 100",
354 + 'example_x' => 'ID', 'example_y' => 'ccount',
355 + ),
356 + );
357 +}
122 358
123 -<option value="column" <?php
124 - echo ($guaven_sqlcharts_graphtype == 'column' ? 'selected' : '');
125 -?>>Column Chart</option>
359 +/**
360 + * Maps deprecated Google-Chart era type slugs to their Chart.js equivalents.
361 + * Old charts keep working without any manual migration; when the post is re-saved
362 + * from the new UI the normalized value is stored automatically.
363 + */
364 +function guaven_sqlcharts_normalize_type($type)
365 +{
366 + $map = array(
367 + 'pie' => 'pie_l',
368 + '3dpie' => 'pie_l',
369 + 'column' => 'bar_l',
370 + 'bar' => 'horizontalbar_l',
371 + 'area' => 'area_l',
372 + );
373 + return isset($map[$type]) ? $map[$type] : $type;
374 +}
126 375
127 -<option value="bar" <?php
128 - echo ($guaven_sqlcharts_graphtype == 'bar' ? 'selected' : '');
129 -?>>Bar Chart</option>
376 +function guaven_gutenberg_wrapper($atts){
377 + if(isset($atts['sqlcharts_inserted_script'])){
378 + global $sqlcharts_inserted_script;
379 + $sqlcharts_inserted_script = $atts['sqlcharts_inserted_script'];
380 + }
130 381
131 - <option value="area" <?php
132 - echo ($guaven_sqlcharts_graphtype == 'area' ? 'selected' : '');
133 -?>>Area Chart</option>
134 -
382 + $post = get_post($atts['chart_id']);
383 + if( ! isset($atts['chart_id']) or !isset($post) or $post->post_type != 'gvn_schart'){
135 384
136 -</select>
137 -</p>
138 -<hr>
385 + return "Invalid id";
386 + }
139 387
388 + return guaven_sqlcharts_local_shortcode(array('id' => $atts['chart_id'])); // temporary explicit value
389 +}
390 +function guaven_register_gutenberg_blocks()
391 +{
392 + wp_register_script(
393 + 'gvn_gutenberg_charts',
394 + plugins_url( 'asset/guaven_gutenberg_charts.js', __FILE__ ),
395 + array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-server-side-render' ),
396 + GVNSQLCHARTS_VERSION.'_'.filemtime( plugin_dir_path( __FILE__ ) . 'asset/guaven_gutenberg_charts.js'),
397 + false
398 + );
399 + wp_localize_script('gvn_gutenberg_charts', 'guaven', array(
400 + 'description' => 'Add My SQL Chart to your post',
401 + ));
140 402
403 + register_block_type( 'guaven-sqlcharts/gvn-chart-gutenberg', array(
404 + 'editor_script' => 'gvn_gutenberg_charts',
405 + 'render_callback' => 'guaven_gutenberg_wrapper',
406 + 'attributes' => array(
407 + 'chart_id' => array(
408 + 'type' => 'string',
409 + 'default' => null
410 + ),
411 + 'sqlcharts_inserted_script' => array(
412 + 'type' => 'number',
413 + 'default' => null
414 + )
415 + )
416 + ));
417 +}
418 +add_action('init', 'guaven_register_gutenberg_blocks');
141 419
142 420
143 -<h4>Your SQL code </h4>
144 -<span>(Use double " " quotes instead of single ' ' ones)</span>
145 -<p>
146 -<textarea name="guaven_sqlcharts_code" id="guaven_sqlcharts_code" style="width:100%" rows="6"><?php
147 - echo (get_post_meta($post->ID, 'guaven_sqlcharts_code', true) != '' ? get_post_meta($post->ID, 'guaven_sqlcharts_code', true) : '');
148 -?>
149 -</textarea>
150 -</p>
151 -<p style="text-align: right;">Need help with custom SQL reports? <a href="http://guaven.com/contact">Contact us.</a></p>
152 -<hr>
153 421
422 +function guaven_sqlcharts_save_metabox_area($post_id, $post)
423 +{
424 + if (!isset($_POST['meta_box_nonce_field']) or !wp_verify_nonce($_POST['meta_box_nonce_field'], 'meta_box_nonce_action')) {
425 + return $post->ID;
426 + }
427 + $fields = array(
428 + "guaven_sqlcharts_chartheight",
429 + "guaven_sqlcharts_chartwidth",
430 + "guaven_sqlcharts_graphtype",
431 + "guaven_sqlcharts_xarg_s",
432 + "guaven_sqlcharts_xarg_l",
433 + "guaven_sqlcharts_yarg_s",
434 + "guaven_sqlcharts_yarg_l",
435 + "guaven_sqlcharts_tablepart",
436 + "guaven_sqlcharts_variables",
437 + "guaven_sqlcharts_formpartrole",
438 + "guaven_sqlcharts_formpartbutton",
439 + "guaven_sqlcharts_dbhost",
440 + "guaven_sqlcharts_dblogin",
441 + "guaven_sqlcharts_dbname",
442 + "guaven_sqlcharts_colors",
443 + "guaven_sqlcharts_begin_with_0_x",
444 + "guaven_sqlcharts_begin_with_0_y",
445 + "guaven_sqlcharts_round_y_values",
446 + "guaven_sqlcharts_legend_position",
447 + "guaven_sqlcharts_nostacked",
448 + "guaven_sqlcharts_forcetooltips",
449 + "guaven_sqlcharts_timeaxis"
450 + );
451 + foreach ($fields as $key => $value) {
452 + if(isset($_POST[$value]))$newval=esc_attr($_POST[$value]);
453 + else $newval='';
154 454
455 + update_post_meta($post->ID, $value, $newval);
456 + }
457 + if(!empty($_POST["guaven_sqlcharts_dbpass"])){
458 + $encpass=guaven_sqlcharts_encrypt_decrypt('encrypt',$_POST["guaven_sqlcharts_dbpass"]);
459 + update_post_meta($post->ID, 'guaven_sqlcharts_dbpass', ['encrypted',$encpass]);
460 + }
461 + // Store the SQL as typed. Do not HTML-encode it and do not rewrite quotes:
462 + // the editor escapes it on output and the front end decodes entities before running it.
463 + $sql_code = isset($_POST['guaven_sqlcharts_code']) ? wp_check_invalid_utf8(wp_unslash($_POST['guaven_sqlcharts_code'])) : '';
464 + update_post_meta($post->ID, 'guaven_sqlcharts_code', $sql_code);
465 + // Flag that this chart stores raw SQL. Charts without the flag were saved by
466 + // versions before 3.0.1, which HTML-encoded the query, and still need decoding.
467 + update_post_meta($post->ID, 'guaven_sqlcharts_code_raw', 1);
468 +}
155 469
470 +// Returns the stored SQL query exactly as the user typed it.
471 +function guaven_sqlcharts_get_code($post_id)
472 +{
473 + $sql = get_post_meta($post_id, 'guaven_sqlcharts_code', true);
474 + if (get_post_meta($post_id, 'guaven_sqlcharts_code_raw', true) != 1) {
475 + $sql = html_entity_decode($sql, ENT_QUOTES, 'UTF-8');
476 + }
477 + return $sql;
478 +}
479 +add_action('save_post', 'guaven_sqlcharts_save_metabox_area', 1, 2);
480 +// save the custom fields
156 481
157 -<h4>Arguments</h4>
158 -<p>
159 -Label for Y axis: <br><input type="text" name="guaven_sqlcharts_xarg_l" id="guaven_sqlcharts_xarg_l" value="<?php
160 - echo get_post_meta($post->ID, 'guaven_sqlcharts_xarg_l', true);
161 -?>"></p>
162 - <p>
163 -SQL field name of Y axis (Write corresponding SQL field name here, which has a number value. f.e. post_count):
164 -<br>
165 -<input type="text" name="guaven_sqlcharts_xarg_s" id="guaven_sqlcharts_xarg_s" value="<?php
166 - echo get_post_meta($post->ID, 'guaven_sqlcharts_xarg_s', true);
167 -?>">
168 -</p>
169 482
170 -<p>
171 -Label for X axis: <br><input type="text" name="guaven_sqlcharts_yarg_l" id="guaven_sqlcharts_yarg_l" value="<?php
172 - echo get_post_meta($post->ID, 'guaven_sqlcharts_yarg_l', true);
173 -?>"></p><p>
174 -SQL field name of X axis (Write corresponding SQL field name here, which usually has a string value. f.e. display_name):
175 -<br>
176 -<input type="text" name="guaven_sqlcharts_yarg_s" id="guaven_sqlcharts_yarg_s" value="<?php
177 - echo get_post_meta($post->ID, 'guaven_sqlcharts_yarg_s', true);
178 -?>">
179 -</p>
180 483
181 -<hr>
484 +function gvn_chart_check_sql_query($sql)
485 +{
486 + // case-insensitive, word-boundary check: only read-only SELECT queries are allowed
487 + $pattern = '/\b(delete|update|insert|replace|drop|truncate|alter|create|rename|grant|revoke|call|handler|load\s+data|load_file|outfile|dumpfile)\b/i';
488 + return preg_match($pattern, $sql) ? 1 : 0;
489 +}
182 490
491 +function guaven_get_labels_and_values($id, $fvs)
492 +{
493 + $values = array();
494 + $labels = array();
495 + $xarg_s = get_post_meta($id, 'guaven_sqlcharts_xarg_s', true);
496 + $yarg_s = get_post_meta($id, 'guaven_sqlcharts_yarg_s', true);
497 + // labels are saved through esc_attr, so "&" is stored as "&amp;"; decode before splitting on ";"
498 + // or the entity's own ";" would be taken as a series separator
499 + $xarg_l = html_entity_decode((string) get_post_meta($id, 'guaven_sqlcharts_xarg_l', true), ENT_QUOTES, 'UTF-8');
500 + $yarg_l = html_entity_decode((string) get_post_meta($id, 'guaven_sqlcharts_yarg_l', true), ENT_QUOTES, 'UTF-8');
501 + foreach ($fvs as $key => $value) {
502 + $values[$value->$xarg_s] = $value->$yarg_s;
503 + $labels[$value->$xarg_s] = '"' . $value->$xarg_s . '"';
504 + }
505 + return array(
506 + $labels,
507 + $values,
508 + explode(";", $yarg_l),
509 + explode(";", $xarg_l)
510 + );
511 +}
183 512
184 -<h4>Width and height (with px. don't type px itself, just numbers)</h4>
185 -<p>
513 +function guaven_sqlcharts_print_chart_js($print_data)
514 +{
515 + extract($print_data);
516 + $tip_g = guaven_sqlcharts_normalize_type($tip_g);
186 517
187 -<input type="number" name="guaven_sqlcharts_chartwidth" id="guaven_sqlcharts_chartwidth" value="<?php
188 - echo get_post_meta($post->ID, 'guaven_sqlcharts_chartwidth', true);
189 -?>">
518 + switch ($tip_g) {
519 + case 'line_l':
520 + guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'false', $pid);
521 + break;
522 + case 'area_l':
523 + guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'true', $pid);
524 + break;
525 + case 'steppedline_l':
526 + guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'false', $pid, 'line', true);
527 + break;
528 + case 'radar_l':
529 + guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'radarfill', $pid, 'radar');
530 + break;
531 + case 'pie_l':
532 + guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid);
533 + break;
534 + case 'donut_l':
535 + guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, 'doughnut');
536 + break;
537 + case 'polar_l':
538 + guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, 'polarArea');
539 + break;
540 + case 'bar_l':
541 + guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, 'bar', $pid);
542 + break;
543 + case 'horizontalbar_l':
544 + guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, 'horizontalBar', $pid);
545 + break;
546 + case 'stackedbar_l':
547 + guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, 'stackedBar', $pid);
548 + break;
549 + case 'scatter_l':
550 + guaven_sqlcharts_scatterdata($title, $labels, $values, $ylabel, $pid);
551 + break;
552 + case 'custom':
553 + guaven_sqlcharts_custom($title, $labels, $values, $ylabel, $pid);
554 + break;
555 + }
556 +}
190 557
191 -<input type="number" name="guaven_sqlcharts_chartheight" id="guaven_sqlcharts_chartheight" value="<?php
192 - echo get_post_meta($post->ID, 'guaven_sqlcharts_chartheight', true);
193 -?>">
194 -</p>
558 +function guaven_sqlcharts_custom($title, $labels, $values, $ylabel, $pid){
559 + do_action('guaven_sqlcharts_custom',$title, $labels, $values, $ylabel, $pid);
560 +}
195 561
196 -<hr>
562 +function gvn_chart_put_variables($sql,$pid){
563 + $sql_initial=$sql;
197 564
198 565
566 + $default_tag_keys=['{current_user_id}','{current_user_login}','{current_user_email}','{current_user_display_name}'];
567 + if(is_user_logged_in( )){
568 + $currentuser=wp_get_current_user();
569 + $default_tag_values=[$currentuser->ID,$currentuser->user_login,$currentuser->user_email,$currentuser->user_display_name];
570 + }
571 + else {
572 + $default_tag_values='';
573 + }
574 + $sql_initial=str_replace($default_tag_keys,$default_tag_values,$sql_initial);
199 575
576 + $variables_raw=get_post_meta($pid,'guaven_sqlcharts_variables',true);
577 + $variables_arr=explode("|",$variables_raw);
578 + foreach($variables_arr as $varfield){
579 + $varfield_arr=explode("~",$varfield);
580 + if (count($varfield_arr)<3) continue;
581 + $varfield_arr=array_map("trim",$varfield_arr);
582 + if (!empty($_GET[$varfield_arr[0]])) {
583 + // User-supplied input: no () bypass allowed — sanitize strictly
584 + $varreplacement = sanitize_text_field(wp_unslash($_GET[$varfield_arr[0]]));
585 + if (is_numeric($varreplacement)) {
586 + $varreplacement = $varreplacement + 0;
587 + } else {
588 + $varreplacement = '"' . esc_sql($varreplacement) . '"';
589 + }
590 + } else {
591 + // Admin-configured default value: allow () for SQL functions (e.g. NOW())
592 + $varreplacement = $varfield_arr[1];
593 + if (!is_numeric($varreplacement) && strpos($varreplacement,'()')===false) {
594 + $varreplacement = '"' . esc_sql($varreplacement) . '"';
595 + }
596 + }
200 597
201 -<?php
202 - if (get_post_meta($post->ID, 'guaven_sqlcharts_graphtype', true) != '') {
203 -?>
204 -<div class="gf-alert-success gf-alert">
205 -<h4>
206 -Text shortcode: [gvn_schart id="<?php
207 - echo $post->ID;
208 -?>"]
209 -<br>
210 -<br>
211 -PHP shorcode: &lt;?php echo do_shortcode(' [gvn_schart id="<?php
212 - echo $post->ID;
213 -?>"]'); ?&gt;
214 -</h4>
215 -<p>Note: Shortcodes supports width and height attributes. F.e. [gvn_schart id="1" width="500" height="400"]. If no attributes, default width, height (which you enter in this page above) will be used.
216 -</div>
217 -<h4>Demo</h4>
218 -<?php
219 - echo do_shortcode(' [gvn_schart id="' . $post->ID . '"]');
220 -
598 + $sql_initial=str_replace('{'.$varfield_arr[0].'}',$varreplacement,$sql_initial);
599 + }
600 + return $sql_initial;
601 +}
602 +
603 +function gvn_chart_top_form($atts){
604 + if (get_post_meta($atts["id"],'guaven_sqlcharts_formpartrole',true)!='' and !is_user_logged_in()) return;
605 + $topform='';$dateexists=false;
606 + $variables_raw=get_post_meta($atts['id'],'guaven_sqlcharts_variables',true);
607 + $variables_raw=explode("|",$variables_raw);
608 + foreach ($variables_raw as $vrow){
609 + $vrow_arr=explode("~",$vrow);
610 + $vrow_arr=array_map("trim",$vrow_arr);
611 + if (empty($vrow_arr[3])) continue;
612 + $gvalue=!empty($_GET[$vrow_arr[0]])?esc_attr(urldecode($_GET[$vrow_arr[0]])):'';
613 + $dvalue=(strpos($vrow_arr[1],'()')===false)?esc_attr($vrow_arr[1]):'';
614 + if ($vrow_arr[3]=='date') {
615 + $dateexists=true;
616 + $topform.= '<span class="gvn-filter-field"><label>'.$vrow_arr[2].'</label> <input class="gws_datepicker" autocomplete="off" type="text"
617 + value="'.$gvalue.'"
618 + data-toggle="datepicker" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'"></span>
619 + ';}
620 + else {
621 + $topform.= '<span class="gvn-filter-field"><label>'.$vrow_arr[2].'</label> <input autocomplete="off"
622 + type="'.$vrow_arr[3].'"
623 + value="'.$gvalue.'" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'"></span>
624 + ';
221 625 }
222 -
626 + }
627 + if (!empty($topform)) {
628 + $allowed_html = array(
629 + 'form' => array(
630 + 'method' => array(),
631 + 'action' => array(),
632 + 'class' => array()
633 + ),
634 + 'input' => array(
635 + 'type' => array(),
636 + 'value' => array(),
637 + 'name' => array(),
638 + 'class' => array(),
639 + 'data-toggle'=>array(),
640 + 'placeholder'=>array(),
641 + 'autocomplete'=>array(),
642 + 'style'=>[]
643 + ),
644 + 'span' => array('class' => array()),
645 + 'label' => array(),
646 + );
647 +
648 + $submit_button_value = get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true) != ''
649 + ? esc_attr(get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true))
650 + : 'OK';
651 +
652 + $topform = '<form method="get" action="" class="guaven_sqlcharts_form">' . $topform . '
653 + <input type="submit" value="' . $submit_button_value . '"></form>';
654 +
655 + echo wp_kses($topform, $allowed_html);
656 + }
223 657 }
224 658
225 659
660 +function guaven_sqlcharts_encrypt_decrypt($action, $string)
661 +{
662 + $output = false;
663 + $encrypt_method = "AES-256-CBC";
664 + $secret_key = 'GWSCHARTPL2022.2016.';
665 + $secret_iv = 'GWSCHARTPL2016.2022';
666 + $key = hash('sha256', $secret_key);
667 + $iv = substr(hash('sha256', $secret_iv), 0, 16);
668 + if ( $action == 'encrypt' ) {
669 + $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
670 + $output = base64_encode($output);
671 + } else if( $action == 'decrypt' ) {
672 + $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
673 + }
674 + return $output;
675 +}
226 676
227 -function gvn_schart_save_metabox_area($post_id, $post)
228 -{
229 -
230 - if (!isset($_POST['meta_box_nonce_field']) or !wp_verify_nonce($_POST['meta_box_nonce_field'], 'meta_box_nonce_action')) {
231 - return $post->ID;
677 +function guaven_sqlcharts_local_shortcode($atts) {
678 + if(empty($atts['id']))return 'ID is missing.';
679 + $atts['id']=intval($atts['id']);
680 + $remote_host=get_post_meta($atts['id'], 'guaven_sqlcharts_dbhost', true);
681 + if ($remote_host!=''){
682 + $remote_db=get_post_meta($atts['id'], 'guaven_sqlcharts_dbname', true);
683 + $remote_login=get_post_meta($atts['id'], 'guaven_sqlcharts_dblogin', true);
684 + $remote_pass=get_post_meta($atts['id'], 'guaven_sqlcharts_dbpass', true);
685 + if(is_array($remote_pass)){
686 + $remote_pass=guaven_sqlcharts_encrypt_decrypt('decrypt',$remote_pass[1]);
687 + }
688 + $wpdb=new wpdb($remote_login,$remote_pass,$remote_db,$remote_host);
232 689 }
233 - $fields = array(
234 - "guaven_sqlcharts_chartheight",
235 - "guaven_sqlcharts_chartwidth",
236 - "guaven_sqlcharts_graphtype",
237 - "guaven_sqlcharts_code",
238 - "guaven_sqlcharts_xarg_s",
239 - "guaven_sqlcharts_xarg_l",
240 - "guaven_sqlcharts_yarg_s",
241 - "guaven_sqlcharts_yarg_l"
242 - );
243 - foreach ($fields as $key => $value) {
244 - update_post_meta($post->ID, $value, esc_attr($_POST[$value]));
690 + else {
691 + global $wpdb;
245 692 }
693 +
694 + $GLOBALS["guaven_sqlcharts_atts"]=$atts;
695 +
696 + $sql = guaven_sqlcharts_get_code($atts['id']);
697 + if(empty($sql))return 'SQL query is missing.';
698 + $sql=gvn_chart_put_variables($sql,$atts['id']);
699 +
700 +
701 + $sql=apply_filters('guaven_sqlcharts_rendered_sql',$sql,$atts);
702 +
703 + $blacklister_f = gvn_chart_check_sql_query($sql);
704 + if ($blacklister_f == 1)return 'You given SQL code contains forbidden commands. Remember that you should only use SELECT queries';
705 + $tip_g = guaven_sqlcharts_normalize_type(get_post_meta($atts['id'], 'guaven_sqlcharts_graphtype', true));
706 +
707 + // {arg1}..{arg19} come from shortcode attributes: [gvn_schart_2 id="1" arg1="41"].
708 + // Substituted directly (not via wpdb::prepare) so the same tag may appear any number of times,
709 + // e.g. in every query of a ";"-separated comparison chart. Numbers are inserted as-is, anything
710 + // else is escaped and quoted; a tag already wrapped in quotes ('{arg1}') is not double-quoted.
711 + for($i=1;$i<20;$i++){
712 + $tag = '{arg'.$i.'}';
713 + if (strpos($sql, $tag) === false) continue;
714 + $replacearg = !empty($atts['arg'.$i]) ? $atts['arg'.$i] : 0;
715 + if (is_numeric($replacearg)) $replacearg = $replacearg + 0;
716 + else $replacearg = "'" . esc_sql($replacearg) . "'";
717 + $sql = str_replace(array("'".$tag."'", '"'.$tag.'"', $tag), $replacearg, $sql);
718 + }
719 +
720 + $sql_split = explode(';', $sql);
721 + $labels_and_values = array();
722 + $labels = $values = $ylabel = $xlabel = array();
723 + $post_g = get_post($atts['id']);
724 +
725 + global $sqlcharts_inserted_script;
726 + ob_start();
727 + for ($i = 0; $i < count($sql_split); $i++) {
728 + if (!empty($sql_split[$i])) {
729 +
730 + $fvs = $wpdb->get_results($sql_split[$i]);
731 + if (strpos($_SERVER["REQUEST_URI"],'wp-admin')!==false){
732 + $wpdb->show_errors();
733 + ob_start();
734 + $wpdb->print_error();
735 + $printerror = ob_get_clean();
736 + if ($printerror != '' and strpos($printerror, "[]") === false){
737 + ob_end_clean();
738 + return $printerror;
739 + }
740 + elseif (empty($fvs)){
741 + ob_end_clean();
742 + return 'Your SQL returnes empty data, please recheck your SQL query above';
743 + }
744 + }
745 +
746 + if (empty($sqlcharts_inserted_script))
747 + $sqlcharts_inserted_script = 1;
748 + $labels_and_values[$i] = guaven_get_labels_and_values($atts['id'], $fvs);
749 + $labels[$i] = $labels_and_values[$i][0];
750 + $values[$i] = $labels_and_values[$i][1];
751 + $ylabel[$i] = !empty($labels_and_values[$i][2][$i]) ? $labels_and_values[$i][2][$i] : '';
752 + $xlabel[$i] = !empty($labels_and_values[$i][3][$i]) ? $labels_and_values[$i][3][$i] : '';
753 + }
754 + }
755 +
756 + gvn_chart_top_form($atts);
757 +
758 + // shortcode width/height attributes override the saved defaults
759 + $chart_w = !empty($atts['width']) ? $atts['width'] : get_post_meta($atts['id'], 'guaven_sqlcharts_chartwidth', true);
760 + $chart_h = !empty($atts['height']) ? $atts['height'] : get_post_meta($atts['id'], 'guaven_sqlcharts_chartheight', true);
761 + $wrap_style = '';
762 + if ($chart_w != '') $wrap_style .= 'max-width:' . (int) $chart_w . 'px;';
763 + if ($chart_h != '') $wrap_style .= 'height:' . (int) $chart_h . 'px;';
764 + ?>
765 + <div class="gvn-chartwrap"<?php echo $wrap_style != '' ? ' style="' . esc_attr($wrap_style) . '"' : ''; ?>>
766 + <canvas
767 + id="ct-chart_<?php echo esc_attr($sqlcharts_inserted_script); ?>"
768 + class="guaven_chart_canvas"
769 + ></canvas>
770 + </div>
771 +
772 + <script type="text/javascript" class="gvn_charts_script" async>
773 + var ctx = jQuery("#ct-chart_<?php
774 + echo esc_attr($sqlcharts_inserted_script);
775 + ?>");
776 +
777 + <?php
778 + $print_data=apply_filters('guaven_sqlcharts_pre_print_vars',['tip_g'=>$tip_g, 'title'=>$post_g->post_title,
779 + 'labels'=>$labels, 'values'=>$values, 'ylabel'=>$ylabel, 'pid'=>$atts['id']]);
780 + guaven_sqlcharts_print_chart_js($print_data);
781 + ?>
782 + </script>
783 +
784 + <?php
785 + if (!empty($atts["table"])) guaven_sqlcharts_tablepart($post_g->post_title, $labels, $values, $ylabel,$xlabel);
786 + $sqlcharts_inserted_script++;
787 + $ret=ob_get_clean();
788 + $ret=apply_filters( 'guaven_sqlcharts_final_output', $ret, $atts );
789 + return $ret;
246 790 }
247 -add_action('save_post', 'gvn_schart_save_metabox_area', 1, 2);
248 -// save the custom fields
249 791
792 +add_shortcode('gvn_schart_2', 'guaven_sqlcharts_local_shortcode');
250 793
794 +// legacy alias: old Google-Chart era posts produced [gvn_schart id=".."] shortcodes
795 +if (!shortcode_exists('gvn_schart')) {
796 + add_shortcode('gvn_schart', 'guaven_sqlcharts_local_shortcode');
797 +}
251 798
799 +// [gvn_schart_2_cached id="1" expire="3600" arg1=".."] – same as gvn_schart_2 but the output is kept in a
800 +// transient. All other attributes (argN, width, height, table, params) are passed through, and each
801 +// distinct set of attributes gets its own cache entry. Append ?force_sql_cache_reload to the URL to bypass.
802 +add_shortcode("gvn_schart_2_cached",function($atts){
803 + if(empty($atts["id"]))return;
804 + $atts["id"]=intval($atts["id"]);
805 + $is_logged_in=is_user_logged_in()?'':'_guest';
806 + $expire=!empty($atts["expire"])?intval($atts["expire"]):3600;
807 + $inner_atts=$atts;
808 + unset($inner_atts['expire']);
809 + $key='cached_sql_charts_'.$atts["id"].$is_logged_in;
810 + if (count($inner_atts) > 1) $key .= '_'.md5(serialize($inner_atts));
811 + $cached=get_transient($key);
812 + if(!empty($cached) and !isset($_GET["force_sql_cache_reload"]) )return $cached;
813 + $tobecached=guaven_sqlcharts_local_shortcode($inner_atts);
814 + set_transient($key, $tobecached,$expire);
815 + return $tobecached;
816 +});
252 817
253 -function gvn_schart_libloads($type, $step)
254 -{
255 - $stty = array(
256 - 'bar' => array(
257 - 'packages' => "'corechart', 'bar'",
258 - 'charts' => "BarChart"
259 - ),
260 - 'column' => array(
261 - 'packages' => "'corechart', 'bar'",
262 - 'charts' => "ColumnChart"
263 - ),
264 - 'area' => array(
265 - 'packages' => "'corechart'",
266 - 'charts' => "AreaChart"
267 - ),
268 - 'pie' => array(
269 - 'packages' => "'corechart'",
270 - 'charts' => "PieChart"
271 - ),
272 - '3dpie' => array(
273 - 'packages' => "'corechart'",
274 - 'charts' => "PieChart"
275 - )
276 - );
277 -
278 - return $stty[$type][$step];
818 +// fixed, colorblind-friendly default palette (Tableau 10) used when no custom colors are set
819 +function guaven_sqlcharts_default_palette(){
820 + return apply_filters('guaven_sqlcharts_default_palette', array(
821 + '#4E79A7', '#F28E2B', '#E15759', '#76B7B2', '#59A14F',
822 + '#EDC948', '#B07AA1', '#FF9DA7', '#9C755F', '#BAB0AC'
823 + ));
279 824 }
280 825
826 +function guaven_sqlcharts_colors($index, $pid = null){
827 + if(!isset($pid)) {
828 + global $post;
829 + $pid = $post->ID;
830 + }
831 + $colors=get_post_meta($pid,'guaven_sqlcharts_colors',true);
832 + $colors=explode(",",$colors);
833 + if (!empty($colors[$index])) return $colors[$index];
834 + $palette = guaven_sqlcharts_default_palette();
835 + return $palette[$index % count($palette)];
836 +}
281 837
838 +// outputs 'maintainAspectRatio:false,' when an explicit height is set, so the
839 +// chart fills its sized wrapper instead of keeping the default aspect ratio
840 +function guaven_sqlcharts_mar($pid){
841 + $atts = isset($GLOBALS["guaven_sqlcharts_atts"]) ? $GLOBALS["guaven_sqlcharts_atts"] : array();
842 + $h = !empty($atts['height']) ? $atts['height'] : get_post_meta($pid, 'guaven_sqlcharts_chartheight', true);
843 + return $h != '' ? 'maintainAspectRatio: false,' : '';
844 +}
282 845
846 +// outputs 'showAllTooltips: true,' when "Value labels" is checked; the values are drawn by the
847 +// gvnShowAllValues plugin in asset/front.js (works for every chart type)
848 +function guaven_sqlcharts_value_labels($pid){
849 + return get_post_meta($pid, 'guaven_sqlcharts_forcetooltips', true) != '' ? 'showAllTooltips: true,' : '';
850 +}
283 851
852 +// Chart.js scale title block built from the "X axis label" / "Y axis label" fields.
853 +// $which is 'x' or 'y' (the *field* to use, not the scale). The Y label is only used as an axis
854 +// title for single-series charts; with several ";"-separated series the legend names them instead.
855 +function guaven_sqlcharts_axis_title($pid, $which){
856 + $key = $which == 'x' ? 'guaven_sqlcharts_xarg_l' : 'guaven_sqlcharts_yarg_l';
857 + $text = trim(html_entity_decode((string) get_post_meta($pid, $key, true), ENT_QUOTES, 'UTF-8'));
858 + if ($text === '' or ($which == 'y' and strpos($text, ';') !== false)) return '';
859 + return 'title: {display: true, text: ' . wp_json_encode($text) . '},';
860 +}
284 861
862 +// dataset label as a safe JS string literal (labels saved before 3.0.1 may hold HTML entities)
863 +function guaven_sqlcharts_js_label($label){
864 + return wp_json_encode(html_entity_decode((string) $label, ENT_QUOTES, 'UTF-8'));
865 +}
285 866
286 -function gvn_schart_shortcode($atts)
867 +// Parses an X value for the "time axis" option. Accepts YYYY, YYYY-MM, YYYY-MM-DD, optionally followed
868 +// by HH:MM or HH:MM:SS. Returns a UTC timestamp in milliseconds, or false when the value is not a date.
869 +function guaven_sqlcharts_parse_date($str){
870 + $str = trim((string) $str);
871 + if (!preg_match('/^(\d{4})(?:-(\d{1,2})(?:-(\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?)?)?$/', $str, $m)) return false;
872 + $y = (int) $m[1]; $mo = isset($m[2]) ? (int) $m[2] : 1; $d = isset($m[3]) ? (int) $m[3] : 1;
873 + $h = isset($m[4]) ? (int) $m[4] : 0; $mi = isset($m[5]) ? (int) $m[5] : 0; $sec = isset($m[6]) ? (int) $m[6] : 0;
874 + if (!checkdate($mo, $d, $y) or $h > 23 or $mi > 59 or $sec > 59) return false;
875 + return gmmktime($h, $mi, $sec, $mo, $d, $y) * 1000;
876 +}
877 +
878 +// "Scale X axis by date/time" option. Returns, per dataset, a list of "{x:<ms>,y:<value>}" JS point
879 +// literals when the option is on and every X value is a date; false otherwise (normal category axis).
880 +function guaven_sqlcharts_time_axis_points($pid, $values){
881 + if (get_post_meta($pid, 'guaven_sqlcharts_timeaxis', true) != 1) return false;
882 + $out = array();
883 + $has_point = false;
884 + foreach ($values as $key_ak => $series) {
885 + $out[$key_ak] = array();
886 + foreach ($series as $x => $y) {
887 + $ts = guaven_sqlcharts_parse_date($x);
888 + if ($ts === false) return false;
889 + $out[$key_ak][] = '{x:' . $ts . ',y:' . (is_numeric($y) ? $y + 0 : 'null') . '}';
890 + $has_point = true;
891 + }
892 + }
893 + return $has_point ? $out : false;
894 +}
895 +
896 +// X scale options for time-axis mode; gvnSqlChartsTimeTick (asset/front.js) formats the ticks as dates
897 +function guaven_sqlcharts_time_axis_scale(){
898 + return "type: 'linear', offset: true, ticks: {callback: gvnSqlChartsTimeTick, maxRotation: 45},";
899 +}
900 +// extra entry for the Chart.js "plugins" object in time-axis mode (tooltip title shown as a date)
901 +function guaven_sqlcharts_time_axis_plugins($time_points){
902 + return $time_points !== false ? 'tooltip: {callbacks: {title: gvnSqlChartsTimeTooltipTitle}}' : '';
903 +}
904 +
905 +function guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, $type = 'bar', $pid = null)
287 906 {
288 -
289 -
290 - global $wpdb;
291 - $sql = html_entity_decode(get_post_meta($atts['id'], 'guaven_sqlcharts_code', true));
292 -
293 -
294 - $blacklister = array(
295 - "delete",
296 - "update",
297 - "insert",
298 - "drop",
299 - "truncate"
300 - ); //add all
301 - $blacklister_f = 0;
302 - foreach ($blacklister as $key => $value) {
303 - if (strpos($sql, $value) !== false)
304 - $blacklister_f = 1;
907 + $horizontal = ($type == 'horizontalBar');
908 + $forcestack = ($type == 'stackedBar');
909 + $stacked = ($forcestack or get_post_meta($pid, 'guaven_sqlcharts_nostacked', true) != 1) ? 'true' : 'false';
910 + $time_points = $horizontal ? false : guaven_sqlcharts_time_axis_points($pid, $values);
911 +?>
912 + var data = {
913 + <?php if ($time_points === false) { ?>labels: [<?php guaven_sqlcharts_merge_labeldata($labels);?>],<?php } ?>
914 + datasets: [
915 + <?php
916 + $values_new=guaven_sqlcharts_key_normalizer($values,$labels,$ylabel)[0];
917 + $i=-1;
918 + foreach ($values_new as $key_ak=>$value_ak) {
919 + $i++;
920 + $points = $time_points !== false ? $time_points[$key_ak] : $values_new[$key_ak];
921 +?>
922 + {
923 + <?php
924 + if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
925 + //passing chartJS params via the shortcode
926 + echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
927 + }
928 + ?>
929 + label: <?php echo guaven_sqlcharts_js_label($ylabel[$key_ak]); ?>,
930 + backgroundColor: [
931 + <?php
932 + echo wp_kses(guaven_sqlcharts_colorgenerator(count($points), 0, 0, guaven_sqlcharts_colors($i, $pid)),[]);
933 +?>
934 + ],
935 + borderColor: [
936 + <?php
937 + echo wp_kses(guaven_sqlcharts_colorgenerator(count($points), 0, 0.2, guaven_sqlcharts_colors($i, $pid)),[]);
938 +?>
939 + ],
940 + borderWidth: 1,
941 + <?php if ($time_points !== false) echo 'maxBarThickness: 48,'; ?>
942 + data: [<?php
943 + echo wp_kses(implode(",", $points),[]);
944 +?>],
945 + },
946 + <?php
305 947 }
306 -
307 - if ($blacklister_f == 1)
308 - return 'You given SQL code contains forbidden commands. Remember that you should only use SELECT queries';
309 -
310 - $fvs = $wpdb->get_results($sql);
311 -
312 - $wpdb->show_errors();
313 - ob_start();
314 - $wpdb->print_error();
315 - $printerror = ob_get_clean();
316 -
317 - if ($printerror != '' and strpos($printerror, "[]") === false)
318 - return $printerror;
319 - elseif (empty($fvs))
320 - return 'Your SQL returnes empty date, please recheck your SQL query above';
321 - else {
322 - ob_start();
323 948 ?>
324 -<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
325 -
326 - <script type="text/javascript">;
327 - google.charts.load('current', {'packages':[<?php
328 - $tip_g = get_post_meta($atts['id'], 'guaven_sqlcharts_graphtype', true);
329 -
330 - echo gvn_schart_libloads($tip_g, 'packages');
331 -?>]});
332 - google.charts.setOnLoadCallback(drawChart);
333 - function drawChart() {
949 + ]
950 +};
951 +var options={
952 + responsive: true,
953 + <?php echo wp_kses(guaven_sqlcharts_mar($pid),[]); ?>
954 + <?php echo wp_kses(guaven_sqlcharts_value_labels($pid),[]); ?>
955 + <?php if ($horizontal) echo "indexAxis: 'y',"; ?>
956 + scales: {
957 + x: {
958 + <?php if ($time_points !== false) echo guaven_sqlcharts_time_axis_scale(); ?>
959 + <?php echo guaven_sqlcharts_axis_title($pid, $horizontal ? 'y' : 'x'); ?>
960 + stacked: <?php echo esc_js($stacked); ?>,
961 + beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
962 + },
963 + y: {
964 + <?php echo guaven_sqlcharts_axis_title($pid, $horizontal ? 'x' : 'y'); ?>
965 + stacked: <?php echo esc_js($stacked); ?>,
966 + beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>,
967 + ticks: {
968 + <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
969 + }
970 + }
971 + }
334 972 <?php
335 - $html_temp = '';
336 -
337 - $post_g = get_post($atts['id']);
338 - $xarg_s = get_post_meta($atts['id'], 'guaven_sqlcharts_xarg_s', true);
339 - $xarg_l = get_post_meta($atts['id'], 'guaven_sqlcharts_xarg_l', true);
340 - $yarg_s = get_post_meta($atts['id'], 'guaven_sqlcharts_yarg_s', true);
341 - $yarg_l = get_post_meta($atts['id'], 'guaven_sqlcharts_yarg_l', true);
342 -
343 - $graph_width = get_post_meta($atts['id'], 'guaven_sqlcharts_chartwidth', true);
344 - $graph_height = get_post_meta($atts['id'], 'guaven_sqlcharts_chartheight', true);
345 -
346 - if (!empty($atts["width"])) {
347 - $graph_width = intval($atts['width']);
973 + guaven_sqlcharts_maybe_additional_parameters($pid, guaven_sqlcharts_time_axis_plugins($time_points));
974 + ?>
975 +};
976 +var myBarChart = new Chart(ctx, {
977 + type: 'bar',
978 + data: data,
979 + options: options
980 +});
981 + <?php
982 +}
983 +
984 +function guaven_sqlcharts_merge_labeldata($labels){
985 + if(count($labels)==1){echo wp_kses(implode(",",$labels[0]),[]);return;}
986 + $merged=[];
987 + foreach($labels as $label){
988 + $merged=array_merge($merged,$label);
989 + }
990 + echo wp_kses(implode(",",array_unique($merged)),[]);
991 +}
992 +
993 +function guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, $type = 'false', $pid = null, $charttype = 'line', $stepped = false)
994 +{
995 + $time_points = ($charttype == 'radar') ? false : guaven_sqlcharts_time_axis_points($pid, $values);
996 +?>
997 +var data = {
998 + <?php if ($time_points === false) { ?>labels: [<?php guaven_sqlcharts_merge_labeldata($labels);?>],<?php } ?>
999 + datasets: [
1000 + <?php
1001 + $values_new=guaven_sqlcharts_key_normalizer($values,$labels,$ylabel)[0];
1002 + $dataset_count=count($values_new);
1003 + $i=-1;
1004 + foreach ($values_new as $key_ak=>$value_ak) {
1005 + $i++;
1006 + $points = $time_points !== false ? $time_points[$key_ak] : $values_new[$key_ak];
1007 + if ($type == 'radarfill') $fill = "'origin'";
1008 + elseif ($type == 'false') $fill = 'false';
1009 + else $fill = ($i == 0 and $dataset_count > 1) ? '"+1"' : '"origin"';
1010 +?>
1011 + {
1012 + <?php
1013 + if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
1014 + //passing chartJS params via the shortcode
1015 + echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
1016 + }
1017 + ?>
1018 + label: <?php echo guaven_sqlcharts_js_label($ylabel[$key_ak]); ?>,
1019 + fill: <?php echo wp_kses($fill,[]);
1020 +?>,
1021 + tension: 0.1,
1022 + <?php if ($stepped) echo 'stepped: true,'; ?>
1023 + backgroundColor: <?php
1024 + echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
1025 +?>
1026 + borderColor: <?php
1027 + echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
1028 +?>
1029 + pointBorderColor: <?php
1030 + echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
1031 +?>
1032 + pointHoverBackgroundColor: <?php
1033 + echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
1034 +?>
1035 + pointHoverBorderColor: <?php
1036 + echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
1037 +?>
1038 + data: [<?php
1039 + echo wp_kses_post(implode(",", $points));
1040 +?>],
1041 + spanGaps: false,
1042 + },
1043 + <?php
1044 + }
1045 +?>
1046 + ]
1047 +};
1048 +var myLineChart = new Chart(ctx, {
1049 + type: '<?php echo esc_attr($charttype); ?>',
1050 + data: data,
1051 + options: {
1052 + responsive: true,
1053 + <?php echo wp_kses(guaven_sqlcharts_mar($pid),[]); ?>
1054 + <?php echo wp_kses(guaven_sqlcharts_value_labels($pid),[]); ?>
1055 + <?php if ($charttype == 'radar') { ?>
1056 + scales: {
1057 + r: {
1058 + beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>
1059 + }
348 1060 }
349 - if (!empty($atts["height"])) {
350 - $graph_height = intval($atts['height']);
1061 + <?php } else { ?>
1062 + scales: {
1063 + x: {
1064 + display: true,
1065 + <?php if ($time_points !== false) echo guaven_sqlcharts_time_axis_scale(); ?>
1066 + <?php echo guaven_sqlcharts_axis_title($pid, 'x'); ?>
1067 + beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
1068 + },
1069 + y: {
1070 + <?php echo guaven_sqlcharts_axis_title($pid, 'y'); ?>
1071 + beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>,
1072 + ticks: {
1073 + <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
1074 + }
1075 + }
351 1076 }
352 -
353 - foreach ($fvs as $fv) {
354 - $html_temp .= "['{$fv->$yarg_s}', {$fv->$xarg_s}, '#b87333'],";
355 -
1077 + <?php } ?>
1078 + <?php
1079 + guaven_sqlcharts_maybe_additional_parameters($pid, guaven_sqlcharts_time_axis_plugins($time_points));
1080 + ?>
1081 +
1082 + }
1083 +});
1084 + <?php
1085 +}
1086 +
1087 +function guaven_sqlcharts_scatterdata($title, $labels, $values, $ylabel, $pid = null)
1088 +{
1089 +?>
1090 +var data = {
1091 + datasets: [
1092 + <?php
1093 + $i=-1;
1094 + foreach ($values as $key_ak=>$value_ak) {
1095 + $i++;
1096 + $points=array();
1097 + foreach ($value_ak as $xval=>$yval) {
1098 + $x = is_numeric($xval) ? $xval : '"'.esc_js($xval).'"';
1099 + $y = is_numeric($yval) ? $yval : '"'.esc_js($yval).'"';
1100 + $points[] = '{x:'.$x.',y:'.$y.'}';
356 1101 }
357 -
358 1102 ?>
359 - var data = google.visualization.arrayToDataTable([
360 - ['<?php
361 - echo $yarg_l;
362 -?>', '<?php
363 - echo $xarg_l;
364 -?>', { role: 'style' }],
1103 + {
1104 + <?php
1105 + if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
1106 + //passing chartJS params via the shortcode
1107 + echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
1108 + }
1109 + ?>
1110 + label: <?php echo guaven_sqlcharts_js_label(isset($ylabel[$key_ak])?$ylabel[$key_ak]:''); ?>,
1111 + backgroundColor: <?php
1112 + echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
1113 +?>
1114 + borderColor: <?php
1115 + echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
1116 +?>
1117 + data: [<?php echo wp_kses(implode(",", $points),[]); ?>],
1118 + },
365 1119 <?php
366 - echo $html_temp;
1120 + }
367 1121 ?>
368 - ]);
1122 + ]
1123 +};
1124 +var myScatterChart = new Chart(ctx, {
1125 + type: 'scatter',
1126 + data: data,
1127 + options: {
1128 + responsive: true,
1129 + <?php echo wp_kses(guaven_sqlcharts_mar($pid),[]); ?>
1130 + <?php echo wp_kses(guaven_sqlcharts_value_labels($pid),[]); ?>
1131 + scales: {
1132 + x: {
1133 + <?php echo guaven_sqlcharts_axis_title($pid, 'x'); ?>
1134 + beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
1135 + },
1136 + y: {
1137 + <?php echo guaven_sqlcharts_axis_title($pid, 'y'); ?>
1138 + beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>,
1139 + ticks: {
1140 + <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
1141 + }
1142 + }
1143 + }
1144 + <?php
1145 + guaven_sqlcharts_maybe_additional_parameters($pid);
1146 + ?>
1147 + }
1148 +});
1149 + <?php
1150 +}
369 1151
370 - var options = {
371 - <?php
372 - echo $tip_g == '3dpie' ? "is3D: true," : '';
373 -?>
374 - chart: {
375 - title: '<?php
376 - echo $post_g->post_title;
377 -?>',
378 - }
379 - };
380 1152
381 -var chart = new google.visualization.<?php
382 - echo gvn_schart_libloads(get_post_meta($atts['id'], 'guaven_sqlcharts_graphtype', true), 'charts');
383 -?>(document.getElementById('columnchart_material'));
384 - chart.draw(data, options);
385 - }
1153 +function guaven_sqlcharts_maybe_additional_parameters($pid, $extra_plugins = ''){
1154 + if(function_exists('guaven_sqlcharts_maybe_additional_parameters_custom')){
1155 + wp_kses(guaven_sqlcharts_maybe_additional_parameters_custom($pid),[]);
1156 + return;
1157 + }
1158 + $guaven_sqlcharts_legend_position=get_post_meta($pid, 'guaven_sqlcharts_legend_position', true);
1159 + if(in_array($guaven_sqlcharts_legend_position,['top','bottom','left','right'])){
1160 + $display='true';$position=$guaven_sqlcharts_legend_position;
1161 + }
1162 + else {
1163 + $display='false';$position='top';
1164 + }
1165 + echo wp_kses( ",plugins: {legend: {display: ".$display.",position:'".$position."'}".($extra_plugins !== '' ? ','.$extra_plugins : '')."}",[]);
1166 +}
386 1167
387 - </script>
388 1168
389 -<div id="columnchart_material" style="width:<?php
390 - echo $graph_width > 0 ? intval($graph_width) : '500';
391 -?>px;
392 -height: <?php
393 - echo $graph_height > 0 ? intval($graph_height) : '400';
394 -?>px"></div>
1169 +
1170 +
1171 +function guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, $type = 'pie')
1172 +{
1173 +?>
1174 + var options={
1175 + <?php echo wp_kses(guaven_sqlcharts_value_labels($pid),[]); ?>
1176 + responsive: true
1177 + <?php echo get_post_meta($pid,'guaven_sqlcharts_chartheight',true)!=''||!empty($GLOBALS["guaven_sqlcharts_atts"]['height'])?',maintainAspectRatio: false':''; ?>
1178 + <?php
1179 + guaven_sqlcharts_maybe_additional_parameters($pid);
1180 + ?>
1181 + };
1182 + var data = {
1183 + labels: [ <?php guaven_sqlcharts_merge_labeldata($labels);?>],
1184 + datasets: [
1185 + <?php
1186 + for ($i = 0; $i < count($values); $i++) {
1187 +?>
1188 + {
1189 + <?php
1190 + if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
1191 + //passing chartJS params via the shortcode
1192 + echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
1193 + }
1194 + ?>
1195 + data: [<?php
1196 + echo wp_kses(implode(",", $values[$i]),[]);
1197 +?>],
1198 + backgroundColor: [
1199 + <?php
1200 + $ii=0;
1201 + foreach($values[$i] as $vci=>$valuecolor){
1202 + echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 0, -0.1, guaven_sqlcharts_colors($ii, $pid)));
1203 + $ii++;
1204 + }
1205 +?>
1206 + ],
1207 + hoverBackgroundColor: [
1208 + <?php
1209 + $ii=0;
1210 + foreach($values[$i] as $vci=>$valuecolor){
1211 + echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 0, 0.2, guaven_sqlcharts_colors($ii, $pid)));
1212 + $ii++;
1213 + }
1214 +?>
1215 + ]
1216 + },
395 1217 <?php
396 - return ob_get_clean();
397 1218 }
1219 +?>
1220 + ]
1221 +};
1222 +var myPieChart = new Chart(ctx,{
1223 + type: '<?php
1224 + echo esc_attr($type);
1225 +?>',
1226 + data: data,
1227 + options: options
1228 +});
1229 + <?php
398 1230 }
399 -add_shortcode('gvn_schart', 'gvn_schart_shortcode');
400 1231
401 1232
402 1233
403 1234
404 -function gvn_schart_wp_tags()
1235 +function guaven_sqlcharts_colorgenerator($count, $indic, $darkness = 0, $initcolor = '255,0,0')
405 1236 {
406 - $tags = get_tags(array(
407 - "order" => "DESC",
408 - "orderby" => "count",
409 - "number" => 10
410 - ));
411 - $html = '';
412 - $itag = 0;
413 - $html60 = '';
414 - foreach ($tags as $tag) {
415 - $itag++;
416 - $html_temp .= "['{$tag->name}', {$tag->count}, '#b87333'],";
1237 + if (strpos($initcolor,'#')===0) {
1238 + $split = str_split(substr($initcolor,1), 2);
1239 + $r = hexdec($split[0]);
1240 + $g = hexdec($split[1]);
1241 + $b = hexdec($split[2]);
1242 + $ret='';
1243 + for ($i = 0; $i < $count; $i++) {
1244 + $ret .= "'rgba(" . $r . ", " . $g . ", " . $b . ",".($darkness + 0.8 - $indic * $i * 0.8 / ($count)).")',
1245 + ";
1246 + }
1247 + return $ret;
1248 + }
1249 + $initial_colors = array(
1250 + 'linebg' => 'red',
1251 + 'linebr' => 'yellow',
1252 + 'linebc' => 'green',
1253 + 'linehbg' => 'white',
1254 + 'linehbc' => 'black'
1255 + );
1256 + if (!empty($initial_colors[$count]))
1257 + return '"' . $initial_colors[$count] . '",
1258 + ';
1259 + $ret = '';
1260 + for ($i = 0; $i < $count; $i++) {
1261 + $ret .= "'rgba(" . $initcolor . "," . ($darkness + 0.8 - $indic * $i * 0.8 / ($count)) . ")',
1262 + ";
417 1263 }
418 -?>
419 - var data = google.visualization.arrayToDataTable([
420 - ['Element', 'Density', { role: 'style' }],
421 - <?php
422 - echo $html_temp;
423 -?>
424 - ]);
1264 + return $ret;
1265 +}
425 1266
426 - var options = {
427 - chart: {
428 - title: 'Company Performance',
429 - subtitle: 'Sales, Expenses, and Profit: 2014-2017',
430 - }
431 - };
432 -<?php
433 - return $html_temp;
1267 +function guaven_sqlcharts_tablepart($title, $labels, $values, $ylabel,$xlabel){
1268 + $tabledata='';
1269 + $fcol=[];$scol=[];
1270 + $empty_cell=apply_filters( 'guaven_sqlcharts_table_empty_cell','<td></td>');
1271 + $tablein='';
1272 + foreach($values as $row=>$valuerow){
1273 + foreach ($valuerow as $key => $value) {
1274 + $putval=$labels[$row][$key]??'';
1275 + $fcol[$key]='<td>'.str_replace('"',"",$putval).'</td>';
1276 + $scol[$key][$row]='<td>'.$value.'</td>';
1277 + }
1278 + foreach($scol as $scolkey=>$scolvalue){
1279 + for($i=0;$i<count($values);$i++){
1280 + //echo $i;
1281 + if(!isset($scolvalue[$i]))$scol[$scolkey][$i]=$empty_cell;;
1282 + }
1283 + ksort($scol[$scolkey]);
1284 + }
1285 + }
1286 +
1287 + foreach($fcol as $key=>$value){
1288 + $tablein.='<tr>'.$value.implode(" ",$scol[$key]).'</tr>'.PHP_EOL;
1289 + }
1290 + $tabledata.='<div class="gvn-tablewrap"><table class="gvn-table"><tr><th>'.$xlabel[0].'</th><th>'.implode("</th><th>",$ylabel).'</th></tr>
1291 + '.$tablein.'</table></div><br>';
1292 +
1293 + echo wp_kses_post($tabledata);
1294 +
434 1295 }
435 1296
1297 +function guaven_sqlcharts_graphtype($post){
1298 + if (strpos(get_post_meta($post->ID, 'guaven_sqlcharts_graphtype', true), "_l") !== false)
1299 + $postfix = '_2';
1300 + else $postfix = '';
1301 + return $postfix;
1302 +}
436 1303
437 -function guaven_sqlcharts_install_first_data()
438 -{
439 -
440 - require_once(dirname(__FILE__) . "/initial_data.php");
441 - gvn_chart_sample_nonxml_data();
1304 +add_filter('the_content',function($content){
1305 + if(!is_singular('gvn_schart'))return $content;
1306 + global $post;
1307 + $postfix=guaven_sqlcharts_graphtype($post);
1308 + return '[gvn_schart'.$postfix.' id="'.$post->ID.'"'.
1309 + (get_post_meta($post->ID,'guaven_sqlcharts_tablepart',true)!=''?' table="1"':'')
1310 + .']';
1311 +});
1312 +
1313 +function guaven_sqlcharts_key_normalizer($values,$labels,$ylabel){
1314 + $normalize_keys=[];
1315 + $empty_value=apply_filters( 'guaven_sqlcharts_table_empty_value','');
1316 + foreach ($values as $key_ak=>$value_ak) {
1317 + $normalize_keys=array_merge($normalize_keys,array_keys($values[$key_ak]));
1318 + }
1319 + $values_normalized=[];$labels_normalized=[];$ylabel_normalized=[];
1320 + foreach($normalize_keys as $normalized_key){
1321 + foreach ($values as $key_ak=>$value_ak) {
1322 + $values_normalized[$key_ak][$normalized_key]=isset( $values[$key_ak][$normalized_key])? $values[$key_ak][$normalized_key]:"'".$empty_value."'";
1323 + $labels_normalized[$key_ak][$normalized_key]=isset( $labels[$key_ak][$normalized_key])? $labels[$key_ak][$normalized_key]:"''";
1324 + $ylabel_normalized[$key_ak][$normalized_key]=isset( $ylabel[$key_ak][$normalized_key])? $ylabel[$key_ak][$normalized_key]:"";
1325 + }
1326 + }
1327 + return [$values_normalized,$labels_normalized,$ylabel_normalized];
442 1328 }
1329 +
1330 +
1331 +add_filter('guaven_sqlcharts_table_empty_cell',function($str){return '<td>#</td>';});
1332 +add_filter('guaven_sqlcharts_table_empty_value',function($str){return 'N/A';});