PluginProbe
SQL Chart Builder / 3.0.1
SQL Chart Builder v3.0.1
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
sql-chart-builder / functions.php

functions.php in SQL Chart Builder 3.0.1, at functions.php

1,247 lines 50.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 if (!defined('ABSPATH')) {
3 die;
4 }
5 //postinstall function
6 function guaven_sqlcharts_load_defaults()
7 {
8 if (get_option("guaven_sqlcharts_already_installed_2") === false) {
9 update_option("guaven_sqlcharts_already_installed_2", "1");
10 guaven_sqlcharts_install_first_data();
11
12 }
13 }
14
15 function guaven_sqlcharts_install_first_data()
16 {
17 require_once(dirname(__FILE__) . "/initial_data.php");
18 gvn_chart_sample_nonxml_data();
19 }
20
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 }
43
44
45
46 function guaven_sqlcharts_my_admin_notice()
47 {
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
63 if (!empty($post) and $post->post_type == 'gvn_schart'):
64 if (!current_user_can('manage_options')) {
65 echo '<br><br>
66 <div class="updated gf-alert gf-alert-danger">Only administrators can manage this page</div>';
67 die();
68 }
69 echo '<div class="updated gf-alert gf-alert-info">';
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
88 echo '<div style="float: right;
89 margin-top: 0px;
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>';
96 endif;
97 }
98 add_action('admin_notices', 'guaven_sqlcharts_my_admin_notice');
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;
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');
111
112 function guaven_sqlcharts_onboarding_notice_dismissed(){
113 check_ajax_referer('notice_dismissed', 'nonce');
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');
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 ));
133
134 }
135 add_action('wp_enqueue_scripts', 'guaven_sqlcharts_enqueue_chart');
136 add_action('admin_enqueue_scripts', 'guaven_sqlcharts_enqueue_chart');
137
138 function guaven_sqlcharts_enqueue_main_style()
139 {
140 wp_enqueue_style('guaven_sqlcharts_main_style', plugins_url('asset/guaven_sqlcharts.css', __FILE__),array(),GVNSQLCHARTS_VERSION);
141 }
142 add_action('wp_enqueue_scripts', 'guaven_sqlcharts_enqueue_main_style');
143 add_action('admin_enqueue_scripts', 'guaven_sqlcharts_enqueue_main_style');
144
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;
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
189 function guaven_sqlcharts_isJson($string)
190 {
191 json_decode($string);
192 return (json_last_error() == JSON_ERROR_NONE);
193 }
194
195 add_action('init', 'guaven_sqlcharts_register_post');
196 function guaven_sqlcharts_register_post()
197 {
198 register_post_type('gvn_schart', array(
199 'labels' => array(
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'),
225 ),
226
227 'public' => true,
228 'menu_icon' => 'dashicons-chart-pie',
229 'supports' => array(
230 'title',
231 'postmeta'
232 ),
233 'register_meta_box_cb' => 'guaven_sqlcharts_metabox_area'
234 ));
235
236 guaven_sqlcharts_load_defaults();
237 }
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
245 add_action('admin_footer', 'guaven_sqlcharts_admin_front');
246
247
248 function guaven_sqlcharts_admin_front()
249 {
250 global $post;
251 if (!empty($post) and $post->post_type == 'gvn_schart') {
252 ?>
253 <style type="text/css">#normal-sortables{display: none}</style>
254 <?php
255 }
256 }
257
258 // metabox for editor
259 function guaven_sqlcharts_metabox_area()
260 {
261 add_meta_box('guaven_sqlcharts_metabox', 'Chart Builder', 'guaven_sqlcharts_metabox', 'gvn_schart', 'advanced', 'default');
262 }
263
264 function guaven_sqlcharts_metabox()
265 {
266 require_once(dirname(__FILE__) . "/admin_metabox.php");
267 }
268
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 }
358
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 }
375
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 }
381
382 $post = get_post($atts['chart_id']);
383 if( ! isset($atts['chart_id']) or !isset($post) or $post->post_type != 'gvn_schart'){
384
385 return "Invalid id";
386 }
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 ));
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');
419
420
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 );
450 foreach ($fields as $key => $value) {
451 if(isset($_POST[$value]))$newval=esc_attr($_POST[$value]);
452 else $newval='';
453
454 update_post_meta($post->ID, $value, $newval);
455 }
456 if(!empty($_POST["guaven_sqlcharts_dbpass"])){
457 $encpass=guaven_sqlcharts_encrypt_decrypt('encrypt',$_POST["guaven_sqlcharts_dbpass"]);
458 update_post_meta($post->ID, 'guaven_sqlcharts_dbpass', ['encrypted',$encpass]);
459 }
460 // Store the SQL as typed. Do not HTML-encode it and do not rewrite quotes:
461 // the editor escapes it on output and the front end decodes entities before running it.
462 $sql_code = isset($_POST['guaven_sqlcharts_code']) ? wp_check_invalid_utf8(wp_unslash($_POST['guaven_sqlcharts_code'])) : '';
463 update_post_meta($post->ID, 'guaven_sqlcharts_code', $sql_code);
464 // Flag that this chart stores raw SQL. Charts without the flag were saved by
465 // versions before 3.0.1, which HTML-encoded the query, and still need decoding.
466 update_post_meta($post->ID, 'guaven_sqlcharts_code_raw', 1);
467 }
468
469 // Returns the stored SQL query exactly as the user typed it.
470 function guaven_sqlcharts_get_code($post_id)
471 {
472 $sql = get_post_meta($post_id, 'guaven_sqlcharts_code', true);
473 if (get_post_meta($post_id, 'guaven_sqlcharts_code_raw', true) != 1) {
474 $sql = html_entity_decode($sql, ENT_QUOTES, 'UTF-8');
475 }
476 return $sql;
477 }
478 add_action('save_post', 'guaven_sqlcharts_save_metabox_area', 1, 2);
479 // save the custom fields
480
481
482
483 function gvn_chart_check_sql_query($sql)
484 {
485 // case-insensitive, word-boundary check: only read-only SELECT queries are allowed
486 $pattern = '/\b(delete|update|insert|replace|drop|truncate|alter|create|rename|grant|revoke|call|handler|load\s+data|load_file|outfile|dumpfile)\b/i';
487 return preg_match($pattern, $sql) ? 1 : 0;
488 }
489
490 function guaven_get_labels_and_values($id, $fvs)
491 {
492 $values = array();
493 $labels = array();
494 $xarg_s = get_post_meta($id, 'guaven_sqlcharts_xarg_s', true);
495 $xarg_l = get_post_meta($id, 'guaven_sqlcharts_xarg_l', true);
496 $yarg_s = get_post_meta($id, 'guaven_sqlcharts_yarg_s', true);
497 $yarg_l = get_post_meta($id, 'guaven_sqlcharts_yarg_l', true);
498 foreach ($fvs as $key => $value) {
499 $values[$value->$xarg_s] = $value->$yarg_s;
500 $labels[$value->$xarg_s] = '"' . $value->$xarg_s . '"';
501 }
502 return array(
503 $labels,
504 $values,
505 explode(";", $yarg_l),
506 explode(";", $xarg_l)
507 );
508 }
509
510 function guaven_sqlcharts_print_chart_js($print_data)
511 {
512 extract($print_data);
513 $tip_g = guaven_sqlcharts_normalize_type($tip_g);
514
515 switch ($tip_g) {
516 case 'line_l':
517 guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'false', $pid);
518 break;
519 case 'area_l':
520 guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'true', $pid);
521 break;
522 case 'steppedline_l':
523 guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'false', $pid, 'line', true);
524 break;
525 case 'radar_l':
526 guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'radarfill', $pid, 'radar');
527 break;
528 case 'pie_l':
529 guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid);
530 break;
531 case 'donut_l':
532 guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, 'doughnut');
533 break;
534 case 'polar_l':
535 guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, 'polarArea');
536 break;
537 case 'bar_l':
538 guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, 'bar', $pid);
539 break;
540 case 'horizontalbar_l':
541 guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, 'horizontalBar', $pid);
542 break;
543 case 'stackedbar_l':
544 guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, 'stackedBar', $pid);
545 break;
546 case 'scatter_l':
547 guaven_sqlcharts_scatterdata($title, $labels, $values, $ylabel, $pid);
548 break;
549 case 'custom':
550 guaven_sqlcharts_custom($title, $labels, $values, $ylabel, $pid);
551 break;
552 }
553 }
554
555 function guaven_sqlcharts_custom($title, $labels, $values, $ylabel, $pid){
556 do_action('guaven_sqlcharts_custom',$title, $labels, $values, $ylabel, $pid);
557 }
558
559 function gvn_chart_put_variables($sql,$pid){
560 $sql_initial=$sql;
561
562
563 $default_tag_keys=['{current_user_id}','{current_user_login}','{current_user_email}','{current_user_display_name}'];
564 if(is_user_logged_in( )){
565 $currentuser=wp_get_current_user();
566 $default_tag_values=[$currentuser->ID,$currentuser->user_login,$currentuser->user_email,$currentuser->user_display_name];
567 }
568 else {
569 $default_tag_values='';
570 }
571 $sql_initial=str_replace($default_tag_keys,$default_tag_values,$sql_initial);
572
573 $variables_raw=get_post_meta($pid,'guaven_sqlcharts_variables',true);
574 $variables_arr=explode("|",$variables_raw);
575 foreach($variables_arr as $varfield){
576 $varfield_arr=explode("~",$varfield);
577 if (count($varfield_arr)<3) continue;
578 $varfield_arr=array_map("trim",$varfield_arr);
579 if (!empty($_GET[$varfield_arr[0]])) {
580 // User-supplied input: no () bypass allowed — sanitize strictly
581 $varreplacement = sanitize_text_field(wp_unslash($_GET[$varfield_arr[0]]));
582 if (is_numeric($varreplacement)) {
583 $varreplacement = $varreplacement + 0;
584 } else {
585 $varreplacement = '"' . esc_sql($varreplacement) . '"';
586 }
587 } else {
588 // Admin-configured default value: allow () for SQL functions (e.g. NOW())
589 $varreplacement = $varfield_arr[1];
590 if (!is_numeric($varreplacement) && strpos($varreplacement,'()')===false) {
591 $varreplacement = '"' . esc_sql($varreplacement) . '"';
592 }
593 }
594
595 $sql_initial=str_replace('{'.$varfield_arr[0].'}',$varreplacement,$sql_initial);
596 }
597 return $sql_initial;
598 }
599
600 function gvn_chart_top_form($atts){
601 if (get_post_meta($atts["id"],'guaven_sqlcharts_formpartrole',true)!='' and !is_user_logged_in()) return;
602 $topform='';$dateexists=false;
603 $variables_raw=get_post_meta($atts['id'],'guaven_sqlcharts_variables',true);
604 $variables_raw=explode("|",$variables_raw);
605 foreach ($variables_raw as $vrow){
606 $vrow_arr=explode("~",$vrow);
607 $vrow_arr=array_map("trim",$vrow_arr);
608 if (empty($vrow_arr[3])) continue;
609 $gvalue=!empty($_GET[$vrow_arr[0]])?esc_attr(urldecode($_GET[$vrow_arr[0]])):'';
610 $dvalue=(strpos($vrow_arr[1],'()')===false)?esc_attr($vrow_arr[1]):'';
611 if ($vrow_arr[3]=='date') {
612 $dateexists=true;
613 $topform.= '<span class="gvn-filter-field"><label>'.$vrow_arr[2].'</label> <input class="gws_datepicker" autocomplete="off" type="text"
614 value="'.$gvalue.'"
615 data-toggle="datepicker" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'"></span>
616 ';}
617 else {
618 $topform.= '<span class="gvn-filter-field"><label>'.$vrow_arr[2].'</label> <input autocomplete="off"
619 type="'.$vrow_arr[3].'"
620 value="'.$gvalue.'" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'"></span>
621 ';
622 }
623 }
624 if (!empty($topform)) {
625 $allowed_html = array(
626 'form' => array(
627 'method' => array(),
628 'action' => array(),
629 'class' => array()
630 ),
631 'input' => array(
632 'type' => array(),
633 'value' => array(),
634 'name' => array(),
635 'class' => array(),
636 'data-toggle'=>array(),
637 'placeholder'=>array(),
638 'autocomplete'=>array(),
639 'style'=>[]
640 ),
641 'span' => array('class' => array()),
642 'label' => array(),
643 );
644
645 $submit_button_value = get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true) != ''
646 ? esc_attr(get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true))
647 : 'OK';
648
649 $topform = '<form method="get" action="" class="guaven_sqlcharts_form">' . $topform . '
650 <input type="submit" value="' . $submit_button_value . '"></form>';
651
652 echo wp_kses($topform, $allowed_html);
653 }
654 }
655
656
657 function guaven_sqlcharts_encrypt_decrypt($action, $string)
658 {
659 $output = false;
660 $encrypt_method = "AES-256-CBC";
661 $secret_key = 'GWSCHARTPL2022.2016.';
662 $secret_iv = 'GWSCHARTPL2016.2022';
663 $key = hash('sha256', $secret_key);
664 $iv = substr(hash('sha256', $secret_iv), 0, 16);
665 if ( $action == 'encrypt' ) {
666 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
667 $output = base64_encode($output);
668 } else if( $action == 'decrypt' ) {
669 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
670 }
671 return $output;
672 }
673
674 function guaven_sqlcharts_local_shortcode($atts) {
675 if(empty($atts['id']))return 'ID is missing.';
676 $atts['id']=intval($atts['id']);
677 $remote_host=get_post_meta($atts['id'], 'guaven_sqlcharts_dbhost', true);
678 if ($remote_host!=''){
679 $remote_db=get_post_meta($atts['id'], 'guaven_sqlcharts_dbname', true);
680 $remote_login=get_post_meta($atts['id'], 'guaven_sqlcharts_dblogin', true);
681 $remote_pass=get_post_meta($atts['id'], 'guaven_sqlcharts_dbpass', true);
682 if(is_array($remote_pass)){
683 $remote_pass=guaven_sqlcharts_encrypt_decrypt('decrypt',$remote_pass[1]);
684 }
685 $wpdb=new wpdb($remote_login,$remote_pass,$remote_db,$remote_host);
686 }
687 else {
688 global $wpdb;
689 }
690
691 $GLOBALS["guaven_sqlcharts_atts"]=$atts;
692
693 $sql = guaven_sqlcharts_get_code($atts['id']);
694 if(empty($sql))return 'SQL query is missing.';
695 $sql=gvn_chart_put_variables($sql,$atts['id']);
696
697
698 $sql=apply_filters('guaven_sqlcharts_rendered_sql',$sql,$atts);
699
700 $blacklister_f = gvn_chart_check_sql_query($sql);
701 if ($blacklister_f == 1)return 'You given SQL code contains forbidden commands. Remember that you should only use SELECT queries';
702 $tip_g = guaven_sqlcharts_normalize_type(get_post_meta($atts['id'], 'guaven_sqlcharts_graphtype', true));
703
704 for($i=1;$i<20;$i++){
705 if(strpos($sql,"{arg".$i."}")!==false){
706 $replacearg=!empty($atts["arg".$i])?$atts["arg".$i]:0;
707 $sql = str_replace("{arg".$i."}", "%s", $sql);
708 $sql=$wpdb->prepare($sql,$replacearg);
709 }
710
711 }
712
713 $sql_split = explode(';', $sql);
714 $labels_and_values = array();
715 $post_g = get_post($atts['id']);
716
717 global $sqlcharts_inserted_script;
718 ob_start();
719 for ($i = 0; $i < count($sql_split); $i++) {
720 if (!empty($sql_split[$i])) {
721
722 $fvs = $wpdb->get_results($sql_split[$i]);
723 if (strpos($_SERVER["REQUEST_URI"],'wp-admin')!==false){
724 $wpdb->show_errors();
725 ob_start();
726 $wpdb->print_error();
727 $printerror = ob_get_clean();
728 if ($printerror != '' and strpos($printerror, "[]") === false){
729 ob_end_clean();
730 return $printerror;
731 }
732 elseif (empty($fvs)){
733 ob_end_clean();
734 return 'Your SQL returnes empty data, please recheck your SQL query above';
735 }
736 }
737
738 if (empty($sqlcharts_inserted_script))
739 $sqlcharts_inserted_script = 1;
740 $labels_and_values[$i] = guaven_get_labels_and_values($atts['id'], $fvs);
741 $labels[$i] = $labels_and_values[$i][0];
742 $values[$i] = $labels_and_values[$i][1];
743 $ylabel[$i] = !empty($labels_and_values[$i][2][$i]) ? $labels_and_values[$i][2][$i] : '';
744 $xlabel[$i] = !empty($labels_and_values[$i][3][$i]) ? $labels_and_values[$i][3][$i] : '';
745 }
746 }
747
748 gvn_chart_top_form($atts);
749
750 // shortcode width/height attributes override the saved defaults
751 $chart_w = !empty($atts['width']) ? $atts['width'] : get_post_meta($atts['id'], 'guaven_sqlcharts_chartwidth', true);
752 $chart_h = !empty($atts['height']) ? $atts['height'] : get_post_meta($atts['id'], 'guaven_sqlcharts_chartheight', true);
753 $wrap_style = '';
754 if ($chart_w != '') $wrap_style .= 'max-width:' . (int) $chart_w . 'px;';
755 if ($chart_h != '') $wrap_style .= 'height:' . (int) $chart_h . 'px;';
756 ?>
757 <div class="gvn-chartwrap"<?php echo $wrap_style != '' ? ' style="' . esc_attr($wrap_style) . '"' : ''; ?>>
758 <canvas
759 id="ct-chart_<?php echo esc_attr($sqlcharts_inserted_script); ?>"
760 class="guaven_chart_canvas"
761 ></canvas>
762 </div>
763
764 <script type="text/javascript" class="gvn_charts_script" async>
765 var ctx = jQuery("#ct-chart_<?php
766 echo esc_attr($sqlcharts_inserted_script);
767 ?>");
768
769 <?php
770 $print_data=apply_filters('guaven_sqlcharts_pre_print_vars',['tip_g'=>$tip_g, 'title'=>$post_g->post_title,
771 'labels'=>$labels, 'values'=>$values, 'ylabel'=>$ylabel, 'pid'=>$atts['id']]);
772 guaven_sqlcharts_print_chart_js($print_data);
773 ?>
774 </script>
775
776 <?php
777 if (!empty($atts["table"])) guaven_sqlcharts_tablepart($post_g->post_title, $labels, $values, $ylabel,$xlabel);
778 $sqlcharts_inserted_script++;
779 $ret=ob_get_clean();
780 $ret=apply_filters( 'guaven_sqlcharts_final_output', $ret, $atts );
781 return $ret;
782 }
783
784 add_shortcode('gvn_schart_2', 'guaven_sqlcharts_local_shortcode');
785
786 // legacy alias: old Google-Chart era posts produced [gvn_schart id=".."] shortcodes
787 if (!shortcode_exists('gvn_schart')) {
788 add_shortcode('gvn_schart', 'guaven_sqlcharts_local_shortcode');
789 }
790
791 add_shortcode("gvn_schart_2_cached",function($atts){
792 if(empty($atts["id"]))return;
793 $atts["id"]=intval($atts["id"]);
794 $is_logged_in=is_user_logged_in()?'':'_guest';
795 $expire=!empty($atts["expire"])?intval($atts["expire"]):3600;
796 $cached=get_transient('cached_sql_charts_'.$atts["id"].$is_logged_in);
797 if(!empty($cached) and !isset($_GET["force_sql_cache_reload"]) )return $cached;
798 $tobecached=do_shortcode('[gvn_schart_2 id="'.$atts["id"].'"]');
799 set_transient('cached_sql_charts_'.$atts["id"].$is_logged_in, $tobecached,$expire);//you can change 3600 yourself
800 return $tobecached;
801 });
802
803 // fixed, colorblind-friendly default palette (Tableau 10) used when no custom colors are set
804 function guaven_sqlcharts_default_palette(){
805 return apply_filters('guaven_sqlcharts_default_palette', array(
806 '#4E79A7', '#F28E2B', '#E15759', '#76B7B2', '#59A14F',
807 '#EDC948', '#B07AA1', '#FF9DA7', '#9C755F', '#BAB0AC'
808 ));
809 }
810
811 function guaven_sqlcharts_colors($index, $pid = null){
812 if(!isset($pid)) {
813 global $post;
814 $pid = $post->ID;
815 }
816 $colors=get_post_meta($pid,'guaven_sqlcharts_colors',true);
817 $colors=explode(",",$colors);
818 if (!empty($colors[$index])) return $colors[$index];
819 $palette = guaven_sqlcharts_default_palette();
820 return $palette[$index % count($palette)];
821 }
822
823 // outputs 'maintainAspectRatio:false,' when an explicit height is set, so the
824 // chart fills its sized wrapper instead of keeping the default aspect ratio
825 function guaven_sqlcharts_mar($pid){
826 $atts = isset($GLOBALS["guaven_sqlcharts_atts"]) ? $GLOBALS["guaven_sqlcharts_atts"] : array();
827 $h = !empty($atts['height']) ? $atts['height'] : get_post_meta($pid, 'guaven_sqlcharts_chartheight', true);
828 return $h != '' ? 'maintainAspectRatio: false,' : '';
829 }
830
831 function guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, $type = 'bar', $pid = null)
832 {
833 $horizontal = ($type == 'horizontalBar');
834 $forcestack = ($type == 'stackedBar');
835 $stacked = ($forcestack or get_post_meta($pid, 'guaven_sqlcharts_nostacked', true) != 1) ? 'true' : 'false';
836 ?>
837 var data = {
838 labels: [<?php guaven_sqlcharts_merge_labeldata($labels);?>],
839 datasets: [
840 <?php
841 $values_new=guaven_sqlcharts_key_normalizer($values,$labels,$ylabel)[0];
842 $i=-1;
843 foreach ($values_new as $key_ak=>$value_ak) {
844 $i++;
845 ?>
846 {
847 <?php
848 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
849 //passing chartJS params via the shortcode
850 echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
851 }
852 ?>
853 label: "<?php
854 echo wp_kses($ylabel[$key_ak],[]);
855 ?>",
856 backgroundColor: [
857 <?php
858 echo wp_kses(guaven_sqlcharts_colorgenerator(count($values_new[$key_ak]), 0, 0, guaven_sqlcharts_colors($i, $pid)),[]);
859 ?>
860 ],
861 borderColor: [
862 <?php
863 echo wp_kses(guaven_sqlcharts_colorgenerator(count($values_new[$key_ak]), 0, 0.2, guaven_sqlcharts_colors($i, $pid)),[]);
864 ?>
865 ],
866 borderWidth: 1,
867 data: [<?php
868 echo wp_kses(implode(",", $values_new[$key_ak]),[]);
869 ?>],
870 },
871 <?php
872 }
873 ?>
874 ]
875 };
876 var options={
877 responsive: true,
878 <?php echo wp_kses(guaven_sqlcharts_mar($pid),[]); ?>
879 <?php if ($horizontal) echo "indexAxis: 'y',"; ?>
880 scales: {
881 x: {
882 stacked: <?php echo esc_js($stacked); ?>,
883 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
884 },
885 y: {
886 stacked: <?php echo esc_js($stacked); ?>,
887 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>,
888 ticks: {
889 <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
890 }
891 }
892 }
893 <?php
894 guaven_sqlcharts_maybe_additional_parameters($pid);
895 ?>
896 };
897 var myBarChart = new Chart(ctx, {
898 type: 'bar',
899 data: data,
900 options: options
901 });
902 <?php
903 }
904
905 function guaven_sqlcharts_merge_labeldata($labels){
906 if(count($labels)==1){echo wp_kses(implode(",",$labels[0]),[]);return;}
907 $merged=[];
908 foreach($labels as $label){
909 $merged=array_merge($merged,$label);
910 }
911 echo wp_kses(implode(",",array_unique($merged)),[]);
912 }
913
914 function guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, $type = 'false', $pid = null, $charttype = 'line', $stepped = false)
915 {
916 ?>
917 var data = {
918 labels: [<?php guaven_sqlcharts_merge_labeldata($labels);?>],
919 datasets: [
920 <?php
921 $values_new=guaven_sqlcharts_key_normalizer($values,$labels,$ylabel)[0];
922 $dataset_count=count($values_new);
923 $i=-1;
924 foreach ($values_new as $key_ak=>$value_ak) {
925 $i++;
926 if ($type == 'radarfill') $fill = "'origin'";
927 elseif ($type == 'false') $fill = 'false';
928 else $fill = ($i == 0 and $dataset_count > 1) ? '"+1"' : '"origin"';
929 ?>
930 {
931 <?php
932 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
933 //passing chartJS params via the shortcode
934 echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
935 }
936 ?>
937 label: "<?php
938 echo esc_attr($ylabel[$key_ak]);
939 ?>",
940 fill: <?php echo wp_kses($fill,[]);
941 ?>,
942 tension: 0.1,
943 <?php if ($stepped) echo 'stepped: true,'; ?>
944 backgroundColor: <?php
945 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
946 ?>
947 borderColor: <?php
948 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
949 ?>
950 pointBorderColor: <?php
951 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
952 ?>
953 pointHoverBackgroundColor: <?php
954 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
955 ?>
956 pointHoverBorderColor: <?php
957 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
958 ?>
959 data: [<?php
960 echo wp_kses_post(implode(",", $values_new[$key_ak]));
961 ?>],
962 spanGaps: false,
963 },
964 <?php
965 }
966 ?>
967 ]
968 };
969 var myLineChart = new Chart(ctx, {
970 type: '<?php echo esc_attr($charttype); ?>',
971 data: data,
972 options: {
973 responsive: true,
974 <?php echo wp_kses(guaven_sqlcharts_mar($pid),[]); ?>
975 <?php if ($charttype == 'radar') { ?>
976 scales: {
977 r: {
978 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>
979 }
980 }
981 <?php } else { ?>
982 scales: {
983 x: {
984 display: true,
985 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
986 },
987 y: {
988 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>,
989 ticks: {
990 <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
991 }
992 }
993 }
994 <?php } ?>
995 <?php
996 guaven_sqlcharts_maybe_additional_parameters($pid);
997 ?>
998
999 }
1000 });
1001 <?php
1002 }
1003
1004 function guaven_sqlcharts_scatterdata($title, $labels, $values, $ylabel, $pid = null)
1005 {
1006 ?>
1007 var data = {
1008 datasets: [
1009 <?php
1010 $i=-1;
1011 foreach ($values as $key_ak=>$value_ak) {
1012 $i++;
1013 $points=array();
1014 foreach ($value_ak as $xval=>$yval) {
1015 $x = is_numeric($xval) ? $xval : '"'.esc_js($xval).'"';
1016 $y = is_numeric($yval) ? $yval : '"'.esc_js($yval).'"';
1017 $points[] = '{x:'.$x.',y:'.$y.'}';
1018 }
1019 ?>
1020 {
1021 <?php
1022 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
1023 //passing chartJS params via the shortcode
1024 echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
1025 }
1026 ?>
1027 label: "<?php echo esc_attr(isset($ylabel[$key_ak])?$ylabel[$key_ak]:''); ?>",
1028 backgroundColor: <?php
1029 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
1030 ?>
1031 borderColor: <?php
1032 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
1033 ?>
1034 data: [<?php echo wp_kses(implode(",", $points),[]); ?>],
1035 },
1036 <?php
1037 }
1038 ?>
1039 ]
1040 };
1041 var myScatterChart = new Chart(ctx, {
1042 type: 'scatter',
1043 data: data,
1044 options: {
1045 responsive: true,
1046 <?php echo wp_kses(guaven_sqlcharts_mar($pid),[]); ?>
1047 scales: {
1048 x: {
1049 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
1050 },
1051 y: {
1052 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>,
1053 ticks: {
1054 <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
1055 }
1056 }
1057 }
1058 <?php
1059 guaven_sqlcharts_maybe_additional_parameters($pid);
1060 ?>
1061 }
1062 });
1063 <?php
1064 }
1065
1066
1067 function guaven_sqlcharts_maybe_additional_parameters($pid){
1068 if(function_exists('guaven_sqlcharts_maybe_additional_parameters_custom')){
1069 wp_kses(guaven_sqlcharts_maybe_additional_parameters_custom($pid),[]);
1070 return;
1071 }
1072 $guaven_sqlcharts_legend_position=get_post_meta($pid, 'guaven_sqlcharts_legend_position', true);
1073 if(in_array($guaven_sqlcharts_legend_position,['top','bottom','left','right'])){
1074 $display='true';$position=$guaven_sqlcharts_legend_position;
1075 }
1076 else {
1077 $display='false';$position='top';
1078 }
1079 echo wp_kses( ",plugins: {legend: {display: ".$display.",position:'".$position."'}}",[]);
1080 }
1081
1082
1083
1084
1085 function guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, $type = 'pie')
1086 {
1087 ?>
1088 var options={
1089 <?php if(get_post_meta($pid,'guaven_sqlcharts_forcetooltips',true)!='') echo 'showAllTooltips: true,'.PHP_EOL; ?>
1090 responsive: true
1091 <?php echo get_post_meta($pid,'guaven_sqlcharts_chartheight',true)!=''||!empty($GLOBALS["guaven_sqlcharts_atts"]['height'])?',maintainAspectRatio: false':''; ?>
1092 <?php
1093 guaven_sqlcharts_maybe_additional_parameters($pid);
1094 ?>
1095 };
1096 var data = {
1097 labels: [ <?php guaven_sqlcharts_merge_labeldata($labels);?>],
1098 datasets: [
1099 <?php
1100 for ($i = 0; $i < count($values); $i++) {
1101 ?>
1102 {
1103 <?php
1104 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
1105 //passing chartJS params via the shortcode
1106 echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
1107 }
1108 ?>
1109 data: [<?php
1110 echo wp_kses(implode(",", $values[$i]),[]);
1111 ?>],
1112 backgroundColor: [
1113 <?php
1114 $ii=0;
1115 foreach($values[$i] as $vci=>$valuecolor){
1116 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 0, -0.1, guaven_sqlcharts_colors($ii, $pid)));
1117 $ii++;
1118 }
1119 ?>
1120 ],
1121 hoverBackgroundColor: [
1122 <?php
1123 $ii=0;
1124 foreach($values[$i] as $vci=>$valuecolor){
1125 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 0, 0.2, guaven_sqlcharts_colors($ii, $pid)));
1126 $ii++;
1127 }
1128 ?>
1129 ]
1130 },
1131 <?php
1132 }
1133 ?>
1134 ]
1135 };
1136 var myPieChart = new Chart(ctx,{
1137 type: '<?php
1138 echo esc_attr($type);
1139 ?>',
1140 data: data,
1141 options: options
1142 });
1143 <?php
1144 }
1145
1146
1147
1148
1149 function guaven_sqlcharts_colorgenerator($count, $indic, $darkness = 0, $initcolor = '255,0,0')
1150 {
1151 if (strpos($initcolor,'#')===0) {
1152 $split = str_split(substr($initcolor,1), 2);
1153 $r = hexdec($split[0]);
1154 $g = hexdec($split[1]);
1155 $b = hexdec($split[2]);
1156 $ret='';
1157 for ($i = 0; $i < $count; $i++) {
1158 $ret .= "'rgba(" . $r . ", " . $g . ", " . $b . ",".($darkness + 0.8 - $indic * $i * 0.8 / ($count)).")',
1159 ";
1160 }
1161 return $ret;
1162 }
1163 $initial_colors = array(
1164 'linebg' => 'red',
1165 'linebr' => 'yellow',
1166 'linebc' => 'green',
1167 'linehbg' => 'white',
1168 'linehbc' => 'black'
1169 );
1170 if (!empty($initial_colors[$count]))
1171 return '"' . $initial_colors[$count] . '",
1172 ';
1173 $ret = '';
1174 for ($i = 0; $i < $count; $i++) {
1175 $ret .= "'rgba(" . $initcolor . "," . ($darkness + 0.8 - $indic * $i * 0.8 / ($count)) . ")',
1176 ";
1177 }
1178 return $ret;
1179 }
1180
1181 function guaven_sqlcharts_tablepart($title, $labels, $values, $ylabel,$xlabel){
1182 $tabledata='';
1183 $fcol=[];$scol=[];
1184 $empty_cell=apply_filters( 'guaven_sqlcharts_table_empty_cell','<td></td>');
1185 $tablein='';
1186 foreach($values as $row=>$valuerow){
1187 foreach ($valuerow as $key => $value) {
1188 $putval=$labels[$row][$key]??'';
1189 $fcol[$key]='<td>'.str_replace('"',"",$putval).'</td>';
1190 $scol[$key][$row]='<td>'.$value.'</td>';
1191 }
1192 foreach($scol as $scolkey=>$scolvalue){
1193 for($i=0;$i<count($values);$i++){
1194 //echo $i;
1195 if(!isset($scolvalue[$i]))$scol[$scolkey][$i]=$empty_cell;;
1196 }
1197 ksort($scol[$scolkey]);
1198 }
1199 }
1200
1201 foreach($fcol as $key=>$value){
1202 $tablein.='<tr>'.$value.implode(" ",$scol[$key]).'</tr>'.PHP_EOL;
1203 }
1204 $tabledata.='<div class="gvn-tablewrap"><table class="gvn-table"><tr><th>'.$xlabel[0].'</th><th>'.implode("</th><th>",$ylabel).'</th></tr>
1205 '.$tablein.'</table></div><br>';
1206
1207 echo wp_kses_post($tabledata);
1208
1209 }
1210
1211 function guaven_sqlcharts_graphtype($post){
1212 if (strpos(get_post_meta($post->ID, 'guaven_sqlcharts_graphtype', true), "_l") !== false)
1213 $postfix = '_2';
1214 else $postfix = '';
1215 return $postfix;
1216 }
1217
1218 add_filter('the_content',function($content){
1219 if(!is_singular('gvn_schart'))return $content;
1220 global $post;
1221 $postfix=guaven_sqlcharts_graphtype($post);
1222 return '[gvn_schart'.$postfix.' id="'.$post->ID.'"'.
1223 (get_post_meta($post->ID,'guaven_sqlcharts_tablepart',true)!=''?' table="1"':'')
1224 .']';
1225 });
1226
1227 function guaven_sqlcharts_key_normalizer($values,$labels,$ylabel){
1228 $normalize_keys=[];
1229 $empty_value=apply_filters( 'guaven_sqlcharts_table_empty_value','');
1230 foreach ($values as $key_ak=>$value_ak) {
1231 $normalize_keys=array_merge($normalize_keys,array_keys($values[$key_ak]));
1232 }
1233 $values_normalized=[];$labels_normalized=[];$ylabel_normalized=[];
1234 foreach($normalize_keys as $normalized_key){
1235 foreach ($values as $key_ak=>$value_ak) {
1236 $values_normalized[$key_ak][$normalized_key]=isset( $values[$key_ak][$normalized_key])? $values[$key_ak][$normalized_key]:"'".$empty_value."'";
1237 $labels_normalized[$key_ak][$normalized_key]=isset( $labels[$key_ak][$normalized_key])? $labels[$key_ak][$normalized_key]:"''";
1238 $ylabel_normalized[$key_ak][$normalized_key]=isset( $ylabel[$key_ak][$normalized_key])? $ylabel[$key_ak][$normalized_key]:"";
1239 }
1240 }
1241 return [$values_normalized,$labels_normalized,$ylabel_normalized];
1242 }
1243
1244
1245 add_filter('guaven_sqlcharts_table_empty_cell',function($str){return '<td>#</td>';});
1246 add_filter('guaven_sqlcharts_table_empty_value',function($str){return 'N/A';});
1247