PluginProbe
SQL Chart Builder / 2.3.7.1
SQL Chart Builder v2.3.7.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 2.3.7.1, at functions.php

946 lines 34.1 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. Choose chart type, type SQL query, enter field names, labels, and then press Publish/Update.<br>
79 3. After update, you will see the name and the demo of the needed shortcode at the bottom of this admin 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/bundle.min.js', __FILE__),array('jquery'),GVNSQLCHARTS_VERSION,false);
127 wp_localize_script('guaven_sqlcharts_chartjs', 'guaven_sqlcharts_notice_dismissed', array(
128 'action' => 'guaven_sqlcharts_onboarding_notice_dismissed',
129 'nonce' => wp_create_nonce('notice_dismissed')
130 ));
131
132 }
133 add_action('wp_enqueue_scripts', 'guaven_sqlcharts_enqueue_chart');
134 add_action('admin_enqueue_scripts', 'guaven_sqlcharts_enqueue_chart');
135
136 function guaven_sqlcharts_enqueue_main_style()
137 {
138 wp_enqueue_style('guaven_sqlcharts_main_style', plugins_url('asset/guaven_sqlcharts.css', __FILE__),array(),GVNSQLCHARTS_VERSION);
139 }
140 add_action('wp_enqueue_scripts', 'guaven_sqlcharts_enqueue_main_style');
141 add_action('admin_enqueue_scripts', 'guaven_sqlcharts_enqueue_main_style');
142
143
144 function guaven_sqlcharts_isJson($string)
145 {
146 json_decode($string);
147 return (json_last_error() == JSON_ERROR_NONE);
148 }
149
150 add_action('init', 'guaven_sqlcharts_register_post');
151 function guaven_sqlcharts_register_post()
152 {
153 //register_taxonomy('guaven_update_push_tag', 'termin');
154 register_post_type('gvn_schart', array(
155 'labels' => array(
156 'name' => __('My SQL Charts','guaven_sqlcharts'),
157 'singular_name' => __('My SQL chart','guaven_sqlcharts')
158 ),
159
160 'public' => true,
161 //'taxonomies' => array('guaven_update_push_tag'),
162 'supports' => array(
163 'title',
164 'postmeta'
165 ),
166 'register_meta_box_cb' => 'guaven_sqlcharts_metabox_area'
167 ));
168
169 guaven_sqlcharts_load_defaults();
170 }
171
172 add_action('admin_footer', 'guaven_sqlcharts_admin_front');
173
174
175 function guaven_sqlcharts_admin_front()
176 {
177 global $post;
178 if (!empty($post) and $post->post_type == 'gvn_schart') {
179 ?>
180 <style type="text/css">#normal-sortables{display: none}</style>
181 <?php
182 }
183 }
184
185 // metabox for editor
186 function guaven_sqlcharts_metabox_area()
187 {
188 add_meta_box('guaven_sqlcharts_metabox', 'Configure your graph chart', 'guaven_sqlcharts_metabox', 'gvn_schart', 'advanced', 'default');
189 }
190
191 function guaven_sqlcharts_metabox()
192 {
193 require_once(dirname(__FILE__) . "/admin_metabox.php");
194 }
195
196 function guaven_gutenberg_wrapper($atts){
197 if(isset($atts['sqlcharts_inserted_script'])){
198 global $sqlcharts_inserted_script;
199 $sqlcharts_inserted_script = $atts['sqlcharts_inserted_script'];
200 }
201
202 // if( isset($_GET["post_id"],$_GET["context"]) and $_GET["context"]=='edit'
203 // and strpos($_SERVER["REQUEST_URI"],'block-renderer/guaven-sqlcharts/gvn-chart-gutenberg')!==false
204 // ){
205 // $atts['chart_id']=$_GET["post_id"];
206 // }
207 $post = get_post($atts['chart_id']);
208 if( ! isset($atts['chart_id']) or !isset($post) or $post->post_type != 'gvn_schart'){
209
210 return "Invalid id";
211 }
212
213 return guaven_sqlcharts_local_shortcode(array('id' => $atts['chart_id'])); // temporary explicit value
214 }
215 function guaven_register_gutenberg_blocks()
216 {
217 wp_register_script(
218 'gvn_gutenberg_charts',
219 plugins_url( 'asset/guaven_gutenberg_charts.js', __FILE__ ),
220 array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-server-side-render' ),
221 GVNSQLCHARTS_VERSION.'_'.filemtime( plugin_dir_path( __FILE__ ) . 'asset/guaven_gutenberg_charts.js'),
222 false
223 );
224 wp_localize_script('gvn_gutenberg_charts', 'guaven', array(
225 'description' => 'Add My SQL Chart to your post',
226 ));
227
228 register_block_type( 'guaven-sqlcharts/gvn-chart-gutenberg', array(
229 'editor_script' => 'gvn_gutenberg_charts',
230 'render_callback' => 'guaven_gutenberg_wrapper',
231 'attributes' => array(
232 'chart_id' => array(
233 'type' => 'string',
234 'default' => null
235 ),
236 'sqlcharts_inserted_script' => array(
237 'type' => 'number',
238 'default' => null
239 )
240 )
241 ));
242 }
243 add_action('init', 'guaven_register_gutenberg_blocks');
244
245
246
247 function guaven_sqlcharts_save_metabox_area($post_id, $post)
248 {
249 if (!isset($_POST['meta_box_nonce_field']) or !wp_verify_nonce($_POST['meta_box_nonce_field'], 'meta_box_nonce_action')) {
250 return $post->ID;
251 }
252 $fields = array(
253 "guaven_sqlcharts_chartheight",
254 "guaven_sqlcharts_chartwidth",
255 "guaven_sqlcharts_graphtype",
256 "guaven_sqlcharts_xarg_s",
257 "guaven_sqlcharts_xarg_l",
258 "guaven_sqlcharts_yarg_s",
259 "guaven_sqlcharts_yarg_l",
260 "guaven_sqlcharts_tablepart",
261 "guaven_sqlcharts_variables",
262 "guaven_sqlcharts_formpartrole",
263 "guaven_sqlcharts_formpartbutton",
264 "guaven_sqlcharts_dbhost",
265 "guaven_sqlcharts_dblogin",
266 "guaven_sqlcharts_dbname",
267 "guaven_sqlcharts_colors",
268 "guaven_sqlcharts_begin_with_0_x",
269 "guaven_sqlcharts_begin_with_0_y",
270 "guaven_sqlcharts_round_y_values",
271 "guaven_sqlcharts_legend_position",
272 "guaven_sqlcharts_nostacked",
273 "guaven_sqlcharts_forcetooltips"
274 );
275 foreach ($fields as $key => $value) {
276 if(isset($_POST[$value]))$newval=esc_attr($_POST[$value]);
277 else $newval='';
278
279 update_post_meta($post->ID, $value, $newval);
280 }
281 if(!empty($_POST["guaven_sqlcharts_dbpass"])){
282 $encpass=guaven_sqlcharts_encrypt_decrypt('encrypt',$_POST["guaven_sqlcharts_dbpass"]);
283 update_post_meta($post->ID, 'guaven_sqlcharts_dbpass', ['encrypted',$encpass]);
284 }
285 update_post_meta($post->ID, 'guaven_sqlcharts_code', esc_attr(str_replace("'",'"',stripslashes($_POST['guaven_sqlcharts_code']))) );
286 }
287 add_action('save_post', 'guaven_sqlcharts_save_metabox_area', 1, 2);
288 // save the custom fields
289
290
291
292 function gvn_chart_check_sql_query($sql)
293 {
294 $blacklister = array(
295 "delete",
296 "update",
297 "insert",
298 "drop",
299 "truncate",
300 "alter"
301 ); //add all
302 $blacklister_f = 0;
303 foreach ($blacklister as $key => $value) {
304 if (strpos($sql, $value) !== false)
305 $blacklister_f = 1;
306 }
307 return $blacklister_f;
308 }
309
310 function guaven_get_labels_and_values($id, $fvs)
311 {
312 $values = array();
313 $labels = array();
314 $xarg_s = get_post_meta($id, 'guaven_sqlcharts_xarg_s', true);
315 $xarg_l = get_post_meta($id, 'guaven_sqlcharts_xarg_l', true);
316 $yarg_s = get_post_meta($id, 'guaven_sqlcharts_yarg_s', true);
317 $yarg_l = get_post_meta($id, 'guaven_sqlcharts_yarg_l', true);
318 $chartype = array(
319 'line_l' => 'Line',
320 'pie_l' => 'Pie',
321 'donut_l' => 'Pie',
322 'bar_l' => 'Bar',
323 'horizontalbar_l' => 'Horizontal Bar',
324 'area_l' => 'Line'
325 );
326 foreach ($fvs as $key => $value) {
327 $values[$value->$xarg_s] = $value->$yarg_s;
328 $labels[$value->$xarg_s] = '"' . $value->$xarg_s . '"';
329 }
330 return array(
331 $labels,
332 $values,
333 explode(";", $yarg_l),
334 explode(";", $xarg_l)
335 );
336 }
337
338 function guaven_sqlcharts_print_chart_js($print_data)
339 {
340 extract($print_data);
341
342 if ($tip_g == 'line_l') {
343 guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'false', $pid);
344 }
345 if ($tip_g == 'area_l') {
346 guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'true', $pid);
347 } elseif ($tip_g == 'pie_l') {
348 guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid);
349 } elseif ($tip_g == 'donut_l') {
350 guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, 'doughnut');
351 } elseif ($tip_g == 'bar_l') {
352 guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, 'bar', $pid);
353 } elseif ($tip_g == 'horizontalbar_l') {
354 guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, 'horizontalBar', $pid);
355 }
356 elseif($tip_g == 'custom'){
357 guaven_sqlcharts_custom($title, $labels, $values, $ylabel, $pid);
358 }
359 elseif ($tip_g == 'polar_l') {
360 guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, 'polarArea');
361 }
362 }
363
364 function guaven_sqlcharts_custom($title, $labels, $values, $ylabel, $pid){
365 do_action('guaven_sqlcharts_custom',$title, $labels, $values, $ylabel, $pid);
366 }
367
368 function gvn_chart_put_variables($sql,$pid){
369 $sql_initial=$sql;
370
371
372 $default_tag_keys=['{current_user_id}','{current_user_login}','{current_user_email}','{current_user_display_name}'];
373 if(is_user_logged_in( )){
374 $currentuser=wp_get_current_user();
375 $default_tag_values=[$currentuser->ID,$currentuser->user_login,$currentuser->user_email,$currentuser->user_display_name];
376 }
377 else {
378 $default_tag_values='';
379 }
380 $sql_initial=str_replace($default_tag_keys,$default_tag_values,$sql_initial);
381
382 $variables_raw=get_post_meta($pid,'guaven_sqlcharts_variables',true);
383 $variables_arr=explode("|",$variables_raw);
384 foreach($variables_arr as $varfield){
385 $varfield_arr=explode("~",$varfield);
386 if (count($varfield_arr)<3) continue;
387 $varfield_arr=array_map("trim",$varfield_arr);
388 if (!empty($_GET[$varfield_arr[0]])) $varreplacement=$_GET[$varfield_arr[0]]; else $varreplacement=$varfield_arr[1];
389 if (!is_numeric($varreplacement) and strpos($varreplacement,'()')===false) $varreplacement='"'.$varreplacement.'"';
390
391 $sql_initial=str_replace('{'.$varfield_arr[0].'}',$varreplacement,$sql_initial);
392 }
393 return $sql_initial;
394 }
395
396 function gvn_chart_top_form($atts){
397 if (get_post_meta($atts["id"],'guaven_sqlcharts_formpartrole',true)!='' and !is_user_logged_in()) return;
398 $topform='';$dateexists=false;
399 $variables_raw=get_post_meta($atts['id'],'guaven_sqlcharts_variables',true);
400 $variables_raw=explode("|",$variables_raw);
401 foreach ($variables_raw as $vrow){
402 $vrow_arr=explode("~",$vrow);
403 $vrow_arr=array_map("trim",$vrow_arr);
404 if (empty($vrow_arr[3])) continue;
405 $gvalue=!empty($_GET[$vrow_arr[0]])?esc_attr(urldecode($_GET[$vrow_arr[0]])):'';
406 $dvalue=(strpos($vrow_arr[1],'()')===false)?esc_attr($vrow_arr[1]):'';
407 if ($vrow_arr[3]=='date') {
408 $dateexists=true;
409 $topform.= $vrow_arr[2].' <input autocomplete="off" style="max-width:210px" type="text"
410 value="'.$gvalue.'"
411 data-toggle="datepicker" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'">
412 ';}
413 else {
414 $topform.= $vrow_arr[2].' <input autocomplete="off" style="max-width:210px;'.($vrow_arr[3]=='number'?'width:100px;':'').'"
415 type="'.$vrow_arr[3].'"
416 value="'.$gvalue.'" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'">
417 ';
418 }
419 }
420 if (!empty($topform)) {
421 $allowed_html = array(
422 'form' => array(
423 'method' => array(),
424 'action' => array(),
425 'class' => array()
426 ),
427 'input' => array(
428 'type' => array(),
429 'value' => array(),
430 'name' => array(),
431 'class' => array()
432 ),
433 'script' => array(),
434 );
435
436 $submit_button_value = get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true) != ''
437 ? esc_attr(get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true))
438 : 'OK';
439
440 $topform = '<form method="get" action="" class="guaven_sqlcharts_form">' . $topform . '
441 <input type="submit" value="' . $submit_button_value . '"></form>';
442
443 if ($dateexists) {
444 $topform .= '<script>setTimeout(function(){jQuery(\'[data-toggle="datepicker"]\').datepicker({format: \'yyyy-mm-dd\'});},300);</script>';
445 }
446
447 echo wp_kses($topform, $allowed_html);
448 }
449 }
450
451
452 function guaven_sqlcharts_encrypt_decrypt($action, $string)
453 {
454 $output = false;
455 $encrypt_method = "AES-256-CBC";
456 $secret_key = 'GWSCHARTPL2022.2016.';
457 $secret_iv = 'GWSCHARTPL2016.2022';
458 $key = hash('sha256', $secret_key);
459 $iv = substr(hash('sha256', $secret_iv), 0, 16);
460 if ( $action == 'encrypt' ) {
461 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
462 $output = base64_encode($output);
463 } else if( $action == 'decrypt' ) {
464 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
465 }
466 return $output;
467 }
468
469 function guaven_sqlcharts_local_shortcode($atts) {
470 if(empty($atts['id']))return 'ID is missing.';
471 $remote_host=get_post_meta($atts['id'], 'guaven_sqlcharts_dbhost', true);
472 if ($remote_host!=''){
473 $remote_db=get_post_meta($atts['id'], 'guaven_sqlcharts_dbname', true);
474 $remote_login=get_post_meta($atts['id'], 'guaven_sqlcharts_dblogin', true);
475 $remote_pass=get_post_meta($atts['id'], 'guaven_sqlcharts_dbpass', true);
476 if(is_array($remote_pass)){
477 $remote_pass=guaven_sqlcharts_encrypt_decrypt('decrypt',$remote_pass[1]);
478 }
479 $wpdb=new wpdb($remote_login,$remote_pass,$remote_db,$remote_host);
480 }
481 else {
482 global $wpdb;
483 }
484
485 $GLOBALS["guaven_sqlcharts_atts"]=$atts;
486
487 $sql = html_entity_decode(get_post_meta($atts['id'], 'guaven_sqlcharts_code', true));
488 if(empty($sql))return 'SQL query is missing.';
489 $sql=gvn_chart_put_variables($sql,$atts['id']);
490
491
492 $sql=apply_filters('guaven_sqlcharts_rendered_sql',$sql,$atts);
493
494 $blacklister_f = gvn_chart_check_sql_query($sql);
495 if ($blacklister_f == 1)return 'You given SQL code contains forbidden commands. Remember that you should only use SELECT queries';
496 $tip_g = get_post_meta($atts['id'], 'guaven_sqlcharts_graphtype', true);
497
498 for($i=1;$i<20;$i++){
499 if(strpos($sql,"{arg".$i."}")!==false){
500 $replacearg=!empty($atts["arg".$i])?$atts["arg".$i]:0;
501 $sql = str_replace("{arg".$i."}", "%s", $sql);
502 $sql=$wpdb->prepare($sql,$replacearg);
503 }
504
505 }
506
507 $sql_split = explode(';', $sql);
508 $labels_and_values = array();
509 $post_g = get_post($atts['id']);
510
511 global $sqlcharts_inserted_script;
512 for ($i = 0; $i < count($sql_split); $i++) {
513 if (!empty($sql_split[$i])) {
514
515 $fvs = $wpdb->get_results($sql_split[$i]);
516 if (strpos($_SERVER["REQUEST_URI"],'wp-admin')!==false){
517 $wpdb->show_errors();
518 ob_start();
519 $wpdb->print_error();
520 $printerror = ob_get_clean();
521 if ($printerror != '' and strpos($printerror, "[]") === false)
522 return $printerror;
523 elseif (empty($fvs))
524 return 'Your SQL returnes empty data, please recheck your SQL query above';
525 }
526
527 ob_start();
528
529 if (empty($sqlcharts_inserted_script))
530 $sqlcharts_inserted_script = 1;
531 $labels_and_values[$i] = guaven_get_labels_and_values($atts['id'], $fvs);
532 $labels[$i] = $labels_and_values[$i][0];
533 $values[$i] = $labels_and_values[$i][1];
534 $ylabel[$i] = !empty($labels_and_values[$i][2][$i]) ? $labels_and_values[$i][2][$i] : '';
535 $xlabel[$i] = !empty($labels_and_values[$i][3][$i]) ? $labels_and_values[$i][3][$i] : '';
536 }
537 }
538
539 gvn_chart_top_form($atts);
540 ?>
541 <canvas
542 id="ct-chart_<?php echo esc_attr($sqlcharts_inserted_script); ?>"
543 class="guaven_chart_canvas"
544 style="width: <?php echo esc_attr(get_post_meta($atts['id']), 'guaven_sqlcharts_chartwidth', true); ?>px !important; height: <?php echo esc_attr(get_post_meta($atts['id'], 'guaven_sqlcharts_chartheight', true)); ?>px !important;"
545 ></canvas>
546
547 <script type="text/javascript" class="gvn_charts_script" async>
548 var ctx = jQuery("#ct-chart_<?php
549 echo esc_attr($sqlcharts_inserted_script);
550 ?>");
551
552 <?php
553 $print_data=apply_filters('guaven_sqlcharts_pre_print_vars',['tip_g'=>$tip_g, 'title'=>$post_g->post_title,
554 'labels'=>$labels, 'values'=>$values, 'ylabel'=>$ylabel, 'pid'=>$atts['id']]);
555 guaven_sqlcharts_print_chart_js($print_data);
556 ?>
557 </script>
558
559 <?php
560 if (!empty($atts["table"])) guaven_sqlcharts_tablepart($post_g->post_title, $labels, $values, $ylabel,$xlabel);
561 $sqlcharts_inserted_script++;
562 $ret=ob_get_clean();
563 $ret=apply_filters( 'guaven_sqlcharts_final_output', $ret, $atts );
564 return $ret;
565 }
566
567 add_shortcode('gvn_schart_2', 'guaven_sqlcharts_local_shortcode');
568
569 add_shortcode("gvn_schart_2_cached",function($atts){
570 if(empty($atts["id"]))return;
571 $is_logged_in=is_user_logged_in()?'':'_guest';
572 $expire=!empty($atts["expire"])?intval($atts["expire"]):3600;
573 $cached=get_transient('cached_sql_charts_'.$atts["id"].$is_logged_in);
574 if(!empty($cached) and !isset($_GET["force_sql_cache_reload"]) )return $cached;
575 $tobecached=do_shortcode('[gvn_schart_2 id="'.$atts["id"].'"]');
576 set_transient('cached_sql_charts_'.$atts["id"].$is_logged_in, $tobecached,$expire);//you can change 3600 yourself
577 return $tobecached;
578 });
579
580 function guaven_sqlcharts_colors($index, $pid = null){
581 if(!isset($pid)) {
582 global $post;
583 $pid = $post->ID;
584 }
585 $colors=get_post_meta($pid,'guaven_sqlcharts_colors',true);
586 $colors=explode(",",$colors);
587 if (!empty($colors[$index])) return $colors[$index];
588 return wp_rand(0, 255) . ',' . wp_rand(0, 255) . ',' . wp_rand(0, 255);
589 }
590
591 /* TBD
592 function guaven_sqlcharts_toshowlegend($pid){
593 $guaven_sqlcharts_legend_position=get_post_meta($pid, 'guaven_sqlcharts_legend_position', true);
594 if(in_array($guaven_sqlcharts_legend_position,['top','bottom','left','right'])){
595 $display='true';$position=$guaven_sqlcharts_legend_position;
596 }
597 else {
598 $display='false';$position='top';
599 }
600 return "legend: {display: ".$display.",position:'".$position."'},";
601 }
602 */
603
604 function guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, $type = 'bar', $pid = null)
605 {
606 ?>
607 var data = {
608 labels: [<?php guaven_sqlcharts_merge_labeldata($labels);?>],
609 datasets: [
610 <?php
611 $values_new=guaven_sqlcharts_key_normalizer($values,$labels,$ylabel)[0];
612 $i=-1;
613 foreach ($values_new as $key_ak=>$value_ak) {
614 $i++;
615 ?>
616 {
617 <?php
618 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
619 //passing chartJS params via the shortcode
620 echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
621 }
622 ?>
623 label: "<?php
624 echo wp_kses($ylabel[$key_ak],[]);
625 ?>",
626 backgroundColor: [
627 <?php
628 echo wp_kses(guaven_sqlcharts_colorgenerator(count($values_new[$key_ak]), 0, 0, guaven_sqlcharts_colors($i, $pid)),[]);
629 ?>
630 ],
631 borderColor: [
632 <?php
633 echo wp_kses(guaven_sqlcharts_colorgenerator(count($values_new[$key_ak]), 0, 0.2, guaven_sqlcharts_colors($i, $pid)),[]);
634 ?>
635 ],
636 borderWidth: 1,
637 data: [<?php
638 echo wp_kses(implode(",", $values_new[$key_ak]),[]);
639 ?>],
640 },
641 <?php
642 }
643 ?>
644 ]
645 };
646 var options={
647 responsive: true,
648 scales: {
649 xAxes: [{
650 <?php echo (get_post_meta($pid, 'guaven_sqlcharts_nostacked', true) == 1) ? '':'stacked: true,';?>
651 ticks: {
652 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
653 }
654 }],
655 yAxes: [{
656 <?php echo (get_post_meta($pid, 'guaven_sqlcharts_nostacked', true) == 1) ? '':'stacked: true,';?>
657 ticks: {
658 <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
659 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>
660 }
661 }]
662 }
663 <?php
664 guaven_sqlcharts_maybe_additional_parameters($pid);
665 ?>
666 };
667 var myBarChart = new Chart(ctx, {
668 type: '<?php
669 echo esc_attr($type);
670 ?>',
671 data: data,
672 options: options
673 });
674 <?php
675 }
676
677 function guaven_sqlcharts_merge_labeldata($labels){
678 if(count($labels)==1){echo wp_kses(implode(",",$labels[0]),[]);return;}
679 $merged=[];
680 foreach($labels as $label){
681 $merged=array_merge($merged,$label);
682 }
683 echo wp_kses(implode(",",array_unique($merged)),[]);
684 }
685
686 function guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, $type = 'false', $pid = null)
687 {
688 ?>
689 var data = {
690 labels: [<?php guaven_sqlcharts_merge_labeldata($labels);?>],
691 datasets: [
692 <?php
693 $values_new=guaven_sqlcharts_key_normalizer($values,$labels,$ylabel)[0];
694 $i=-1;
695 foreach ($values_new as $key_ak=>$value_ak) {
696 $i++;
697 ?>
698 {
699 <?php
700 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
701 //passing chartJS params via the shortcode
702 echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
703 }
704 ?>
705 label: "<?php
706 echo esc_attr($ylabel[$key_ak]);
707 ?>",
708 fill: <?php echo $type=="false"? esc_attr($type):($i==0?'"+1"':'"origin"');
709 ?>,
710 lineTension: 0.1,
711 backgroundColor: <?php
712 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
713 ?>
714 borderColor: <?php
715 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
716 ?>
717 pointBorderColor: <?php
718 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
719 ?>
720 pointHoverBackgroundColor: <?php
721 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
722 ?>
723 pointHoverBorderColor: <?php
724 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid)));
725 ?>
726 data: [<?php
727 echo wp_kses_post(implode(",", $values_new[$key_ak]));
728 ?>],
729 spanGaps: false,
730 },
731 <?php
732 }
733 ?>
734 ]
735 };
736 var myLineChart = new Chart(ctx, {
737 type: 'line',
738 data: data,
739 options: {
740 responsive: true,
741 scales: {
742 xAxes: [{
743 display: true,
744 ticks: {
745 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
746 }
747 }],
748 yAxes: [{
749 ticks: {
750 <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
751 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>
752 }
753 }]
754 }
755 <?php
756 guaven_sqlcharts_maybe_additional_parameters($pid);
757 ?>
758
759 }
760 });
761 <?php
762 }
763
764
765 function guaven_sqlcharts_maybe_additional_parameters($pid){
766 if(function_exists('guaven_sqlcharts_maybe_additional_parameters_custom')){
767 wp_kses(guaven_sqlcharts_maybe_additional_parameters_custom($pid),[]);
768 return;
769 }
770 $guaven_sqlcharts_legend_position=get_post_meta($pid, 'guaven_sqlcharts_legend_position', true);
771 if(in_array($guaven_sqlcharts_legend_position,['top','bottom','left','right'])){
772 $display='true';$position=$guaven_sqlcharts_legend_position;
773 }
774 else {
775 $display='false';$position='top';
776 }
777 echo wp_kses( ",legend: {display: ".$display.",position:'".$position."'}",[]);
778 }
779
780
781
782
783 function guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, $type = 'pie')
784 {
785 if(get_post_meta($pid,'guaven_sqlcharts_forcetooltips',true)!=''){
786 echo 'guaven_sqlcharts_show_pie_labels();'.PHP_EOL;
787 }
788 ?>
789 var options={
790 showAllTooltips: true,
791 responsive: true
792 <?php
793 guaven_sqlcharts_maybe_additional_parameters($pid);
794 ?>
795 };
796 var data = {
797 labels: [ <?php guaven_sqlcharts_merge_labeldata($labels);?>],
798 datasets: [
799 <?php
800 for ($i = 0; $i < count($values); $i++) {
801 ?>
802 {
803 <?php
804 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
805 //passing chartJS params via the shortcode
806 echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]);
807 }
808 ?>
809 data: [<?php
810 echo wp_kses(implode(",", $values[$i]),[]);
811 ?>],
812 backgroundColor: [
813 <?php
814 $ii=0;
815 foreach($values[$i] as $vci=>$valuecolor){
816 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 0, -0.1, guaven_sqlcharts_colors($ii, $pid)));
817 $ii++;
818 }
819 ?>
820 ],
821 hoverBackgroundColor: [
822 <?php
823 $ii=0;
824 foreach($values[$i] as $vci=>$valuecolor){
825 echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 0, 0.2, guaven_sqlcharts_colors($ii, $pid)));
826 $ii++;
827 }
828 ?>
829 ]
830 },
831 <?php
832 }
833 ?>
834 ]
835 };
836 var myPieChart = new Chart(ctx,{
837 type: '<?php
838 echo esc_attr($type);
839 ?>',
840 data: data,
841 options: options
842 });
843 <?php
844 }
845
846
847
848
849 function guaven_sqlcharts_colorgenerator($count, $indic, $darkness = 0, $initcolor = '255,0,0')
850 {
851 if (strpos($initcolor,'#')===0) {
852 $split = str_split(substr($initcolor,1), 2);
853 $r = hexdec($split[0]);
854 $g = hexdec($split[1]);
855 $b = hexdec($split[2]);
856 $ret='';
857 for ($i = 0; $i < $count; $i++) {
858 $ret .= "'rgba(" . $r . ", " . $g . ", " . $b . ",".($darkness + 0.8 - $indic * $i * 0.8 / ($count)).")',
859 ";
860 }
861 return $ret;
862 }
863 $initial_colors = array(
864 'linebg' => 'red',
865 'linebr' => 'yellow',
866 'linebc' => 'green',
867 'linehbg' => 'white',
868 'linehbc' => 'black'
869 );
870 if (!empty($initial_colors[$count]))
871 return '"' . $initial_colors[$count] . '",
872 ';
873 $ret = '';
874 for ($i = 0; $i < $count; $i++) {
875 $ret .= "'rgba(" . $initcolor . "," . ($darkness + 0.8 - $indic * $i * 0.8 / ($count)) . ")',
876 ";
877 }
878 return $ret;
879 }
880
881 function guaven_sqlcharts_tablepart($title, $labels, $values, $ylabel,$xlabel){
882 $tabledata='';
883 $fcol=[];$scol=[];
884 $empty_cell=apply_filters( 'guaven_sqlcharts_table_empty_cell','<td></td>');
885 $tablein='';
886 foreach($values as $row=>$valuerow){
887 foreach ($valuerow as $key => $value) {
888 $putval=$labels[$row][$key]??'';
889 $fcol[$key]='<td>'.str_replace('"',"",$putval).'</td>';
890 $scol[$key][$row]='<td>'.$value.'</td>';
891 }
892 foreach($scol as $scolkey=>$scolvalue){
893 for($i=0;$i<count($values);$i++){
894 //echo $i;
895 if(!isset($scolvalue[$i]))$scol[$scolkey][$i]=$empty_cell;;
896 }
897 ksort($scol[$scolkey]);
898 }
899 }
900
901 foreach($fcol as $key=>$value){
902 $tablein.='<tr>'.$value.implode(" ",$scol[$key]).'</tr>'.PHP_EOL;
903 }
904 $tabledata.='<table><tr><th>'.$xlabel[0].'</th><th>'.implode("</th><th>",$ylabel).'</th></tr>
905 '.$tablein.'</table><br>';
906
907 echo wp_kses_post($tabledata);
908
909 }
910
911 function guaven_sqlcharts_graphtype($post){
912 if (strpos(get_post_meta($post->ID, 'guaven_sqlcharts_graphtype', true), "_l") !== false)
913 $postfix = '_2';
914 else $postfix = '';
915 return $postfix;
916 }
917
918 add_filter('the_content',function($content){
919 if(!is_singular('gvn_schart'))return $content;
920 global $post;
921 $postfix=guaven_sqlcharts_graphtype($post);
922 return '[gvn_schart'.$postfix.' id="'.$post->ID.'"'.
923 (get_post_meta($post->ID,'guaven_sqlcharts_tablepart',true)!=''?' table="1"':'')
924 .']';
925 });
926
927 function guaven_sqlcharts_key_normalizer($values,$labels,$ylabel){
928 $normalize_keys=[];
929 $empty_value=apply_filters( 'guaven_sqlcharts_table_empty_value','');
930 foreach ($values as $key_ak=>$value_ak) {
931 $normalize_keys=array_merge($normalize_keys,array_keys($values[$key_ak]));
932 }
933 $values_normalized=[];$labels_normalized=[];$ylabel_normalized=[];
934 foreach($normalize_keys as $normalized_key){
935 foreach ($values as $key_ak=>$value_ak) {
936 $values_normalized[$key_ak][$normalized_key]=isset( $values[$key_ak][$normalized_key])? $values[$key_ak][$normalized_key]:"'".$empty_value."'";
937 $labels_normalized[$key_ak][$normalized_key]=isset( $labels[$key_ak][$normalized_key])? $labels[$key_ak][$normalized_key]:"''";
938 $ylabel_normalized[$key_ak][$normalized_key]=isset( $ylabel[$key_ak][$normalized_key])? $ylabel[$key_ak][$normalized_key]:"";
939 }
940 }
941 return [$values_normalized,$labels_normalized,$ylabel_normalized];
942 }
943
944
945 add_filter('guaven_sqlcharts_table_empty_cell',function($str){return '<td>#</td>';});
946 add_filter('guaven_sqlcharts_table_empty_value',function($str){return 'N/A';});