PluginProbe
SQL Chart Builder / 2.3.3
SQL Chart Builder v2.3.3
3.0.4 3.0.3 3.0.2 3.0.1 trunk 1.0.2 1.0.3 2.2.2 2.3.0 2.3.1 2.3.2 2.3.3 2.3.4 2.3.5 2.3.6 2.3.7 2.3.7.1 2.3.7.2 2.3.8 3.0.0
sql-chart-builder / functions.php

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

824 lines 28.8 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 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">
39 <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>
40 </svg>
41 </a>
42 <img src="'.plugin_dir_url( __FILE__ ) . 'asset/img/recommended1.jpg" style="max-width: 430px;"></td></tr>
43 </tbody></table>';
44 }
45
46
47
48 function guaven_sqlcharts_my_admin_notice()
49 {
50 global $post;
51
52
53 if(
54 (!empty($_SERVER["REQUEST_URI"]) and strpos($_SERVER["REQUEST_URI"],'post_type=gvn_schart')!==false)
55 or
56 (!empty($post) and $post->post_type == 'gvn_schart')
57 ){
58 echo 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"]) and strpos($_SERVER["REQUEST_URI"], "post-new") === false):
71 $gf_message = 'Use <b>Add new</b> button above to create new sql report. And click on any existing rule names below
72 to manage them. ';
73 else:
74 $gf_message = '
75 1. Give any name to your report.<br>
76 2. Choose chart type, type sql query, enter field names, labels and then press to Publish/Update<br>
77 3. After update you will see needed shortcode below. You can use that shortcode anywhere in your website: in pages, posts, widgets etc. <br>
78 ';
79 endif;
80 _e('<div style="float:left">' . $gf_message . '</div>', 'guaven_sqlcharts');
81 echo '<div style="float: right;
82 margin-top: 0px;
83 padding-top: 0px;"><a target="_blank" style="text-align:center;border:0px solid #6200ee;border-radius:0px;color:white;font-weight:bold;background: #6200ee;"
84 class="button button-secondary" href="https://guaven.com/contact/solution-request/">Get Premium Support </a>
85 <span style="line-height: 30px;padding: 0 5px;">OR</span>
86 <a target="_blank" style="text-align:center;border:0px solid #26b286;border-radius:0px;color:white;font-weight:bold;background: #26b286;"
87 class="button button-secondary" href="https://guaven.com/service/small-thankyou-premium-support-service/">Make a Small Donation</a>
88 </div> </div>';
89 endif;
90 }
91 add_action('admin_notices', 'guaven_sqlcharts_my_admin_notice');
92
93 function guaven_sqlcharts_onboarding_notice(){
94 if((function_exists('wp_doing_ajax') and wp_doing_ajax()) or get_option('guaven_sqlcharts_onboarding_notice_dismissed') == 1)
95 return;
96
97 printf('
98 <div class="guaven-sqlcharts-notice notice notice-success is-dismissible" data-notice="onboarding_notice">
99 <p>Welcome aboard on MySQL Charts!</p>
100 </div>'
101 );
102 }
103 add_action('admin_notices', 'guaven_sqlcharts_onboarding_notice');
104
105 function guaven_sqlcharts_onboarding_notice_dismissed(){
106 check_ajax_referer('notice_dismissed', 'nonce');
107 switch ($_POST['type']){
108 case 'onboarding_notice':
109 update_option('guaven_sqlcharts_onboarding_notice_dismissed', 1);
110 break;
111 }
112 }
113 add_action('wp_ajax_guaven_sqlcharts_onboarding_notice_dismissed', 'guaven_sqlcharts_onboarding_notice_dismissed');
114
115 function guaven_sqlcharts_enqueue_chart()
116 {
117 wp_enqueue_script('guaven_sqlcharts_chartjs', plugins_url('asset/bundle.min.js', __FILE__),array('jquery'),GVNSQLCHARTS_VERSION);
118 wp_localize_script('guaven_sqlcharts_chartjs', 'guaven_sqlcharts_notice_dismissed', array(
119 'action' => 'guaven_sqlcharts_onboarding_notice_dismissed',
120 'nonce' => wp_create_nonce('notice_dismissed')
121 ));
122
123 }
124 add_action('wp_enqueue_scripts', 'guaven_sqlcharts_enqueue_chart');
125 add_action('admin_enqueue_scripts', 'guaven_sqlcharts_enqueue_chart');
126
127 function guaven_sqlcharts_enqueue_main_style()
128 {
129 wp_enqueue_style('guaven_sqlcharts_main_style', plugins_url('asset/guaven_sqlcharts.css', __FILE__),array(),GVNSQLCHARTS_VERSION);
130 }
131 add_action('admin_enqueue_scripts', 'guaven_sqlcharts_enqueue_main_style');
132
133
134 function guaven_sqlcharts_isJson($string)
135 {
136 json_decode($string);
137 return (json_last_error() == JSON_ERROR_NONE);
138 }
139
140 add_action('init', 'guaven_sqlcharts_register_post');
141 function guaven_sqlcharts_register_post()
142 {
143 //register_taxonomy('guaven_update_push_tag', 'termin');
144 register_post_type('gvn_schart', array(
145 'labels' => array(
146 'name' => __('My SQL Charts'),
147 'singular_name' => __('My SQL chart')
148 ),
149
150 'public' => true,
151 //'taxonomies' => array('guaven_update_push_tag'),
152 'supports' => array(
153 'title',
154 'postmeta'
155 ),
156 'register_meta_box_cb' => 'guaven_sqlcharts_metabox_area'
157 ));
158
159 guaven_sqlcharts_load_defaults();
160 }
161
162 add_action('admin_footer', 'guaven_sqlcharts_admin_front');
163
164
165 function guaven_sqlcharts_admin_front()
166 {
167 global $post;
168 if (!empty($post) and $post->post_type == 'gvn_schart') {
169 ?>
170 <style type="text/css">#normal-sortables{display: none}</style>
171 <?php
172 }
173 }
174
175 // metabox for editor
176 function guaven_sqlcharts_metabox_area()
177 {
178 add_meta_box('guaven_sqlcharts_metabox', 'Configure your graph chart', 'guaven_sqlcharts_metabox', 'gvn_schart', 'advanced', 'default');
179 }
180
181 function guaven_sqlcharts_metabox()
182 {
183 require_once(dirname(__FILE__) . "/admin_metabox.php");
184 }
185
186 function guaven_gutenberg_wrapper($atts){
187 if(isset($atts['sqlcharts_inserted_script'])){
188 global $sqlcharts_inserted_script;
189 $sqlcharts_inserted_script = $atts['sqlcharts_inserted_script'];
190 }
191
192 // if( isset($_GET["post_id"],$_GET["context"]) and $_GET["context"]=='edit'
193 // and strpos($_SERVER["REQUEST_URI"],'block-renderer/guaven-sqlcharts/gvn-chart-gutenberg')!==false
194 // ){
195 // $atts['chart_id']=$_GET["post_id"];
196 // }
197 $post = get_post($atts['chart_id']);
198 if( ! isset($atts['chart_id']) or !isset($post) or $post->post_type != 'gvn_schart'){
199
200 return "Invalid id";
201 }
202
203 return guaven_sqlcharts_local_shortcode(array('id' => $atts['chart_id'])); // temporary explicit value
204 }
205 function guaven_register_gutenberg_blocks()
206 {
207 wp_register_script(
208 'gvn_gutenberg_charts',
209 plugins_url( 'asset/guaven_gutenberg_charts.js', __FILE__ ),
210 array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-server-side-render' ),
211 GVNSQLCHARTS_VERSION.'_'.filemtime( plugin_dir_path( __FILE__ ) . 'asset/guaven_gutenberg_charts.js' )
212 );
213 wp_localize_script('gvn_gutenberg_charts', 'guaven', array(
214 'description' => 'Add My SQL Chart to your post',
215 ));
216
217 register_block_type( 'guaven-sqlcharts/gvn-chart-gutenberg', array(
218 'editor_script' => 'gvn_gutenberg_charts',
219 'render_callback' => 'guaven_gutenberg_wrapper',
220 'attributes' => array(
221 'chart_id' => array(
222 'type' => 'string',
223 'default' => null
224 ),
225 'sqlcharts_inserted_script' => array(
226 'type' => 'number',
227 'default' => null
228 )
229 )
230 ));
231 }
232 add_action('init', 'guaven_register_gutenberg_blocks');
233
234
235
236 function guaven_sqlcharts_save_metabox_area($post_id, $post)
237 {
238 if (!isset($_POST['meta_box_nonce_field']) or !wp_verify_nonce($_POST['meta_box_nonce_field'], 'meta_box_nonce_action')) {
239 return $post->ID;
240 }
241 $fields = array(
242 "guaven_sqlcharts_chartheight",
243 "guaven_sqlcharts_chartwidth",
244 "guaven_sqlcharts_graphtype",
245 "guaven_sqlcharts_xarg_s",
246 "guaven_sqlcharts_xarg_l",
247 "guaven_sqlcharts_yarg_s",
248 "guaven_sqlcharts_yarg_l",
249 "guaven_sqlcharts_tablepart",
250 "guaven_sqlcharts_variables",
251 "guaven_sqlcharts_formpartrole",
252 "guaven_sqlcharts_formpartbutton",
253 "guaven_sqlcharts_dbhost",
254 "guaven_sqlcharts_dblogin",
255 "guaven_sqlcharts_dbname",
256 "guaven_sqlcharts_colors",
257 "guaven_sqlcharts_begin_with_0_x",
258 "guaven_sqlcharts_begin_with_0_y",
259 "guaven_sqlcharts_round_y_values",
260 "guaven_sqlcharts_legend_position",
261 "guaven_sqlcharts_nostacked"
262 );
263 foreach ($fields as $key => $value) {
264 if(isset($_POST[$value]))$newval=esc_attr($_POST[$value]);
265 else $newval='';
266
267 update_post_meta($post->ID, $value, $newval);
268 }
269 if(!empty($_POST["guaven_sqlcharts_dbpass"])){
270 $encpass=guaven_sqlcharts_encrypt_decrypt('encrypt',$_POST["guaven_sqlcharts_dbpass"]);
271 update_post_meta($post->ID, 'guaven_sqlcharts_dbpass', ['encrypted',$encpass]);
272 }
273 update_post_meta($post->ID, 'guaven_sqlcharts_code', esc_attr(str_replace("'",'"',stripslashes($_POST['guaven_sqlcharts_code']))) );
274 }
275 add_action('save_post', 'guaven_sqlcharts_save_metabox_area', 1, 2);
276 // save the custom fields
277
278
279
280
281 function guaven_sqlcharts_libloads($type, $step)
282 {
283 $stty = array(
284 'bar' => array(
285 'packages' => "'corechart', 'bar'",
286 'charts' => "BarChart"
287 ),
288 'column' => array(
289 'packages' => "'corechart', 'bar'",
290 'charts' => "ColumnChart"
291 ),
292 'area' => array(
293 'packages' => "'corechart'",
294 'charts' => "AreaChart"
295 ),
296 'pie' => array(
297 'packages' => "'corechart'",
298 'charts' => "PieChart"
299 ),
300 '3dpie' => array(
301 'packages' => "'corechart'",
302 'charts' => "PieChart"
303 )
304 );
305
306 return $stty[$type][$step];
307 }
308 function gvn_chart_check_sql_query($sql)
309 {
310 $blacklister = array(
311 "delete",
312 "update",
313 "insert",
314 "drop",
315 "truncate",
316 "alter"
317 ); //add all
318 $blacklister_f = 0;
319 foreach ($blacklister as $key => $value) {
320 if (strpos($sql, $value) !== false)
321 $blacklister_f = 1;
322 }
323 return $blacklister_f;
324 }
325
326 function guaven_get_labels_and_values($id, $fvs)
327 {
328 $values = array();
329 $labels = array();
330 $xarg_s = get_post_meta($id, 'guaven_sqlcharts_xarg_s', true);
331 $xarg_l = get_post_meta($id, 'guaven_sqlcharts_xarg_l', true);
332 $yarg_s = get_post_meta($id, 'guaven_sqlcharts_yarg_s', true);
333 $yarg_l = get_post_meta($id, 'guaven_sqlcharts_yarg_l', true);
334 $chartype = array(
335 'line_l' => 'Line',
336 'pie_l' => 'Pie',
337 'donut_l' => 'Pie',
338 'bar_l' => 'Bar',
339 'horizontalbar_l' => 'Horizontal Bar',
340 'area_l' => 'Line'
341 );
342 foreach ($fvs as $key => $value) {
343 $values[] = $value->$yarg_s;
344 $labels[] = '"' . $value->$xarg_s . '"';
345 }
346 return array(
347 $labels,
348 $values,
349 explode(";", $yarg_l),
350 explode(";", $xarg_l)
351 );
352 }
353
354 function guaven_sqlcharts_print_chart_js($tip_g, $title, $labels, $values, $ylabel, $pid = null)
355 {
356 if ($tip_g == 'line_l') {
357 guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'false', $pid);
358 }
359 if ($tip_g == 'area_l') {
360 guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, 'true', $pid);
361 } elseif ($tip_g == 'pie_l') {
362 guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid);
363 } elseif ($tip_g == 'donut_l') {
364 guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, 'doughnut');
365 } elseif ($tip_g == 'bar_l') {
366 guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, 'bar', $pid);
367 } elseif ($tip_g == 'horizontalbar_l') {
368 guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, 'horizontalBar', $pid);
369 }
370 elseif($tip_g == 'custom'){
371 guaven_sqlcharts_custom($title, $labels, $values, $ylabel, $pid);
372 }
373 elseif ($tip_g == 'polar_l') {
374 guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, 'polarArea');
375 }
376 }
377
378 function guaven_sqlcharts_custom($title, $labels, $values, $ylabel, $pid){
379 do_action('guaven_sqlcharts_custom',$title, $labels, $values, $ylabel, $pid);
380 }
381
382 function gvn_chart_put_variables($sql,$pid){
383 $sql_initial=$sql;
384
385
386 $default_tag_keys=['{current_user_id}','{current_user_login}','{current_user_email}','{current_user_display_name}'];
387 if(is_user_logged_in( )){
388 $currentuser=wp_get_current_user();
389 $default_tag_values=[$currentuser->ID,$currentuser->user_login,$currentuser->user_email,$currentuser->user_display_name];
390 }
391 else {
392 $default_tag_values='';
393 }
394 $sql_initial=str_replace($default_tag_keys,$default_tag_values,$sql_initial);
395
396 $variables_raw=get_post_meta($pid,'guaven_sqlcharts_variables',true);
397 $variables_arr=explode("|",$variables_raw);
398 foreach($variables_arr as $varfield){
399 $varfield_arr=explode("~",$varfield);
400 if (count($varfield_arr)<3) continue;
401 $varfield_arr=array_map("trim",$varfield_arr);
402 if (!empty($_GET[$varfield_arr[0]])) $varreplacement=$_GET[$varfield_arr[0]]; else $varreplacement=$varfield_arr[1];
403 if (!is_numeric($varreplacement) and strpos($varreplacement,'()')===false) $varreplacement='"'.$varreplacement.'"';
404
405 $sql_initial=str_replace('{'.$varfield_arr[0].'}',$varreplacement,$sql_initial);
406 }
407 return $sql_initial;
408 }
409
410 function gvn_chart_top_form($atts){
411 if (get_post_meta($atts["id"],'guaven_sqlcharts_formpartrole',true)!='' and !is_user_logged_in()) return;
412 $topform='';$dateexists=false;
413 $variables_raw=get_post_meta($atts['id'],'guaven_sqlcharts_variables',true);
414 $variables_raw=explode("|",$variables_raw);
415 foreach ($variables_raw as $vrow){
416 $vrow_arr=explode("~",$vrow);
417 $vrow_arr=array_map("trim",$vrow_arr);
418 if (empty($vrow_arr[3])) continue;
419 $gvalue=!empty($_GET[$vrow_arr[0]])?esc_attr(urldecode($_GET[$vrow_arr[0]])):'';
420 $dvalue=(strpos($vrow_arr[1],'()')===false)?esc_attr($vrow_arr[1]):'';
421 if ($vrow_arr[3]=='date') {
422 $dateexists=true;
423 $topform.= $vrow_arr[2].' <input autocomplete="off" style="max-width:210px" type="text"
424 value="'.$gvalue.'"
425 data-toggle="datepicker" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'">
426 ';}
427 else {
428 $topform.= $vrow_arr[2].' <input autocomplete="off" style="max-width:210px;'.($vrow_arr[3]=='number'?'width:100px;':'').'"
429 type="'.$vrow_arr[3].'"
430 value="'.$gvalue.'" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'">
431 ';
432 }
433 }
434 if (!empty($topform)) {
435 $topform='<form method="get" action="" class="guaven_sqlcharts_form">'.$topform.'
436 <input type="submit"
437 value="'.(get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true)!=''?esc_attr(get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true)):'OK').'"></form>';
438 if ($dateexists) $topform.='<script>setTimeout(function(){jQuery(\'[data-toggle="datepicker"]\').datepicker({format: \'yyyy-mm-dd\'});
439 },300);</script>';
440 return $topform ;
441 }
442 return;
443 }
444
445
446 function guaven_sqlcharts_encrypt_decrypt($action, $string)
447 {
448 $output = false;
449 $encrypt_method = "AES-256-CBC";
450 $secret_key = 'GWSCHARTPL2022.2016.';
451 $secret_iv = 'GWSCHARTPL2016.2022';
452 $key = hash('sha256', $secret_key);
453 $iv = substr(hash('sha256', $secret_iv), 0, 16);
454 if ( $action == 'encrypt' ) {
455 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
456 $output = base64_encode($output);
457 } else if( $action == 'decrypt' ) {
458 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
459 }
460 return $output;
461 }
462
463 function guaven_sqlcharts_local_shortcode($atts)
464 {
465 $remote_host=get_post_meta($atts['id'], 'guaven_sqlcharts_dbhost', true);
466 if ($remote_host!=''){
467 $remote_db=get_post_meta($atts['id'], 'guaven_sqlcharts_dbname', true);
468 $remote_login=get_post_meta($atts['id'], 'guaven_sqlcharts_dblogin', true);
469 $remote_pass=get_post_meta($atts['id'], 'guaven_sqlcharts_dbpass', true);
470 if(is_array($remote_pass)){
471 $remote_pass=guaven_sqlcharts_encrypt_decrypt('decrypt',$remote_pass[1]);
472 }
473 $wpdb=new wpdb($remote_login,$remote_pass,$remote_db,$remote_host);
474 }
475 else {
476 global $wpdb;
477 }
478
479 $GLOBALS["guaven_sqlcharts_atts"]=$atts;
480
481 $sql = html_entity_decode(get_post_meta($atts['id'], 'guaven_sqlcharts_code', true));
482 $sql=gvn_chart_put_variables($sql,$atts['id']);
483 $blacklister_f = gvn_chart_check_sql_query($sql);
484 if ($blacklister_f == 1)
485 return 'You given SQL code contains forbidden commands. Remember that you should only use SELECT queries';
486 $tip_g = get_post_meta($atts['id'], 'guaven_sqlcharts_graphtype', true);
487
488 for($i=1;$i<20;$i++){ $replacearg=!empty($atts["arg".$i])?$atts["arg".$i]:0;
489 $sql=str_replace("{arg".$i."}",esc_sql($replacearg),$sql);}
490 $sql_split = explode(';', $sql);
491 $labels_and_values = array();
492 $post_g = get_post($atts['id']);
493
494 global $sqlcharts_inserted_script;
495 for ($i = 0; $i < count($sql_split); $i++) {
496 if (!empty($sql_split[$i])) {
497
498 $fvs = $wpdb->get_results($sql_split[$i]);
499 if (strpos($_SERVER["REQUEST_URI"],'wp-admin')!==false){
500 $wpdb->show_errors();
501 ob_start();
502 $wpdb->print_error();
503 $printerror = ob_get_clean();
504 if ($printerror != '' and strpos($printerror, "[]") === false)
505 return $printerror;
506 elseif (empty($fvs))
507 return 'Your SQL returnes empty date, please recheck your SQL query above';
508 }
509
510 ob_start();
511
512 if (empty($sqlcharts_inserted_script))
513 $sqlcharts_inserted_script = 1;
514 $labels_and_values[$i] = guaven_get_labels_and_values($atts['id'], $fvs);
515 $labels[$i] = $labels_and_values[$i][0];
516 $values[$i] = $labels_and_values[$i][1];
517 $ylabel[$i] = !empty($labels_and_values[$i][2][$i]) ? $labels_and_values[$i][2][$i] : '';
518 $xlabel[$i] = !empty($labels_and_values[$i][3][$i]) ? $labels_and_values[$i][3][$i] : '';
519 }
520 }
521
522 echo gvn_chart_top_form($atts);
523 ?>
524 <canvas
525 id="ct-chart_<?php echo $sqlcharts_inserted_script; ?>"
526 class="guaven_chart_canvas"
527 style="width: <?php echo get_post_meta($atts['id'], 'guaven_sqlcharts_chartwidth', true); ?>px !important; height: <?php echo get_post_meta($atts['id'], 'guaven_sqlcharts_chartheight', true); ?>px !important;"
528 ></canvas>
529
530 <script type="text/javascript" class="gvn_charts_script" async>
531 var ctx = jQuery("#ct-chart_<?php
532 echo $sqlcharts_inserted_script;
533 ?>");
534
535 <?php
536 guaven_sqlcharts_print_chart_js($tip_g, $post_g->post_title, $labels, $values, $ylabel, $atts['id']);
537 ?>
538 </script>
539
540 <?php
541 if (!empty($atts["table"])) echo guaven_sqlcharts_tablepart($post_g->post_title, $labels, $values, $ylabel,$xlabel);
542 $sqlcharts_inserted_script++;
543 return ob_get_clean();
544 }
545
546 add_shortcode('gvn_schart_2', 'guaven_sqlcharts_local_shortcode');
547
548 function guaven_sqlcharts_colors($index, $pid = null){
549 if(!isset($pid)) {
550 global $post;
551 $pid = $post->ID;
552 }
553 $colors=get_post_meta($pid,'guaven_sqlcharts_colors',true);
554 $colors=explode(",",$colors);
555 if (!empty($colors[$index])) return $colors[$index];
556 return rand(0, 255) . ',' . rand(0, 255) . ',' . rand(0, 255);
557 }
558
559 function guaven_sqlcharts_toshowlegend($pid){
560 $guaven_sqlcharts_legend_position=get_post_meta($pid, 'guaven_sqlcharts_legend_position', true);
561 if(in_array($guaven_sqlcharts_legend_position,['top','bottom','left','right'])){
562 $display='true';$position=$guaven_sqlcharts_legend_position;
563 }
564 else {
565 $display='false';$position='top';
566 }
567 return "legend: {display: ".$display.",position:'".$position."'},";
568 }
569
570 function guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, $type = 'bar', $pid = null)
571 {
572 ?>
573 var data = {
574 labels: [<?php
575 echo implode(",", $labels[0]);
576 ?>],
577 datasets: [
578 <?php
579 for ($i = 0; $i < count($values); $i++) {
580 ?>
581 {
582 <?php
583 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
584 //passing chartJS params via the shortcode
585 echo esc_js($GLOBALS["guaven_sqlcharts_atts"]["params"]);
586 }
587 ?>
588 label: "<?php
589 echo esc_attr($ylabel[$i]);
590 ?>",
591 backgroundColor: [
592 <?php
593 echo guaven_sqlcharts_colorgenerator(count($values[$i]), 0, 0, guaven_sqlcharts_colors($i, $pid));
594 ?>
595 ],
596 borderColor: [
597 <?php
598 echo guaven_sqlcharts_colorgenerator(count($values[$i]), 0, 0.2, guaven_sqlcharts_colors($i, $pid));
599 ?>
600 ],
601 borderWidth: 1,
602 data: [<?php
603 echo implode(",", $values[$i]);
604 ?>],
605 },
606 <?php
607 }
608 ?>
609 ]
610 };
611 var options={
612 <?php echo guaven_sqlcharts_toshowlegend($pid);?>
613 responsive: true,
614 scales: {
615 xAxes: [{
616 <?php echo (get_post_meta($pid, 'guaven_sqlcharts_nostacked', true) == 1) ? '':'stacked: true,';?>
617 ticks: {
618 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
619 }
620 }],
621 yAxes: [{
622 <?php echo (get_post_meta($pid, 'guaven_sqlcharts_nostacked', true) == 1) ? '':'stacked: true,';?>
623 ticks: {
624 <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
625 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>
626 }
627 }]
628 }
629 };
630 var myBarChart = new Chart(ctx, {
631 type: '<?php
632 echo $type;
633 ?>',
634 data: data,
635 options: options
636 });
637 <?php
638 }
639
640
641
642 function guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, $type = 'false', $pid = null)
643 {
644 ?>
645 var data = {
646 labels: [<?php
647 echo implode(",", $labels[0]);
648 ?>],
649 datasets: [
650 <?php
651 for ($i = 0; $i < count($values); $i++) {
652 ?>
653 {
654 <?php
655 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
656 //passing chartJS params via the shortcode
657 echo esc_js($GLOBALS["guaven_sqlcharts_atts"]["params"]);
658 }
659 ?>
660 label: "<?php
661 echo esc_attr($ylabel[$i]);
662 ?>",
663 fill: <?php echo $type=="false"?$type:($i==0?'"+1"':'"origin"');
664 ?>,
665 lineTension: 0.1,
666 backgroundColor: <?php
667 echo guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid));
668 ?>
669 borderColor: <?php
670 echo guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid));
671 ?>
672 pointBorderColor: <?php
673 echo guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid));
674 ?>
675 pointHoverBackgroundColor: <?php
676 echo guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid));
677 ?>
678 pointHoverBorderColor: <?php
679 echo guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid));
680 ?>
681 data: [<?php
682 echo implode(",", $values[$i]);
683 ?>],
684 spanGaps: false,
685 },
686 <?php
687 }
688 ?>
689 ]
690 };
691 var myLineChart = new Chart(ctx, {
692 type: 'line',
693 data: data,
694 options: {
695 <?php echo guaven_sqlcharts_toshowlegend($pid);?>
696 responsive: true,
697 scales: {
698 xAxes: [{
699 display: true,
700 ticks: {
701 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
702 }
703 }],
704 yAxes: [{
705 ticks: {
706 <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
707 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>
708 }
709 }]
710 }
711 }
712 });
713 <?php
714 }
715
716
717 function guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, $type = 'pie')
718 {
719 ?>
720 var options={
721 <?php echo guaven_sqlcharts_toshowlegend($pid);?>
722 responsive: true,
723 };
724 var data = {
725 labels: [ <?php echo implode(",", $labels[0]);?>],
726 datasets: [
727 <?php
728 for ($i = 0; $i < count($values); $i++) {
729 ?>
730 {
731 <?php
732 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
733 //passing chartJS params via the shortcode
734 echo esc_js($GLOBALS["guaven_sqlcharts_atts"]["params"]);
735 }
736 ?>
737 data: [<?php
738 echo implode(",", $values[$i]);
739 ?>],
740 backgroundColor: [
741 <?php
742 foreach($values[$i] as $vci=>$valuecolor){
743 echo guaven_sqlcharts_colorgenerator(1, 0, 0, guaven_sqlcharts_colors($vci, $pid));
744 }
745 ?>
746 ],
747 hoverBackgroundColor: [
748 <?php
749 foreach($values[$i] as $vci=>$valuecolor){
750 echo guaven_sqlcharts_colorgenerator(1, 0, 0.2, guaven_sqlcharts_colors($vci, $pid));
751 }
752 ?>
753 ]
754 },
755 <?php
756 }
757 ?>
758 ]
759 };
760 var myPieChart = new Chart(ctx,{
761 type: '<?php
762 echo $type;
763 ?>',
764 data: data,
765 options: options
766 });
767 <?php
768 }
769
770
771
772
773 function guaven_sqlcharts_colorgenerator($count, $indic, $darkness = 0, $initcolor = '255,0,0')
774 {
775 if (strpos($initcolor,'#')===0) {
776 $split = str_split(substr($initcolor,1), 2);
777 $r = hexdec($split[0]);
778 $g = hexdec($split[1]);
779 $b = hexdec($split[2]);
780 $ret='';
781 for ($i = 0; $i < $count; $i++) {
782 $ret .= "'rgba(" . $r . ", " . $g . ", " . $b . ",".($darkness + 0.8 - $indic * $i * 0.8 / ($count)).")',
783 ";
784 }
785 return $ret;
786 }
787 $initial_colors = array(
788 'linebg' => 'red',
789 'linebr' => 'yellow',
790 'linebc' => 'green',
791 'linehbg' => 'white',
792 'linehbc' => 'black'
793 );
794 if (!empty($initial_colors[$count]))
795 return '"' . $initial_colors[$count] . '",
796 ';
797 $ret = '';
798 for ($i = 0; $i < $count; $i++) {
799 $ret .= "'rgba(" . $initcolor . "," . ($darkness + 0.8 - $indic * $i * 0.8 / ($count)) . ")',
800 ";
801 }
802 return $ret;
803 }
804
805 function guaven_sqlcharts_tablepart($title, $labels, $values, $ylabel,$xlabel){
806 $tabledata='';
807 $fcol=[];$scol=[];
808 $tablein='<br>';
809 foreach($values as $valuerow){
810 foreach ($valuerow as $key => $value) {
811 $fcol[$key]='<td>'.str_replace('"',"",$labels[0][$key]).'</td>';
812 $scol[$key][]='<td>'.$value.'</td>';
813
814 }
815 }
816 foreach($fcol as $key=>$value){
817 $tablein.='<tr>'.$value.implode(" ",$scol[$key]).'</tr>'.PHP_EOL;
818 }
819 $tabledata.='<table><tr><th>'.$xlabel[0].'</th><th>'.implode("</th><th>",$ylabel).'</th></tr>
820 '.$tablein.'</table><br>';
821 return $tabledata;
822
823 }
824