PluginProbe
SQL Chart Builder / 2.3.5
SQL Chart Builder v2.3.5
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.5, at functions.php

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