| @@ -110,8 +110,9 @@ | ||
| 110 | 110 | add_action('admin_notices', 'guaven_sqlcharts_onboarding_notice'); |
| 111 | 111 | |
| 112 | 112 | function guaven_sqlcharts_onboarding_notice_dismissed(){ |
| 113 | 113 | check_ajax_referer('notice_dismissed', 'nonce'); |
| 114 | + if (!current_user_can('manage_options')) return; | |
| 114 | 115 | |
| 115 | 116 | if(empty($_POST['type']))return; |
| 116 | 117 | switch ($_POST['type']){ |
| 117 | 118 | case 'onboarding_notice': |
| @@ -224,9 +225,31 @@ | ||
| 224 | 225 | 'item_updated' => __('Chart updated.','guaven_sqlcharts'), |
| 225 | 226 | ), |
| 226 | 227 | |
| 227 | 228 | 'public' => true, |
| 229 | + 'show_in_rest' => false, | |
| 228 | 230 | 'menu_icon' => 'dashicons-chart-pie', |
| 231 | + // Charts execute SQL, so every primitive capability of this post type maps to manage_options. | |
| 232 | + // Contributors/Authors cannot create, edit, publish or delete charts through any WordPress | |
| 233 | + // entry point (admin UI, XML-RPC, REST). Published charts stay viewable on the front end. | |
| 234 | + // Only primitive capabilities are remapped: mapping the meta capabilities edit_post/read_post/ | |
| 235 | + // delete_post to manage_options would make WordPress treat manage_options itself as a meta | |
| 236 | + // capability and break that check site-wide. | |
| 237 | + 'capability_type' => 'post', | |
| 238 | + 'map_meta_cap' => true, | |
| 239 | + 'capabilities' => array( | |
| 240 | + 'edit_posts' => 'manage_options', | |
| 241 | + 'edit_others_posts' => 'manage_options', | |
| 242 | + 'edit_published_posts' => 'manage_options', | |
| 243 | + 'edit_private_posts' => 'manage_options', | |
| 244 | + 'publish_posts' => 'manage_options', | |
| 245 | + 'read_private_posts' => 'manage_options', | |
| 246 | + 'delete_posts' => 'manage_options', | |
| 247 | + 'delete_private_posts' => 'manage_options', | |
| 248 | + 'delete_published_posts' => 'manage_options', | |
| 249 | + 'delete_others_posts' => 'manage_options', | |
| 250 | + 'create_posts' => 'manage_options', | |
| 251 | + ), | |
| 229 | 252 | 'supports' => array( |
| 230 | 253 | 'title', |
| 231 | 254 | 'postmeta' |
| 232 | 255 | ), |
| @@ -235,8 +258,14 @@ | ||
| 235 | 258 | |
| 236 | 259 | guaven_sqlcharts_load_defaults(); |
| 237 | 260 | } |
| 238 | 261 | |
| 262 | +// All guaven_sqlcharts_* meta keys are protected: they cannot be written through the Custom Fields box, | |
| 263 | +// XML-RPC or the REST API. The plugin's own save handler (update_post_meta) is not affected. | |
| 264 | +add_filter('is_protected_meta', function ($protected, $meta_key) { | |
| 265 | + return strpos((string) $meta_key, 'guaven_sqlcharts_') === 0 ? true : $protected; | |
| 266 | +}, 10, 2); | |
| 267 | + | |
| 239 | 268 | // "Add title" placeholder on the chart edit screen |
| 240 | 269 | add_filter('enter_title_here', function ($title, $post) { |
| 241 | 270 | if (!empty($post) and $post->post_type == 'gvn_schart') return __('Chart name', 'guaven_sqlcharts'); |
| 242 | 271 | return $title; |
| @@ -423,8 +452,11 @@ | ||
| 423 | 452 | { |
| 424 | 453 | if (!isset($_POST['meta_box_nonce_field']) or !wp_verify_nonce($_POST['meta_box_nonce_field'], 'meta_box_nonce_action')) { |
| 425 | 454 | return $post->ID; |
| 426 | 455 | } |
| 456 | + if ($post->post_type != 'gvn_schart' or !current_user_can('manage_options') or (defined('DOING_AUTOSAVE') and DOING_AUTOSAVE)) { | |
| 457 | + return $post->ID; | |
| 458 | + } | |
| 427 | 459 | $fields = array( |
| 428 | 460 | "guaven_sqlcharts_chartheight", |
| 429 | 461 | "guaven_sqlcharts_chartwidth", |
| 430 | 462 | "guaven_sqlcharts_graphtype", |
| @@ -444,9 +476,10 @@ | ||
| 444 | 476 | "guaven_sqlcharts_begin_with_0_y", |
| 445 | 477 | "guaven_sqlcharts_round_y_values", |
| 446 | 478 | "guaven_sqlcharts_legend_position", |
| 447 | 479 | "guaven_sqlcharts_nostacked", |
| 448 | - "guaven_sqlcharts_forcetooltips" | |
| 480 | + "guaven_sqlcharts_forcetooltips", | |
| 481 | + "guaven_sqlcharts_timeaxis" | |
| 449 | 482 | ); |
| 450 | 483 | foreach ($fields as $key => $value) { |
| 451 | 484 | if(isset($_POST[$value]))$newval=esc_attr($_POST[$value]); |
| 452 | 485 | else $newval=''; |
| @@ -479,13 +512,57 @@ | ||
| 479 | 512 | // save the custom fields |
| 480 | 513 | |
| 481 | 514 | |
| 482 | 515 | |
| 516 | +// Removes string literals (contents only), backtick identifiers and comments from SQL so keyword checks | |
| 517 | +// see the same code MySQL will execute. "/*!" and "/*+" comments are executable in MySQL and are kept. | |
| 518 | +function guaven_sqlcharts_strip_sql_literals($sql) | |
| 519 | +{ | |
| 520 | + $out = ''; $len = strlen($sql); $i = 0; | |
| 521 | + while ($i < $len) { | |
| 522 | + $c = $sql[$i]; | |
| 523 | + if ($c === "'" or $c === '"' or $c === '`') { | |
| 524 | + $out .= $c . $c; $i++; | |
| 525 | + while ($i < $len) { | |
| 526 | + if ($sql[$i] === '\\' and $c !== '`') { $i += 2; continue; } | |
| 527 | + if ($sql[$i] === $c) { if ($i + 1 < $len and $sql[$i + 1] === $c) { $i += 2; continue; } $i++; break; } | |
| 528 | + $i++; | |
| 529 | + } | |
| 530 | + continue; | |
| 531 | + } | |
| 532 | + if ($c === '#' or ($c === '-' and substr($sql, $i, 2) === '--' and ($i + 2 >= $len or ctype_space($sql[$i + 2])))) { | |
| 533 | + $nl = strpos($sql, "\n", $i); $i = ($nl === false) ? $len : $nl; continue; | |
| 534 | + } | |
| 535 | + if ($c === '/' and substr($sql, $i, 2) === '/*' and !in_array(substr($sql, $i + 2, 1), array('!', '+'), true)) { | |
| 536 | + $close = strpos($sql, '*/', $i + 2); $i = ($close === false) ? $len : $close + 2; $out .= ' '; continue; | |
| 537 | + } | |
| 538 | + $out .= $c; $i++; | |
| 539 | + } | |
| 540 | + return $out; | |
| 541 | +} | |
| 542 | + | |
| 543 | +// Returns 1 when the (fully substituted) SQL must not run, 0 when it is a read-only query. | |
| 544 | +// Called after every {tag}/{argN} replacement so user-supplied values are covered too. | |
| 483 | 545 | function gvn_chart_check_sql_query($sql) |
| 484 | 546 | { |
| 485 | - // case-insensitive, word-boundary check: only read-only SELECT queries are allowed | |
| 486 | - $pattern = '/\b(delete|update|insert|replace|drop|truncate|alter|create|rename|grant|revoke|call|handler|load\s+data|load_file|outfile|dumpfile)\b/i'; | |
| 487 | - return preg_match($pattern, $sql) ? 1 : 0; | |
| 547 | + // 1) data-changing statements: checked on the raw text, exactly as in every previous version | |
| 548 | + $write = '/\b(delete|update|insert|replace|drop|truncate|alter|create|rename|grant|revoke|call|handler|load\s+data|load_file|outfile|dumpfile)\b/i'; | |
| 549 | + if (preg_match($write, $sql)) return 1; | |
| 550 | + | |
| 551 | + // 2) further dangerous statements, matched outside string literals and comments so that ordinary | |
| 552 | + // values such as status = 'reset' keep working | |
| 553 | + $danger = '/\b(prepare|execute|deallocate|lock|unlock|kill|shutdown|flush|reset|purge|install|uninstall|import' | |
| 554 | + . '|set\s+(?:global|session|persist|persist_only|password|@@)|start\s+(?:replica|slave|group_replication)|stop\s+(?:replica|slave)|change\s+(?:master|replication))\b/i'; | |
| 555 | + if (preg_match($danger, guaven_sqlcharts_strip_sql_literals($sql))) return 1; | |
| 556 | + | |
| 557 | + // 3) every ";"-separated statement must be a read statement. The renderer sends each segment to the | |
| 558 | + // database on its own, so this stops a value from smuggling a second statement behind a ";". | |
| 559 | + foreach (explode(';', $sql) as $segment) { | |
| 560 | + $segment = ltrim(guaven_sqlcharts_strip_sql_literals($segment), " \t\r\n("); | |
| 561 | + if ($segment === '') continue; | |
| 562 | + if (!preg_match('/^(select|with|show|describe|desc|explain)\b/i', $segment)) return 1; | |
| 563 | + } | |
| 564 | + return 0; | |
| 488 | 565 | } |
| 489 | 566 | |
| 490 | 567 | function guaven_get_labels_and_values($id, $fvs) |
| 491 | 568 | { |
| @@ -491,11 +568,13 @@ | ||
| 491 | 568 | { |
| 492 | 569 | $values = array(); |
| 493 | 570 | $labels = array(); |
| 494 | 571 | $xarg_s = get_post_meta($id, 'guaven_sqlcharts_xarg_s', true); |
| 495 | - $xarg_l = get_post_meta($id, 'guaven_sqlcharts_xarg_l', true); | |
| 496 | 572 | $yarg_s = get_post_meta($id, 'guaven_sqlcharts_yarg_s', true); |
| 497 | - $yarg_l = get_post_meta($id, 'guaven_sqlcharts_yarg_l', true); | |
| 573 | + // labels are saved through esc_attr, so "&" is stored as "&"; decode before splitting on ";" | |
| 574 | + // or the entity's own ";" would be taken as a series separator | |
| 575 | + $xarg_l = html_entity_decode((string) get_post_meta($id, 'guaven_sqlcharts_xarg_l', true), ENT_QUOTES, 'UTF-8'); | |
| 576 | + $yarg_l = html_entity_decode((string) get_post_meta($id, 'guaven_sqlcharts_yarg_l', true), ENT_QUOTES, 'UTF-8'); | |
| 498 | 577 | foreach ($fvs as $key => $value) { |
| 499 | 578 | $values[$value->$xarg_s] = $value->$yarg_s; |
| 500 | 579 | $labels[$value->$xarg_s] = '"' . $value->$xarg_s . '"'; |
| 501 | 580 | } |
| @@ -577,9 +656,9 @@ | ||
| 577 | 656 | if (count($varfield_arr)<3) continue; |
| 578 | 657 | $varfield_arr=array_map("trim",$varfield_arr); |
| 579 | 658 | if (!empty($_GET[$varfield_arr[0]])) { |
| 580 | 659 | // User-supplied input: no () bypass allowed — sanitize strictly |
| 581 | - $varreplacement = sanitize_text_field(wp_unslash($_GET[$varfield_arr[0]])); | |
| 660 | + $varreplacement = str_replace(';', '', sanitize_text_field(wp_unslash($_GET[$varfield_arr[0]]))); | |
| 582 | 661 | if (is_numeric($varreplacement)) { |
| 583 | 662 | $varreplacement = $varreplacement + 0; |
| 584 | 663 | } else { |
| 585 | 664 | $varreplacement = '"' . esc_sql($varreplacement) . '"'; |
| @@ -598,8 +677,14 @@ | ||
| 598 | 677 | } |
| 599 | 678 | |
| 600 | 679 | function gvn_chart_top_form($atts){ |
| 601 | 680 | if (get_post_meta($atts["id"],'guaven_sqlcharts_formpartrole',true)!='' and !is_user_logged_in()) return; |
| 681 | + // Inside the chart builder's live preview the filter inputs are rendered disabled and without a <form> | |
| 682 | + // or submit button: the preview sits inside WordPress's own post edit form, nested forms are dropped | |
| 683 | + // by the browser, and a filter named e.g. "post_type" would otherwise be submitted with the post and | |
| 684 | + // make WordPress stop with "A post type mismatch has been detected." (chart settings not saved). | |
| 685 | + $preview = !empty($GLOBALS['guaven_sqlcharts_admin_preview']); | |
| 686 | + $dis = $preview ? ' disabled' : ''; | |
| 602 | 687 | $topform='';$dateexists=false; |
| 603 | 688 | $variables_raw=get_post_meta($atts['id'],'guaven_sqlcharts_variables',true); |
| 604 | 689 | $variables_raw=explode("|",$variables_raw); |
| 605 | 690 | foreach ($variables_raw as $vrow){ |
| @@ -611,14 +696,14 @@ | ||
| 611 | 696 | if ($vrow_arr[3]=='date') { |
| 612 | 697 | $dateexists=true; |
| 613 | 698 | $topform.= '<span class="gvn-filter-field"><label>'.$vrow_arr[2].'</label> <input class="gws_datepicker" autocomplete="off" type="text" |
| 614 | 699 | value="'.$gvalue.'" |
| 615 | - data-toggle="datepicker" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'"></span> | |
| 700 | + data-toggle="datepicker" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'"'.$dis.'></span> | |
| 616 | 701 | ';} |
| 617 | 702 | else { |
| 618 | 703 | $topform.= '<span class="gvn-filter-field"><label>'.$vrow_arr[2].'</label> <input autocomplete="off" |
| 619 | 704 | type="'.$vrow_arr[3].'" |
| 620 | - value="'.$gvalue.'" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'"></span> | |
| 705 | + value="'.$gvalue.'" name="'.$vrow_arr[0].'" placeholder="'.$dvalue.'"'.$dis.'></span> | |
| 621 | 706 | '; |
| 622 | 707 | } |
| 623 | 708 | } |
| 624 | 709 | if (!empty($topform)) { |
| @@ -635,12 +720,14 @@ | ||
| 635 | 720 | 'class' => array(), |
| 636 | 721 | 'data-toggle'=>array(), |
| 637 | 722 | 'placeholder'=>array(), |
| 638 | 723 | 'autocomplete'=>array(), |
| 724 | + 'disabled'=>array(), | |
| 639 | 725 | 'style'=>[] |
| 640 | 726 | ), |
| 641 | 727 | 'span' => array('class' => array()), |
| 642 | 728 | 'label' => array(), |
| 729 | + 'div' => array('class' => array()), | |
| 643 | 730 | ); |
| 644 | 731 | |
| 645 | 732 | $submit_button_value = get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true) != '' |
| 646 | 733 | ? esc_attr(get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true)) |
| @@ -645,10 +732,14 @@ | ||
| 645 | 732 | $submit_button_value = get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true) != '' |
| 646 | 733 | ? esc_attr(get_post_meta($atts['id'], 'guaven_sqlcharts_formpartbutton', true)) |
| 647 | 734 | : 'OK'; |
| 648 | 735 | |
| 649 | - $topform = '<form method="get" action="" class="guaven_sqlcharts_form">' . $topform . ' | |
| 736 | + if ($preview) { | |
| 737 | + $topform = '<div class="guaven_sqlcharts_form">' . $topform . '<input type="submit" value="' . $submit_button_value . '" disabled></div>'; | |
| 738 | + } else { | |
| 739 | + $topform = '<form method="get" action="" class="guaven_sqlcharts_form">' . $topform . ' | |
| 650 | 740 | <input type="submit" value="' . $submit_button_value . '"></form>'; |
| 741 | + } | |
| 651 | 742 | |
| 652 | 743 | echo wp_kses($topform, $allowed_html); |
| 653 | 744 | } |
| 654 | 745 | } |
| @@ -673,8 +764,10 @@ | ||
| 673 | 764 | |
| 674 | 765 | function guaven_sqlcharts_local_shortcode($atts) { |
| 675 | 766 | if(empty($atts['id']))return 'ID is missing.'; |
| 676 | 767 | $atts['id']=intval($atts['id']); |
| 768 | + $post_g = get_post($atts['id']); | |
| 769 | + if (!$post_g or $post_g->post_type != 'gvn_schart') return 'Chart not found.'; | |
| 677 | 770 | $remote_host=get_post_meta($atts['id'], 'guaven_sqlcharts_dbhost', true); |
| 678 | 771 | if ($remote_host!=''){ |
| 679 | 772 | $remote_db=get_post_meta($atts['id'], 'guaven_sqlcharts_dbname', true); |
| 680 | 773 | $remote_login=get_post_meta($atts['id'], 'guaven_sqlcharts_dblogin', true); |
| @@ -691,29 +784,34 @@ | ||
| 691 | 784 | $GLOBALS["guaven_sqlcharts_atts"]=$atts; |
| 692 | 785 | |
| 693 | 786 | $sql = guaven_sqlcharts_get_code($atts['id']); |
| 694 | 787 | if(empty($sql))return 'SQL query is missing.'; |
| 695 | - $sql=gvn_chart_put_variables($sql,$atts['id']); | |
| 696 | 788 | |
| 789 | + // {arg1}..{arg19} come from shortcode attributes: [gvn_schart_2 id="1" arg1="41"]. | |
| 790 | + // Substituted directly (not via wpdb::prepare) so the same tag may appear any number of times, | |
| 791 | + // e.g. in every query of a ";"-separated comparison chart. Numbers are inserted as-is, anything | |
| 792 | + // else is escaped and quoted; a tag already wrapped in quotes ('{arg1}') is not double-quoted. | |
| 793 | + // ";" is removed from values because the finished SQL is split on ";" below. | |
| 794 | + for($i=1;$i<20;$i++){ | |
| 795 | + $tag = '{arg'.$i.'}'; | |
| 796 | + if (strpos($sql, $tag) === false) continue; | |
| 797 | + $replacearg = !empty($atts['arg'.$i]) ? $atts['arg'.$i] : 0; | |
| 798 | + if (is_numeric($replacearg)) $replacearg = $replacearg + 0; | |
| 799 | + else $replacearg = "'" . esc_sql(str_replace(';', '', sanitize_text_field((string) $replacearg))) . "'"; | |
| 800 | + $sql = str_replace(array("'".$tag."'", '"'.$tag.'"', $tag), $replacearg, $sql); | |
| 801 | + } | |
| 697 | 802 | |
| 803 | + $sql=gvn_chart_put_variables($sql,$atts['id']); | |
| 698 | 804 | $sql=apply_filters('guaven_sqlcharts_rendered_sql',$sql,$atts); |
| 699 | 805 | |
| 806 | + // command check on the final SQL, after every shortcode argument and filter value is in place | |
| 700 | 807 | $blacklister_f = gvn_chart_check_sql_query($sql); |
| 701 | 808 | if ($blacklister_f == 1)return 'You given SQL code contains forbidden commands. Remember that you should only use SELECT queries'; |
| 702 | 809 | $tip_g = guaven_sqlcharts_normalize_type(get_post_meta($atts['id'], 'guaven_sqlcharts_graphtype', true)); |
| 703 | 810 | |
| 704 | - for($i=1;$i<20;$i++){ | |
| 705 | - if(strpos($sql,"{arg".$i."}")!==false){ | |
| 706 | - $replacearg=!empty($atts["arg".$i])?$atts["arg".$i]:0; | |
| 707 | - $sql = str_replace("{arg".$i."}", "%s", $sql); | |
| 708 | - $sql=$wpdb->prepare($sql,$replacearg); | |
| 709 | - } | |
| 710 | - | |
| 711 | - } | |
| 712 | - | |
| 713 | 811 | $sql_split = explode(';', $sql); |
| 714 | 812 | $labels_and_values = array(); |
| 715 | - $post_g = get_post($atts['id']); | |
| 813 | + $labels = $values = $ylabel = $xlabel = array(); | |
| 716 | 814 | |
| 717 | 815 | global $sqlcharts_inserted_script; |
| 718 | 816 | ob_start(); |
| 719 | 817 | for ($i = 0; $i < count($sql_split); $i++) { |
| @@ -787,17 +885,30 @@ | ||
| 787 | 885 | if (!shortcode_exists('gvn_schart')) { |
| 788 | 886 | add_shortcode('gvn_schart', 'guaven_sqlcharts_local_shortcode'); |
| 789 | 887 | } |
| 790 | 888 | |
| 889 | +// [gvn_schart_2_cached id="1" expire="3600" arg1=".."] – same as gvn_schart_2 but the output is kept in a | |
| 890 | +// transient. All other attributes (argN, width, height, table, params) are passed through, and each | |
| 891 | +// distinct set of attributes gets its own cache entry. Append ?force_sql_cache_reload to the URL to bypass. | |
| 791 | 892 | add_shortcode("gvn_schart_2_cached",function($atts){ |
| 792 | 893 | if(empty($atts["id"]))return; |
| 793 | 894 | $atts["id"]=intval($atts["id"]); |
| 794 | - $is_logged_in=is_user_logged_in()?'':'_guest'; | |
| 795 | 895 | $expire=!empty($atts["expire"])?intval($atts["expire"]):3600; |
| 796 | - $cached=get_transient('cached_sql_charts_'.$atts["id"].$is_logged_in); | |
| 896 | + $inner_atts=$atts; | |
| 897 | + unset($inner_atts['expire']); | |
| 898 | + // One cache entry per user (charts may use {current_user_*} tags), per set of shortcode attributes | |
| 899 | + // and per value of every dynamic filter this chart reads from the URL. A visitor can therefore | |
| 900 | + // never be served, or pre-seed, a result computed for someone else or for other filter values. | |
| 901 | + $key_parts = array('atts' => $inner_atts, 'user' => is_user_logged_in() ? get_current_user_id() : 0, 'get' => array()); | |
| 902 | + foreach (explode('|', (string) get_post_meta($atts['id'], 'guaven_sqlcharts_variables', true)) as $vrow) { | |
| 903 | + $vname = trim(current(explode('~', $vrow))); | |
| 904 | + if ($vname !== '' and isset($_GET[$vname])) $key_parts['get'][$vname] = sanitize_text_field(wp_unslash($_GET[$vname])); | |
| 905 | + } | |
| 906 | + $key = 'cached_sql_charts_' . $atts["id"] . '_' . md5(serialize($key_parts)); | |
| 907 | + $cached=get_transient($key); | |
| 797 | 908 | if(!empty($cached) and !isset($_GET["force_sql_cache_reload"]) )return $cached; |
| 798 | - $tobecached=do_shortcode('[gvn_schart_2 id="'.$atts["id"].'"]'); | |
| 799 | - set_transient('cached_sql_charts_'.$atts["id"].$is_logged_in, $tobecached,$expire);//you can change 3600 yourself | |
| 909 | + $tobecached=guaven_sqlcharts_local_shortcode($inner_atts); | |
| 910 | + set_transient($key, $tobecached,$expire); | |
| 800 | 911 | return $tobecached; |
| 801 | 912 | }); |
| 802 | 913 | |
| 803 | 914 | // fixed, colorblind-friendly default palette (Tableau 10) used when no custom colors are set |
| @@ -827,16 +938,86 @@ | ||
| 827 | 938 | $h = !empty($atts['height']) ? $atts['height'] : get_post_meta($pid, 'guaven_sqlcharts_chartheight', true); |
| 828 | 939 | return $h != '' ? 'maintainAspectRatio: false,' : ''; |
| 829 | 940 | } |
| 830 | 941 | |
| 942 | +// outputs 'showAllTooltips: true,' when "Value labels" is checked; the values are drawn by the | |
| 943 | +// gvnShowAllValues plugin in asset/front.js (works for every chart type) | |
| 944 | +function guaven_sqlcharts_value_labels($pid){ | |
| 945 | + return get_post_meta($pid, 'guaven_sqlcharts_forcetooltips', true) != '' ? 'showAllTooltips: true,' : ''; | |
| 946 | +} | |
| 947 | + | |
| 948 | +// Chart.js scale title block built from the "X axis label" / "Y axis label" fields. | |
| 949 | +// $which is 'x' or 'y' (the *field* to use, not the scale). The Y label is only used as an axis | |
| 950 | +// title for single-series charts; with several ";"-separated series the legend names them instead. | |
| 951 | +function guaven_sqlcharts_axis_title($pid, $which){ | |
| 952 | + $key = $which == 'x' ? 'guaven_sqlcharts_xarg_l' : 'guaven_sqlcharts_yarg_l'; | |
| 953 | + $text = trim(html_entity_decode((string) get_post_meta($pid, $key, true), ENT_QUOTES, 'UTF-8')); | |
| 954 | + if ($text === '' or ($which == 'y' and strpos($text, ';') !== false)) return ''; | |
| 955 | + return 'title: {display: true, text: ' . wp_json_encode($text) . '},'; | |
| 956 | +} | |
| 957 | + | |
| 958 | +// "params" shortcode attribute: extra Chart.js dataset options, e.g. params="borderWidth: 3, borderDash: [5,5],". | |
| 959 | +// The text is placed inside the inline <script>, so only a conservative character set is accepted: | |
| 960 | +// no parentheses, semicolons, "=", "<", ">", "/", "\\", "+" or backticks, which rules out executable JavaScript. | |
| 961 | +function guaven_sqlcharts_dataset_params(){ | |
| 962 | + $params = isset($GLOBALS["guaven_sqlcharts_atts"]["params"]) ? (string) $GLOBALS["guaven_sqlcharts_atts"]["params"] : ''; | |
| 963 | + if ($params === '' or !preg_match('/^[A-Za-z0-9_\s,:.\'"#%\-\[\]{}]+$/', $params)) return ''; | |
| 964 | + return $params; | |
| 965 | +} | |
| 966 | + | |
| 967 | +// dataset label as a safe JS string literal (labels saved before 3.0.1 may hold HTML entities) | |
| 968 | +function guaven_sqlcharts_js_label($label){ | |
| 969 | + return wp_json_encode(html_entity_decode((string) $label, ENT_QUOTES, 'UTF-8')); | |
| 970 | +} | |
| 971 | + | |
| 972 | +// Parses an X value for the "time axis" option. Accepts YYYY, YYYY-MM, YYYY-MM-DD, optionally followed | |
| 973 | +// by HH:MM or HH:MM:SS. Returns a UTC timestamp in milliseconds, or false when the value is not a date. | |
| 974 | +function guaven_sqlcharts_parse_date($str){ | |
| 975 | + $str = trim((string) $str); | |
| 976 | + if (!preg_match('/^(\d{4})(?:-(\d{1,2})(?:-(\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?)?)?$/', $str, $m)) return false; | |
| 977 | + $y = (int) $m[1]; $mo = isset($m[2]) ? (int) $m[2] : 1; $d = isset($m[3]) ? (int) $m[3] : 1; | |
| 978 | + $h = isset($m[4]) ? (int) $m[4] : 0; $mi = isset($m[5]) ? (int) $m[5] : 0; $sec = isset($m[6]) ? (int) $m[6] : 0; | |
| 979 | + if (!checkdate($mo, $d, $y) or $h > 23 or $mi > 59 or $sec > 59) return false; | |
| 980 | + return gmmktime($h, $mi, $sec, $mo, $d, $y) * 1000; | |
| 981 | +} | |
| 982 | + | |
| 983 | +// "Scale X axis by date/time" option. Returns, per dataset, a list of "{x:<ms>,y:<value>}" JS point | |
| 984 | +// literals when the option is on and every X value is a date; false otherwise (normal category axis). | |
| 985 | +function guaven_sqlcharts_time_axis_points($pid, $values){ | |
| 986 | + if (get_post_meta($pid, 'guaven_sqlcharts_timeaxis', true) != 1) return false; | |
| 987 | + $out = array(); | |
| 988 | + $has_point = false; | |
| 989 | + foreach ($values as $key_ak => $series) { | |
| 990 | + $out[$key_ak] = array(); | |
| 991 | + foreach ($series as $x => $y) { | |
| 992 | + $ts = guaven_sqlcharts_parse_date($x); | |
| 993 | + if ($ts === false) return false; | |
| 994 | + $out[$key_ak][] = '{x:' . $ts . ',y:' . (is_numeric($y) ? $y + 0 : 'null') . '}'; | |
| 995 | + $has_point = true; | |
| 996 | + } | |
| 997 | + } | |
| 998 | + return $has_point ? $out : false; | |
| 999 | +} | |
| 1000 | + | |
| 1001 | +// X scale options for time-axis mode (globals from asset/front.js): gvnSqlChartsTimeTicks replaces the evenly | |
| 1002 | +// spaced ticks Chart.js generates on a linear scale with the actual data dates, gvnSqlChartsTimeTick formats them | |
| 1003 | +function guaven_sqlcharts_time_axis_scale(){ | |
| 1004 | + return "type: 'linear', offset: true, afterBuildTicks: gvnSqlChartsTimeTicks, ticks: {callback: gvnSqlChartsTimeTick, maxRotation: 45, autoSkip: true},"; | |
| 1005 | +} | |
| 1006 | +// extra entry for the Chart.js "plugins" object in time-axis mode (tooltip title shown as a date) | |
| 1007 | +function guaven_sqlcharts_time_axis_plugins($time_points){ | |
| 1008 | + return $time_points !== false ? 'tooltip: {callbacks: {title: gvnSqlChartsTimeTooltipTitle}}' : ''; | |
| 1009 | +} | |
| 1010 | + | |
| 831 | 1011 | function guaven_sqlcharts_bardata($title, $labels, $values, $ylabel, $type = 'bar', $pid = null) |
| 832 | 1012 | { |
| 833 | 1013 | $horizontal = ($type == 'horizontalBar'); |
| 834 | 1014 | $forcestack = ($type == 'stackedBar'); |
| 835 | 1015 | $stacked = ($forcestack or get_post_meta($pid, 'guaven_sqlcharts_nostacked', true) != 1) ? 'true' : 'false'; |
| 1016 | + $time_points = $horizontal ? false : guaven_sqlcharts_time_axis_points($pid, $values); | |
| 836 | 1017 | ?> |
| 837 | 1018 | var data = { |
| 838 | - labels: [<?php guaven_sqlcharts_merge_labeldata($labels);?>], | |
| 1019 | + <?php if ($time_points === false) { ?>labels: [<?php guaven_sqlcharts_merge_labeldata($labels);?>],<?php } ?> | |
| 839 | 1020 | datasets: [ |
| 840 | 1021 | <?php |
| 841 | 1022 | $values_new=guaven_sqlcharts_key_normalizer($values,$labels,$ylabel)[0]; |
| 842 | 1023 | $i=-1; |
| @@ -841,32 +1022,29 @@ | ||
| 841 | 1022 | $values_new=guaven_sqlcharts_key_normalizer($values,$labels,$ylabel)[0]; |
| 842 | 1023 | $i=-1; |
| 843 | 1024 | foreach ($values_new as $key_ak=>$value_ak) { |
| 844 | 1025 | $i++; |
| 1026 | + $points = $time_points !== false ? $time_points[$key_ak] : $values_new[$key_ak]; | |
| 845 | 1027 | ?> |
| 846 | 1028 | { |
| 847 | 1029 | <?php |
| 848 | - if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){ | |
| 849 | - //passing chartJS params via the shortcode | |
| 850 | - echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]); | |
| 851 | - } | |
| 1030 | + echo guaven_sqlcharts_dataset_params(); // "params" shortcode attribute (validated) | |
| 852 | 1031 | ?> |
| 853 | - label: "<?php | |
| 854 | - echo wp_kses($ylabel[$key_ak],[]); | |
| 855 | -?>", | |
| 1032 | + label: <?php echo guaven_sqlcharts_js_label($ylabel[$key_ak]); ?>, | |
| 856 | 1033 | backgroundColor: [ |
| 857 | 1034 | <?php |
| 858 | - echo wp_kses(guaven_sqlcharts_colorgenerator(count($values_new[$key_ak]), 0, 0, guaven_sqlcharts_colors($i, $pid)),[]); | |
| 1035 | + echo wp_kses(guaven_sqlcharts_colorgenerator(count($points), 0, 0, guaven_sqlcharts_colors($i, $pid)),[]); | |
| 859 | 1036 | ?> |
| 860 | 1037 | ], |
| 861 | 1038 | borderColor: [ |
| 862 | 1039 | <?php |
| 863 | - echo wp_kses(guaven_sqlcharts_colorgenerator(count($values_new[$key_ak]), 0, 0.2, guaven_sqlcharts_colors($i, $pid)),[]); | |
| 1040 | + echo wp_kses(guaven_sqlcharts_colorgenerator(count($points), 0, 0.2, guaven_sqlcharts_colors($i, $pid)),[]); | |
| 864 | 1041 | ?> |
| 865 | 1042 | ], |
| 866 | 1043 | borderWidth: 1, |
| 1044 | + <?php if ($time_points !== false) echo 'barThickness: 24,'; // fixed width: on a time axis Chart.js would otherwise size bars from the closest pair of dates ?> | |
| 867 | 1045 | data: [<?php |
| 868 | - echo wp_kses(implode(",", $values_new[$key_ak]),[]); | |
| 1046 | + echo wp_kses(implode(",", $points),[]); | |
| 869 | 1047 | ?>], |
| 870 | 1048 | }, |
| 871 | 1049 | <?php |
| 872 | 1050 | } |
| @@ -875,15 +1053,19 @@ | ||
| 875 | 1053 | }; |
| 876 | 1054 | var options={ |
| 877 | 1055 | responsive: true, |
| 878 | 1056 | <?php echo wp_kses(guaven_sqlcharts_mar($pid),[]); ?> |
| 1057 | + <?php echo wp_kses(guaven_sqlcharts_value_labels($pid),[]); ?> | |
| 879 | 1058 | <?php if ($horizontal) echo "indexAxis: 'y',"; ?> |
| 880 | 1059 | scales: { |
| 881 | 1060 | x: { |
| 1061 | + <?php if ($time_points !== false) echo guaven_sqlcharts_time_axis_scale(); ?> | |
| 1062 | + <?php echo guaven_sqlcharts_axis_title($pid, $horizontal ? 'y' : 'x'); ?> | |
| 882 | 1063 | stacked: <?php echo esc_js($stacked); ?>, |
| 883 | 1064 | beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?> |
| 884 | 1065 | }, |
| 885 | 1066 | y: { |
| 1067 | + <?php echo guaven_sqlcharts_axis_title($pid, $horizontal ? 'x' : 'y'); ?> | |
| 886 | 1068 | stacked: <?php echo esc_js($stacked); ?>, |
| 887 | 1069 | beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>, |
| 888 | 1070 | ticks: { |
| 889 | 1071 | <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?> |
| @@ -890,9 +1072,9 @@ | ||
| 890 | 1072 | } |
| 891 | 1073 | } |
| 892 | 1074 | } |
| 893 | 1075 | <?php |
| 894 | - guaven_sqlcharts_maybe_additional_parameters($pid); | |
| 1076 | + guaven_sqlcharts_maybe_additional_parameters($pid, guaven_sqlcharts_time_axis_plugins($time_points)); | |
| 895 | 1077 | ?> |
| 896 | 1078 | }; |
| 897 | 1079 | var myBarChart = new Chart(ctx, { |
| 898 | 1080 | type: 'bar', |
| @@ -912,11 +1094,12 @@ | ||
| 912 | 1094 | } |
| 913 | 1095 | |
| 914 | 1096 | function guaven_sqlcharts_linedata($title, $labels, $values, $ylabel, $type = 'false', $pid = null, $charttype = 'line', $stepped = false) |
| 915 | 1097 | { |
| 1098 | + $time_points = ($charttype == 'radar') ? false : guaven_sqlcharts_time_axis_points($pid, $values); | |
| 916 | 1099 | ?> |
| 917 | 1100 | var data = { |
| 918 | - labels: [<?php guaven_sqlcharts_merge_labeldata($labels);?>], | |
| 1101 | + <?php if ($time_points === false) { ?>labels: [<?php guaven_sqlcharts_merge_labeldata($labels);?>],<?php } ?> | |
| 919 | 1102 | datasets: [ |
| 920 | 1103 | <?php |
| 921 | 1104 | $values_new=guaven_sqlcharts_key_normalizer($values,$labels,$ylabel)[0]; |
| 922 | 1105 | $dataset_count=count($values_new); |
| @@ -922,8 +1105,9 @@ | ||
| 922 | 1105 | $dataset_count=count($values_new); |
| 923 | 1106 | $i=-1; |
| 924 | 1107 | foreach ($values_new as $key_ak=>$value_ak) { |
| 925 | 1108 | $i++; |
| 1109 | + $points = $time_points !== false ? $time_points[$key_ak] : $values_new[$key_ak]; | |
| 926 | 1110 | if ($type == 'radarfill') $fill = "'origin'"; |
| 927 | 1111 | elseif ($type == 'false') $fill = 'false'; |
| 928 | 1112 | else $fill = ($i == 0 and $dataset_count > 1) ? '"+1"' : '"origin"'; |
| 929 | 1113 | ?> |
| @@ -928,16 +1112,11 @@ | ||
| 928 | 1112 | else $fill = ($i == 0 and $dataset_count > 1) ? '"+1"' : '"origin"'; |
| 929 | 1113 | ?> |
| 930 | 1114 | { |
| 931 | 1115 | <?php |
| 932 | - if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){ | |
| 933 | - //passing chartJS params via the shortcode | |
| 934 | - echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]); | |
| 935 | - } | |
| 1116 | + echo guaven_sqlcharts_dataset_params(); // "params" shortcode attribute (validated) | |
| 936 | 1117 | ?> |
| 937 | - label: "<?php | |
| 938 | - echo esc_attr($ylabel[$key_ak]); | |
| 939 | -?>", | |
| 1118 | + label: <?php echo guaven_sqlcharts_js_label($ylabel[$key_ak]); ?>, | |
| 940 | 1119 | fill: <?php echo wp_kses($fill,[]); |
| 941 | 1120 | ?>, |
| 942 | 1121 | tension: 0.1, |
| 943 | 1122 | <?php if ($stepped) echo 'stepped: true,'; ?> |
| @@ -956,9 +1135,9 @@ | ||
| 956 | 1135 | pointHoverBorderColor: <?php |
| 957 | 1136 | echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid))); |
| 958 | 1137 | ?> |
| 959 | 1138 | data: [<?php |
| 960 | - echo wp_kses_post(implode(",", $values_new[$key_ak])); | |
| 1139 | + echo wp_kses_post(implode(",", $points)); | |
| 961 | 1140 | ?>], |
| 962 | 1141 | spanGaps: false, |
| 963 | 1142 | }, |
| 964 | 1143 | <?php |
| @@ -971,8 +1150,9 @@ | ||
| 971 | 1150 | data: data, |
| 972 | 1151 | options: { |
| 973 | 1152 | responsive: true, |
| 974 | 1153 | <?php echo wp_kses(guaven_sqlcharts_mar($pid),[]); ?> |
| 1154 | + <?php echo wp_kses(guaven_sqlcharts_value_labels($pid),[]); ?> | |
| 975 | 1155 | <?php if ($charttype == 'radar') { ?> |
| 976 | 1156 | scales: { |
| 977 | 1157 | r: { |
| 978 | 1158 | beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?> |
| @@ -981,11 +1161,14 @@ | ||
| 981 | 1161 | <?php } else { ?> |
| 982 | 1162 | scales: { |
| 983 | 1163 | x: { |
| 984 | 1164 | display: true, |
| 1165 | + <?php if ($time_points !== false) echo guaven_sqlcharts_time_axis_scale(); ?> | |
| 1166 | + <?php echo guaven_sqlcharts_axis_title($pid, 'x'); ?> | |
| 985 | 1167 | beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?> |
| 986 | 1168 | }, |
| 987 | 1169 | y: { |
| 1170 | + <?php echo guaven_sqlcharts_axis_title($pid, 'y'); ?> | |
| 988 | 1171 | beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>, |
| 989 | 1172 | ticks: { |
| 990 | 1173 | <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?> |
| 991 | 1174 | } |
| @@ -992,9 +1175,9 @@ | ||
| 992 | 1175 | } |
| 993 | 1176 | } |
| 994 | 1177 | <?php } ?> |
| 995 | 1178 | <?php |
| 996 | - guaven_sqlcharts_maybe_additional_parameters($pid); | |
| 1179 | + guaven_sqlcharts_maybe_additional_parameters($pid, guaven_sqlcharts_time_axis_plugins($time_points)); | |
| 997 | 1180 | ?> |
| 998 | 1181 | |
| 999 | 1182 | } |
| 1000 | 1183 | }); |
| @@ -1018,14 +1201,11 @@ | ||
| 1018 | 1201 | } |
| 1019 | 1202 | ?> |
| 1020 | 1203 | { |
| 1021 | 1204 | <?php |
| 1022 | - if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){ | |
| 1023 | - //passing chartJS params via the shortcode | |
| 1024 | - echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]); | |
| 1025 | - } | |
| 1205 | + echo guaven_sqlcharts_dataset_params(); // "params" shortcode attribute (validated) | |
| 1026 | 1206 | ?> |
| 1027 | - label: "<?php echo esc_attr(isset($ylabel[$key_ak])?$ylabel[$key_ak]:''); ?>", | |
| 1207 | + label: <?php echo guaven_sqlcharts_js_label(isset($ylabel[$key_ak])?$ylabel[$key_ak]:''); ?>, | |
| 1028 | 1208 | backgroundColor: <?php |
| 1029 | 1209 | echo wp_kses_post(guaven_sqlcharts_colorgenerator(1, 1, 0.2, guaven_sqlcharts_colors($i, $pid))); |
| 1030 | 1210 | ?> |
| 1031 | 1211 | borderColor: <?php |
| @@ -1043,13 +1223,16 @@ | ||
| 1043 | 1223 | data: data, |
| 1044 | 1224 | options: { |
| 1045 | 1225 | responsive: true, |
| 1046 | 1226 | <?php echo wp_kses(guaven_sqlcharts_mar($pid),[]); ?> |
| 1227 | + <?php echo wp_kses(guaven_sqlcharts_value_labels($pid),[]); ?> | |
| 1047 | 1228 | scales: { |
| 1048 | 1229 | x: { |
| 1230 | + <?php echo guaven_sqlcharts_axis_title($pid, 'x'); ?> | |
| 1049 | 1231 | beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_x', true) == 1) ? 'true':'false'; ?> |
| 1050 | 1232 | }, |
| 1051 | 1233 | y: { |
| 1234 | + <?php echo guaven_sqlcharts_axis_title($pid, 'y'); ?> | |
| 1052 | 1235 | beginAtZero: <?php echo (get_post_meta($pid, 'guaven_sqlcharts_begin_with_0_y', true) == 1) ? 'true':'false'; ?>, |
| 1053 | 1236 | ticks: { |
| 1054 | 1237 | <?php if(get_post_meta($pid, 'guaven_sqlcharts_round_y_values', true) == 1) echo 'precision: 0,'; ?> |
| 1055 | 1238 | } |
| @@ -1063,9 +1246,9 @@ | ||
| 1063 | 1246 | <?php |
| 1064 | 1247 | } |
| 1065 | 1248 | |
| 1066 | 1249 | |
| 1067 | -function guaven_sqlcharts_maybe_additional_parameters($pid){ | |
| 1250 | +function guaven_sqlcharts_maybe_additional_parameters($pid, $extra_plugins = ''){ | |
| 1068 | 1251 | if(function_exists('guaven_sqlcharts_maybe_additional_parameters_custom')){ |
| 1069 | 1252 | wp_kses(guaven_sqlcharts_maybe_additional_parameters_custom($pid),[]); |
| 1070 | 1253 | return; |
| 1071 | 1254 | } |
| @@ -1075,9 +1258,9 @@ | ||
| 1075 | 1258 | } |
| 1076 | 1259 | else { |
| 1077 | 1260 | $display='false';$position='top'; |
| 1078 | 1261 | } |
| 1079 | - echo wp_kses( ",plugins: {legend: {display: ".$display.",position:'".$position."'}}",[]); | |
| 1262 | + echo wp_kses( ",plugins: {legend: {display: ".$display.",position:'".$position."'}".($extra_plugins !== '' ? ','.$extra_plugins : '')."}",[]); | |
| 1080 | 1263 | } |
| 1081 | 1264 | |
| 1082 | 1265 | |
| 1083 | 1266 | |
| @@ -1085,9 +1268,9 @@ | ||
| 1085 | 1268 | function guaven_sqlcharts_piedata($title, $labels, $values, $ylabel, $pid, $type = 'pie') |
| 1086 | 1269 | { |
| 1087 | 1270 | ?> |
| 1088 | 1271 | var options={ |
| 1089 | - <?php if(get_post_meta($pid,'guaven_sqlcharts_forcetooltips',true)!='') echo 'showAllTooltips: true,'.PHP_EOL; ?> | |
| 1272 | + <?php echo wp_kses(guaven_sqlcharts_value_labels($pid),[]); ?> | |
| 1090 | 1273 | responsive: true |
| 1091 | 1274 | <?php echo get_post_meta($pid,'guaven_sqlcharts_chartheight',true)!=''||!empty($GLOBALS["guaven_sqlcharts_atts"]['height'])?',maintainAspectRatio: false':''; ?> |
| 1092 | 1275 | <?php |
| 1093 | 1276 | guaven_sqlcharts_maybe_additional_parameters($pid); |
| @@ -1100,12 +1283,9 @@ | ||
| 1100 | 1283 | for ($i = 0; $i < count($values); $i++) { |
| 1101 | 1284 | ?> |
| 1102 | 1285 | { |
| 1103 | 1286 | <?php |
| 1104 | - if(!empty($GLOBALS["guaven_sqlcharts_atts"]["params"])){ | |
| 1105 | - //passing chartJS params via the shortcode | |
| 1106 | - echo wp_kses($GLOBALS["guaven_sqlcharts_atts"]["params"],[]); | |
| 1107 | - } | |
| 1287 | + echo guaven_sqlcharts_dataset_params(); // "params" shortcode attribute (validated) | |
| 1108 | 1288 | ?> |
| 1109 | 1289 | data: [<?php |
| 1110 | 1290 | echo wp_kses(implode(",", $values[$i]),[]); |
| 1111 | 1291 | ?>], |