PluginProbe
SQL Chart Builder / 3.0.0
SQL Chart Builder v3.0.0
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.0, at functions.php

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