PluginProbe
SQL Chart Builder / 2.3.4
SQL Chart Builder v2.3.4
3.0.5 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.4, at functions.php

849 lines 30.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 {
439 $remote_host=get_post_meta($atts['id'], 'guaven_sqlcharts_dbhost', true);
440 if ($remote_host!=''){
441 $remote_db=get_post_meta($atts['id'], 'guaven_sqlcharts_dbname', true);
442 $remote_login=get_post_meta($atts['id'], 'guaven_sqlcharts_dblogin', true);
443 $remote_pass=get_post_meta($atts['id'], 'guaven_sqlcharts_dbpass', true);
444 if(is_array($remote_pass)){
445 $remote_pass=guaven_sqlcharts_encrypt_decrypt('decrypt',$remote_pass[1]);
446 }
447 $wpdb=new wpdb($remote_login,$remote_pass,$remote_db,$remote_host);
448 }
449 else {
450 global $wpdb;
451 }
452
453 $GLOBALS["guaven_sqlcharts_atts"]=$atts;
454
455 $sql = html_entity_decode(get_post_meta($atts['id'], 'guaven_sqlcharts_code', true));
456 $sql=gvn_chart_put_variables($sql,$atts['id']);
457 $blacklister_f = gvn_chart_check_sql_query($sql);
458 if ($blacklister_f == 1)
459 return 'You given SQL code contains forbidden commands. Remember that you should only use SELECT queries';
460 $tip_g = get_post_meta($atts['id'], 'guaven_sqlcharts_graphtype', true);
461
462 for($i=1;$i<20;$i++){ $replacearg=!empty($atts["arg".$i])?$atts["arg".$i]:0;
463 $sql=str_replace("{arg".$i."}",esc_sql($replacearg),$sql);}
464 $sql_split = explode(';', $sql);
465 $labels_and_values = array();
466 $post_g = get_post($atts['id']);
467
468 global $sqlcharts_inserted_script;
469 for ($i = 0; $i < count($sql_split); $i++) {
470 if (!empty($sql_split[$i])) {
471
472 $fvs = $wpdb->get_results($sql_split[$i]);
473 if (strpos($_SERVER["REQUEST_URI"],'wp-admin')!==false){
474 $wpdb->show_errors();
475 ob_start();
476 $wpdb->print_error();
477 $printerror = ob_get_clean();
478 if ($printerror != '' and strpos($printerror, "[]") === false)
479 return $printerror;
480 elseif (empty($fvs))
481 return 'Your SQL returnes empty data, please recheck your SQL query above';
482 }
483
484 ob_start();
485
486 if (empty($sqlcharts_inserted_script))
487 $sqlcharts_inserted_script = 1;
488 $labels_and_values[$i] = guaven_get_labels_and_values($atts['id'], $fvs);
489 $labels[$i] = $labels_and_values[$i][0];
490 $values[$i] = $labels_and_values[$i][1];
491 $ylabel[$i] = !empty($labels_and_values[$i][2][$i]) ? $labels_and_values[$i][2][$i] : '';
492 $xlabel[$i] = !empty($labels_and_values[$i][3][$i]) ? $labels_and_values[$i][3][$i] : '';
493 }
494 }
495
496 echo gvn_chart_top_form($atts);
497 ?>
498 <canvas
499 id="ct-chart_<?php echo $sqlcharts_inserted_script; ?>"
500 class="guaven_chart_canvas"
501 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;"
502 ></canvas>
503
504 <script type="text/javascript" class="gvn_charts_script" async>
505 var ctx = jQuery("#ct-chart_<?php
506 echo $sqlcharts_inserted_script;
507 ?>");
508
509 <?php
510 guaven_sqlcharts_print_chart_js($tip_g, $post_g->post_title, $labels, $values, $ylabel, $atts['id']);
511 ?>
512 </script>
513
514 <?php
515 if (!empty($atts["table"])) echo guaven_sqlcharts_tablepart($post_g->post_title, $labels, $values, $ylabel,$xlabel);
516 $sqlcharts_inserted_script++;
517 return ob_get_clean();
518 }
519
520 add_shortcode('gvn_schart_2', 'guaven_sqlcharts_local_shortcode');
521
522 add_shortcode("gvn_schart_2_cached",function($atts){
523 if(empty($atts["id"]))return;
524 $expire=!empty($atts["expire"])?intval($atts["expire"]):3600;
525 $cached=get_transient('cached_sql_charts_'.$atts["id"]);
526 if(!empty($cached) and !isset($_GET["force_sql_cache_reload"]) )return $cached;
527 $tobecached=do_shortcode('[gvn_schart_2 id="'.$atts["id"].'"]');
528 set_transient('cached_sql_charts_'.$atts["id"], $tobecached,$expire);//you can change 3600 yourself
529 return $tobecached;
530 });
531
532 function guaven_sqlcharts_colors($index, $pid = null){
533 if(!isset($pid)) {
534 global $post;
535 $pid = $post->ID;
536 }
537 $colors=get_post_meta($pid,'guaven_sqlcharts_colors',true);
538 $colors=explode(",",$colors);
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(",", $labels[0]);
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
628
629 function guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, $type = 'false', $pid = null)
630 {
631 ?>
632 var data = {
633 labels: [<?php
634 echo implode(",", $labels[0]);
635 ?>],
636 datasets: [
637 <?php
638 $values_new=guaven_sqlcharts_key_normalizer($values,$labels,$ylabel)[0];
639 $i=-1;
640 foreach ($values_new as $key_ak=>$value_ak) {
641 $i++;
642 ?>
643 {
644 <?php
645 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
646 //passing chartJS params via the shortcode
647 echo esc_js($GLOBALS["guaven_sqlcharts_atts"]["params"]);
648 }
649 ?>
650 label: "<?php
651 echo esc_attr($ylabel[$key_ak]);
652 ?>",
653 fill: <?php echo $type=="false"?$type:($i==0?'"+1"':'"origin"');
654 ?>,
655 lineTension: 0.1,
656 backgroundColor: <?php
657 echo guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid));
658 ?>
659 borderColor: <?php
660 echo guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid));
661 ?>
662 pointBorderColor: <?php
663 echo guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid));
664 ?>
665 pointHoverBackgroundColor: <?php
666 echo guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid));
667 ?>
668 pointHoverBorderColor: <?php
669 echo guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid));
670 ?>
671 data: [<?php
672 echo implode(",", $values_new[$key_ak]);
673 ?>],
674 spanGaps: false,
675 },
676 <?php
677 }
678 ?>
679 ]
680 };
681 var myLineChart = new Chart(ctx, {
682 type: 'line',
683 data: data,
684 options: {
685 <?php echo guaven_sqlcharts_toshowlegend($pid);?>
686 responsive: true,
687 scales: {
688 xAxes: [{
689 display: true,
690 ticks: {
691 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?>
692 }
693 }],
694 yAxes: [{
695 ticks: {
696 <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?>
697 beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>
698 }
699 }]
700 }
701 }
702 });
703 <?php
704 }
705
706
707 function guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, $type = 'pie')
708 {
709 if(get_post_meta($pid,'guaven_sqlcharts_forcetooltips',true)!=''){
710 echo 'guaven_sqlcharts_show_pie_labels();'.PHP_EOL;
711 }
712 ?>
713 var options={
714 showAllTooltips: true,
715 <?php echo guaven_sqlcharts_toshowlegend($pid);?>
716 responsive: true,
717 };
718 var data = {
719 labels: [ <?php echo implode(",", $labels[0]);?>],
720 datasets: [
721 <?php
722 for ($i = 0; $i < count($values); $i++) {
723 ?>
724 {
725 <?php
726 if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){
727 //passing chartJS params via the shortcode
728 echo esc_js($GLOBALS["guaven_sqlcharts_atts"]["params"]);
729 }
730 ?>
731 data: [<?php
732 echo implode(",", $values[$i]);
733 ?>],
734 backgroundColor: [
735 <?php
736 foreach($values[$i] as $vci=>$valuecolor){
737 echo guaven_sqlcharts_colorgenerator(1, 0, 0, guaven_sqlcharts_colors($vci, $pid));
738 }
739 ?>
740 ],
741 hoverBackgroundColor: [
742 <?php
743 foreach($values[$i] as $vci=>$valuecolor){
744 echo guaven_sqlcharts_colorgenerator(1, 0, 0.2, guaven_sqlcharts_colors($vci, $pid));
745 }
746 ?>
747 ]
748 },
749 <?php
750 }
751 ?>
752 ]
753 };
754 var myPieChart = new Chart(ctx,{
755 type: '<?php
756 echo $type;
757 ?>',
758 data: data,
759 options: options
760 });
761 <?php
762 }
763
764
765
766
767 function guaven_sqlcharts_colorgenerator($count, $indic, $darkness = 0, $initcolor = '255,0,0')
768 {
769 if (strpos($initcolor,'#')===0) {
770 $split = str_split(substr($initcolor,1), 2);
771 $r = hexdec($split[0]);
772 $g = hexdec($split[1]);
773 $b = hexdec($split[2]);
774 $ret='';
775 for ($i = 0; $i < $count; $i++) {
776 $ret .= "'rgba(" . $r . ", " . $g . ", " . $b . ",".($darkness + 0.8 - $indic * $i * 0.8 / ($count)).")',
777 ";
778 }
779 return $ret;
780 }
781 $initial_colors = array(
782 'linebg' => 'red',
783 'linebr' => 'yellow',
784 'linebc' => 'green',
785 'linehbg' => 'white',
786 'linehbc' => 'black'
787 );
788 if (!empty($initial_colors[$count]))
789 return '"' . $initial_colors[$count] . '",
790 ';
791 $ret = '';
792 for ($i = 0; $i < $count; $i++) {
793 $ret .= "'rgba(" . $initcolor . "," . ($darkness + 0.8 - $indic * $i * 0.8 / ($count)) . ")',
794 ";
795 }
796 return $ret;
797 }
798
799 function guaven_sqlcharts_tablepart($title, $labels, $values, $ylabel,$xlabel){
800 $tabledata='';
801 $fcol=[];$scol=[];
802 $tablein='<br>';
803 foreach($values as $valuerow){
804 foreach ($valuerow as $key => $value) {
805 $fcol[$key]='<td>'.str_replace('"',"",$labels[0][$key]).'</td>';
806 $scol[$key][]='<td>'.$value.'</td>';
807
808 }
809 }
810 foreach($fcol as $key=>$value){
811 $tablein.='<tr>'.$value.implode(" ",$scol[$key]).'</tr>'.PHP_EOL;
812 }
813 $tabledata.='<table><tr><th>'.$xlabel[0].'</th><th>'.implode("</th><th>",$ylabel).'</th></tr>
814 '.$tablein.'</table><br>';
815 return $tabledata;
816
817 }
818
819 function guaven_sqlcharts_graphtype($post){
820 if (strpos(get_post_meta($post->ID, 'guaven_sqlcharts_graphtype', true), "_l") !== false)
821 $postfix = '_2';
822 else $postfix = '';
823 return $postfix;
824 }
825
826 add_filter('the_content',function($content){
827 if(!is_singular('gvn_schart'))return $content;
828 global $post;
829 $postfix=guaven_sqlcharts_graphtype($post);
830 return '[gvn_schart'.$postfix.' id="'.$post->ID.'"'.
831 (get_post_meta($post->ID,'guaven_sqlcharts_tablepart',true)!=''?' table="1"':'')
832 .']';
833 });
834
835 function guaven_sqlcharts_key_normalizer($values,$labels,$ylabel){
836 $normalize_keys=[];
837 foreach ($values as $key_ak=>$value_ak) {
838 $normalize_keys=array_merge($normalize_keys,array_keys($values[$key_ak]));
839 }
840 $values_normalized=[];$labels_normalized=[];$ylabel_normalized=[];
841 foreach($normalize_keys as $normalized_key){
842 foreach ($values as $key_ak=>$value_ak) {
843 $values_normalized[$key_ak][$normalized_key]=isset( $values[$key_ak][$normalized_key])? $values[$key_ak][$normalized_key]:"''";
844 $labels_normalized[$key_ak][$normalized_key]=isset( $labels[$key_ak][$normalized_key])? $labels[$key_ak][$normalized_key]:"''";
845 $ylabel_normalized[$key_ak][$normalized_key]=isset( $ylabel[$key_ak][$normalized_key])? $ylabel[$key_ak][$normalized_key]:"''";
846 }
847 }
848 return [$values_normalized,$labels_normalized,$ylabel_normalized];
849 }