-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathBlock.php
More file actions
866 lines (759 loc) · 27.8 KB
/
Copy pathBlock.php
File metadata and controls
866 lines (759 loc) · 27.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
<?php
// +----------------------------------------------------------------------+
// | Copyright 2018 ThemeIsle (email : friends@themeisle.com) |
// +----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License, version 2, as |
// | published by the Free Software Foundation. |
// | |
// | This program is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
// | GNU General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software |
// | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, |
// | MA 02110-1301 USA |
// +----------------------------------------------------------------------+
// | Author: Hardeep Asrani <hardeep@themeisle.com> |
// +----------------------------------------------------------------------+
/**
* All the Gutenberg block related code.
*
* @category Visualizer
* @package Gutenberg
*
* @since 3.1.0
*/
class Visualizer_Gutenberg_Block {
/**
* A reference to an instance of this class.
*
* @var Visualizer_Gutenberg_Block The one Visualizer_Gutenberg_Block instance.
*/
private static $instance;
/**
* Visualizer plugin version.
*
* @var string $version The current version of the plugin.
*/
protected $version;
/**
* Returns an instance of this class.
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new Visualizer_Gutenberg_Block();
}
return self::$instance;
}
/**
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->version = Visualizer_Plugin::VERSION;
add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_gutenberg_scripts' ) );
add_action( 'init', array( $this, 'register_block_type' ) );
add_action( 'rest_api_init', array( $this, 'register_rest_endpoints' ) );
add_filter( 'rest_visualizer_query', array( $this, 'add_rest_query_vars' ), 9, 2 );
}
/**
* Enqueue front end and editor JavaScript and CSS
*/
public function enqueue_gutenberg_scripts() {
global $wp_version, $pagenow;
$blockPath = VISUALIZER_ABSURL . 'classes/Visualizer/Gutenberg/build/block.js';
$handsontableJS = VISUALIZER_ABSURL . 'classes/Visualizer/Gutenberg/build/handsontable.js';
$stylePath = VISUALIZER_ABSURL . 'classes/Visualizer/Gutenberg/build/block.css';
$handsontableCSS = VISUALIZER_ABSURL . 'classes/Visualizer/Gutenberg/build/handsontable.css';
if ( VISUALIZER_TEST_JS_CUSTOMIZATION ) {
$version = filemtime( VISUALIZER_ABSPATH . '/classes/Visualizer/Gutenberg/build/block.js' );
} else {
$version = $this->version;
}
if ( ! wp_script_is( 'visualizer-datatables', 'registered' ) ) {
wp_register_script( 'visualizer-datatables', VISUALIZER_ABSURL . 'js/lib/datatables.min.js', array( 'jquery-ui-core' ), Visualizer_Plugin::VERSION );
}
if ( ! wp_style_is( 'visualizer-datatables', 'registered' ) ) {
wp_register_style( 'visualizer-datatables', VISUALIZER_ABSURL . 'css/lib/datatables.min.css', array(), Visualizer_Plugin::VERSION );
}
// Enqueue the bundled block JS file
wp_enqueue_script( 'handsontable', $handsontableJS );
wp_enqueue_script( 'visualizer-gutenberg-block', $blockPath, array( 'wp-api', 'handsontable', 'visualizer-datatables', 'moment', 'lodash' ), $version, true );
$type = 'community';
if ( Visualizer_Module::is_pro() ) {
$type = 'pro';
if ( apply_filters( 'visualizer_is_business', false ) ) {
$type = 'business';
}
}
$table_col_mapping = Visualizer_Source_Query_Params::get_all_db_tables_column_mapping( null, false );
$translation_array = array(
'isPro' => $type,
'proTeaser' => tsdk_utmify( Visualizer_Plugin::PRO_TEASER_URL, 'blockupsell'),
'absurl' => VISUALIZER_ABSURL,
'charts' => Visualizer_Module_Admin::_getChartTypesLocalized(),
'adminPage' => menu_page_url( 'visualizer', false ),
'createChart' => add_query_arg( array( 'action' => 'visualizer-create-chart', 'library' => 'yes', 'type' => '', 'chart-library' => '', 'tab' => 'visualizer' ), admin_url( 'admin-ajax.php' ) ),
'sqlTable' => $table_col_mapping,
'chartsPerPage' => defined( 'TI_CYPRESS_TESTING' ) ? 20 : 6,
'proFeaturesLocked' => Visualizer_Module_Admin::proFeaturesLocked(),
'isFullSiteEditor' => 'site-editor.php' === $pagenow,
'legacyBlockEdit' => apply_filters( 'visualizer_legacy_block_edit', false ),
/* translators: %1$s: opening tag, %2$s: closing tag */
'blockEditDoc' => sprintf( __( 'The editor for managing chart settings has been removed from the block editor. You can find more information in this %1$sdocumentation%2$s', 'visualizer' ), '<a href="https://docs.themeisle.com/article/1705-how-can-i-display-a-chart#using-visualizer-block" target="_blank">', '</a>' ),
'chartEditUrl' => admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'visualizer-gutenberg-block', 'visualizerLocalize', $translation_array );
// Enqueue frontend and editor block styles
wp_enqueue_style( 'handsontable', $handsontableCSS );
wp_enqueue_style( 'visualizer-gutenberg-block', $stylePath, array( 'visualizer-datatables' ), $version );
if ( version_compare( $wp_version, '4.9.0', '>' ) ) {
wp_enqueue_code_editor(
array(
'type' => 'sql',
'codemirror' => array(
'autofocus' => true,
'lineWrapping' => true,
'dragDrop' => false,
'matchBrackets' => true,
'autoCloseBrackets' => true,
'extraKeys' => array( 'Shift-Space' => 'autocomplete' ),
'hintOptions' => array( 'tables' => $table_col_mapping ),
),
)
);
}
}
/**
* Hook server side rendering into render callback
*/
public function register_block_type() {
register_block_type(
'visualizer/chart', array(
'render_callback' => array( $this, 'gutenberg_block_callback' ),
'attributes' => array(
'id' => array(
'type' => 'number',
),
'lazy' => array(
'type' => 'string',
),
),
)
);
}
/**
* Gutenberg Block Callback Function
*/
public function gutenberg_block_callback( $atts ) {
// no id, no fun.
if ( ! isset( $atts['id'] ) ) {
return '';
}
$atts = shortcode_atts(
array(
'id' => false,
'lazy' => apply_filters( 'visualizer_lazy_by_default', false, $atts['id'] ),
// we are deliberating excluding the class attribute from here
// as this will be handled by the custom class in Gutenberg
),
$atts
);
// no id, no fun.
if ( ! $atts['id'] ) {
return '';
}
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
if ( $atts['lazy'] == -1 || $atts['lazy'] == false ) {
$atts['lazy'] = 'no';
}
// we don't want the chart in the editor lazy-loading.
if ( is_admin() ) {
unset( $atts['lazy'] );
}
$shortcode = '[visualizer';
foreach ( $atts as $name => $value ) {
$shortcode .= sprintf( ' %s="%s"', $name, $value );
}
$shortcode .= ']';
return $shortcode;
}
/**
* Hook server side rendering into render callback
*/
public function register_rest_endpoints() {
register_rest_field(
'visualizer',
'chart_data',
array(
'get_callback' => array( $this, 'get_visualizer_data' ),
)
);
register_rest_route(
'visualizer/v' . VISUALIZER_REST_VERSION,
'/get-query-data',
array(
'methods' => 'GET',
'callback' => array( $this, 'get_query_data' ),
'permission_callback' => function () {
return current_user_can( 'edit_posts' );
},
)
);
register_rest_route(
'visualizer/v' . VISUALIZER_REST_VERSION,
'/get-json-root',
array(
'methods' => 'GET',
'callback' => array( $this, 'get_json_root_data' ),
'args' => array(
'url' => array(
'sanitize_callback' => 'esc_url_raw',
),
),
'permission_callback' => function () {
return current_user_can( 'edit_posts' );
},
)
);
register_rest_route(
'visualizer/v' . VISUALIZER_REST_VERSION,
'/get-json-data',
array(
'methods' => 'GET',
'callback' => array( $this, 'get_json_data' ),
'args' => array(
'url' => array(
'sanitize_callback' => 'esc_url_raw',
),
'chart' => array(
'sanitize_callback' => 'absint',
),
),
'permission_callback' => function () {
return current_user_can( 'edit_posts' );
},
)
);
register_rest_route(
'visualizer/v' . VISUALIZER_REST_VERSION,
'/set-json-data',
array(
'methods' => 'GET',
'callback' => array( $this, 'set_json_data' ),
'args' => array(
'url' => array(
'sanitize_callback' => 'esc_url_raw',
),
),
'permission_callback' => function () {
return current_user_can( 'edit_posts' );
},
)
);
register_rest_route(
'visualizer/v' . VISUALIZER_REST_VERSION,
'/update-chart',
array(
'methods' => 'POST',
'callback' => array( $this, 'update_chart_data' ),
'args' => array(
'id' => array(
'sanitize_callback' => 'absint',
),
),
'permission_callback' => function () {
return current_user_can( 'edit_posts' );
},
)
);
register_rest_route(
'visualizer/v' . VISUALIZER_REST_VERSION,
'/upload-data',
array(
'methods' => 'POST',
'callback' => array( $this, 'upload_csv_data' ),
'args' => array(
'url' => array(
'sanitize_callback' => 'esc_url_raw',
),
),
'permission_callback' => function () {
return current_user_can( 'edit_posts' );
},
)
);
register_rest_route(
'visualizer/v' . VISUALIZER_REST_VERSION,
'/get-permission-data',
array(
'methods' => 'GET',
'callback' => array( $this, 'get_permission_data' ),
'args' => array(
'type' => array(
'sanitize_callback' => 'sanitize_text_field',
),
),
'permission_callback' => function () {
return current_user_can( 'edit_posts' );
},
)
);
}
/**
* Get Post Meta Fields
*/
public function get_visualizer_data( $post ) {
if ( ! current_user_can( 'edit_posts' ) ) {
return false;
}
$data = array();
$post_id = $post['id'];
$data['visualizer-chart-type'] = get_post_meta( $post_id, Visualizer_Plugin::CF_CHART_TYPE, true );
$library = get_post_meta( $post_id, Visualizer_Plugin::CF_CHART_LIBRARY, true );
$data['visualizer-chart-library'] = $library;
$data['visualizer-source'] = get_post_meta( $post_id, Visualizer_Plugin::CF_SOURCE, true );
$data['visualizer-default-data'] = get_post_meta( $post_id, Visualizer_Plugin::CF_DEFAULT_DATA, true );
// faetch and update settings
$data['visualizer-settings'] = get_post_meta( $post_id, Visualizer_Plugin::CF_SETTINGS, true );
if ( empty( $data['visualizer-settings']['pagination'] ) ) {
$data['visualizer-settings']['pageSize'] = '';
}
// handle series filter hooks
$data['visualizer-series'] = apply_filters( Visualizer_Plugin::FILTER_GET_CHART_SERIES, get_post_meta( $post_id, Visualizer_Plugin::CF_SERIES, true ), $post_id, $data['visualizer-chart-type'] );
// handle settings filter hooks
$data['visualizer-settings'] = apply_filters( Visualizer_Plugin::FILTER_GET_CHART_SETTINGS, $data['visualizer-settings'], $post_id, $data['visualizer-chart-type'] );
// handle data filter hooks
$data['visualizer-data'] = apply_filters( Visualizer_Plugin::FILTER_GET_CHART_DATA, unserialize( html_entity_decode( get_the_content( $post_id ) ) ), $post_id, $data['visualizer-chart-type'] );
// we are going to format only for tabular charts, because we are not sure of the effect on others.
// this is to solve the case where boolean data shows up as all-ticks on gutenberg.
if ( in_array( $data['visualizer-chart-type'], array( 'tabular' ), true ) ) {
$data['visualizer-data'] = $this->format_chart_data( $data['visualizer-data'], $data['visualizer-series'] );
}
if ( ! isset( $data['visualizer-settings']['hAxis']['format'] ) ) {
$data['visualizer-settings']['hAxis']['format'] = '';
}
$data['visualizer-data-exploded'] = '';
// handle annotations for google charts
if ( 'GoogleCharts' === $library ) {
// this will contain the data of both axis.
$settings = $data['visualizer-settings'];
// this will contain data only of Y axis.
$series = $data['visualizer-series'];
$annotations = array();
if ( isset( $settings['series'] ) ) {
foreach ( $settings['series'] as $index => $serie ) {
// skip X axis data.
if ( $index === 0 ) {
continue;
}
if ( ! empty( $serie['role'] ) ) {
// this series is some kind of annotation, so let's collect its index.
// the index will be +1 because the X axis value is index 0, which is being ignored.
$annotations[ 'role' . ( intval( $index ) + 1 ) ] = $serie['role'];
if ( isset( $data['visualizer-series'][ intval( $index ) + 1 ] ) ) {
$data['visualizer-series'][ intval( $index ) + 1 ]['role'] = $serie['role'];
}
}
}
}
if ( ! empty( $annotations ) ) {
$exploded_data = array();
$series_names = array();
foreach ( $series as $index => $serie ) {
// skip X axis data.
if ( $index === 0 ) {
continue;
}
if ( array_key_exists( 'role' . $index, $annotations ) ) {
$series_names[] = (object) array( 'role' => $annotations[ 'role' . $index ], 'type' => $serie['type'] );
} else {
$series_names[] = $serie['label'];
}
}
$exploded_data[] = $series_names;
foreach ( $data['visualizer-data'] as $datum ) {
// skip X axis data.
unset( $datum[0] );
$exploded_data[] = $datum;
}
$data['visualizer-data-exploded'] = array( $exploded_data );
}
}
$import = get_post_meta( $post_id, Visualizer_Plugin::CF_CHART_URL, true );
$schedule = get_post_meta( $post_id, Visualizer_Plugin::CF_CHART_SCHEDULE, true );
$db_schedule = get_post_meta( $post_id, Visualizer_Plugin::CF_DB_SCHEDULE, true );
$db_query = get_post_meta( $post_id, Visualizer_Plugin::CF_DB_QUERY, true );
$json_url = get_post_meta( $post_id, Visualizer_Plugin::CF_JSON_URL, true );
$json_headers = get_post_meta( $post_id, Visualizer_Plugin::CF_JSON_HEADERS, true );
$json_schedule = get_post_meta( $post_id, Visualizer_Plugin::CF_JSON_SCHEDULE, true );
$json_root = get_post_meta( $post_id, Visualizer_Plugin::CF_JSON_ROOT, true );
$json_paging = get_post_meta( $post_id, Visualizer_Plugin::CF_JSON_PAGING, true );
if ( ! empty( $import ) && $schedule >= 0 ) {
$data['visualizer-chart-url'] = $import;
$data['visualizer-chart-schedule'] = $schedule;
}
if ( ! empty( $db_schedule ) && ! empty( $db_query ) ) {
$data['visualizer-db-schedule'] = $db_schedule;
$data['visualizer-db-query'] = $db_query;
}
if ( ! empty( $json_url ) ) {
$data['visualizer-json-schedule'] = $json_schedule;
$data['visualizer-json-url'] = $json_url;
$data['visualizer-json-headers'] = $json_headers;
$data['visualizer-json-root'] = $json_root;
if ( Visualizer_Module::is_pro() && ! empty( $json_paging ) ) {
$data['visualizer-json-paging'] = $json_paging;
}
}
if ( Visualizer_Module::is_pro() ) {
$permissions = get_post_meta( $post_id, Visualizer_Pro::CF_PERMISSIONS, true );
if ( empty( $permissions ) ) {
$permissions = array( 'permissions' => array(
'read' => 'all',
'edit' => 'roles',
'edit-specific' => array( 'administrator' ),
),
);
}
$data['visualizer-permissions'] = $permissions;
}
return $data;
}
/**
* Returns the data for the query.
*
* @access public
*/
public function get_query_data( $data ) {
if ( ! current_user_can( 'administrator' ) || ( is_multisite() && ! is_super_admin() ) ) {
return false;
}
$source = new Visualizer_Source_Query( stripslashes( $data['query'] ) );
$html = $source->fetch( true );
$source->fetch( false );
$name = $source->getSourceName();
$series = $source->getSeries();
$data = $source->getRawData();
$error = '';
if ( empty( $html ) ) {
$error = $source->get_error();
wp_send_json_error( array( 'msg' => $error ) );
}
wp_send_json_success( array( 'table' => $html, 'name' => $name, 'series' => $series, 'data' => $data ) );
}
/**
* Returns the JSON root.
*
* @access public
*/
public function get_json_root_data( $data ) {
if ( ! current_user_can( 'edit_posts' ) ) {
return false;
}
$source = new Visualizer_Source_Json( $data );
$roots = $source->fetchRoots();
if ( empty( $roots ) ) {
wp_send_json_error( array( 'msg' => $source->get_error() ) );
}
wp_send_json_success( array( 'url' => $data['url'], 'roots' => $roots ) );
}
/**
* Returns the JSON data.
*
* @access public
*/
public function get_json_data( $data ) {
if ( ! current_user_can( 'edit_posts' ) ) {
return false;
}
$chart_id = $data['chart'];
if ( empty( $chart_id ) ) {
wp_die();
}
$source = new Visualizer_Source_Json( $data );
$source->fetch();
$table = $source->getRawData();
if ( empty( $table ) ) {
wp_send_json_error( array( 'msg' => esc_html__( 'Unable to fetch data from the endpoint. Please try again.', 'visualizer' ) ) );
}
$table = Visualizer_Render_Layout::show( 'editor-table', $table, $chart_id, 'viz-json-table', false, false );
wp_send_json_success( array( 'table' => $table, 'root' => $data['root'], 'url' => $data['url'], 'paging' => $source->getPaginationElements() ) );
}
/**
* Set the JSON data.
*
* @access public
*/
public function set_json_data( $data ) {
if ( ! current_user_can( 'edit_posts' ) ) {
return false;
}
$source = new Visualizer_Source_Json( $data );
$table = $source->fetch();
if ( empty( $table ) ) {
wp_send_json_error( array( 'msg' => esc_html__( 'Unable to fetch data from the endpoint. Please try again.', 'visualizer' ) ) );
}
$source->fetchFromEditableTable();
$name = $source->getSourceName();
$series = json_encode( $source->getSeries() );
$data = json_encode( $source->getRawData() );
wp_send_json_success( array( 'name' => $name, 'series' => $series, 'data' => $data ) );
}
/**
* Rest Callback Method
*/
public function update_chart_data( $data ) {
if ( ! current_user_can( 'edit_posts' ) ) {
return false;
}
if ( $data['id'] && ! is_wp_error( $data['id'] ) ) {
if ( get_post_type( $data['id'] ) !== Visualizer_Plugin::CPT_VISUALIZER ) {
return new WP_Error( 'invalid_post_type', 'Invalid post type.' );
}
$chart_type = sanitize_text_field( $data['visualizer-chart-type'] );
$source_type = sanitize_text_field( $data['visualizer-source'] );
update_post_meta( $data['id'], Visualizer_Plugin::CF_CHART_TYPE, $chart_type );
update_post_meta( $data['id'], Visualizer_Plugin::CF_SOURCE, $source_type );
update_post_meta( $data['id'], Visualizer_Plugin::CF_DEFAULT_DATA, $data['visualizer-default-data'] );
update_post_meta( $data['id'], Visualizer_Plugin::CF_SERIES, $data['visualizer-series'] );
update_post_meta( $data['id'], Visualizer_Plugin::CF_SETTINGS, $data['visualizer-settings'] );
if ( $data['visualizer-chart-url'] && $data['visualizer-chart-schedule'] >= 0 ) {
$chart_url = esc_url_raw( $data['visualizer-chart-url'] );
$chart_schedule = intval( $data['visualizer-chart-schedule'] );
update_post_meta( $data['id'], Visualizer_Plugin::CF_CHART_URL, $chart_url );
apply_filters( 'visualizer_pro_chart_schedule', $data['id'], $chart_url, $chart_schedule );
} else {
delete_post_meta( $data['id'], Visualizer_Plugin::CF_CHART_URL );
apply_filters( 'visualizer_pro_remove_schedule', $data['id'] );
}
// let's check if this is not an external db chart
// as there is no support for that in the block editor interface
$external_params = get_post_meta( $data['id'], Visualizer_Plugin::CF_REMOTE_DB_PARAMS, true );
if ( empty( $external_params ) ) {
if ( $source_type === 'Visualizer_Source_Query' ) {
$db_schedule = intval( $data['visualizer-db-schedule'] );
$db_query = $data['visualizer-db-query'];
update_post_meta( $data['id'], Visualizer_Plugin::CF_DB_SCHEDULE, $db_schedule );
update_post_meta( $data['id'], Visualizer_Plugin::CF_DB_QUERY, stripslashes( $db_query ) );
} else {
delete_post_meta( $data['id'], Visualizer_Plugin::CF_DB_SCHEDULE );
delete_post_meta( $data['id'], Visualizer_Plugin::CF_DB_QUERY );
}
if ( 'Visualizer_Source_Csv_Remote' === $source_type ) {
$schedule_url = $data['visualizer-chart-url'];
$schedule_id = $data['visualizer-chart-schedule'];
update_post_meta( $data['id'], Visualizer_Plugin::CF_CHART_URL, $schedule_url );
update_post_meta( $data['id'], Visualizer_Plugin::CF_CHART_SCHEDULE, $schedule_id );
} else {
delete_post_meta( $data['id'], Visualizer_Plugin::CF_CHART_URL );
delete_post_meta( $data['id'], Visualizer_Plugin::CF_CHART_SCHEDULE );
}
}
if ( $source_type === 'Visualizer_Source_Json' ) {
$json_schedule = intval( $data['visualizer-json-schedule'] );
$json_url = esc_url_raw( $data['visualizer-json-url'] );
$json_headers = esc_url_raw( $data['visualizer-json-headers'] );
$json_root = $data['visualizer-json-root'];
$json_paging = $data['visualizer-json-paging'];
update_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_SCHEDULE, $json_schedule );
update_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_URL, $json_url );
update_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_HEADERS, $json_headers );
update_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_ROOT, $json_root );
if ( ! empty( $json_paging ) ) {
update_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_PAGING, $json_paging );
} else {
delete_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_PAGING );
}
} else {
delete_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_SCHEDULE );
delete_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_URL );
delete_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_HEADERS );
delete_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_ROOT );
delete_post_meta( $data['id'], Visualizer_Plugin::CF_JSON_PAGING );
}
if ( Visualizer_Module::is_pro() ) {
update_post_meta( $data['id'], Visualizer_Pro::CF_PERMISSIONS, $data['visualizer-permissions'] );
}
if ( $data['visualizer-chart-url'] ) {
$chart_url = esc_url_raw( $data['visualizer-chart-url'] );
$content['source'] = $chart_url;
$content['data'] = $this->format_chart_data( $data['visualizer-data'], $data['visualizer-series'] );
} else {
$content = $this->format_chart_data( $data['visualizer-data'], $data['visualizer-series'] );
}
$chart = array(
'ID' => $data['id'],
'post_content' => serialize( $content ),
);
wp_update_post( $chart );
// Clear existing chart cache.
$cache_key = Visualizer_Plugin::CF_CHART_CACHE . '_' . $data['id'];
if ( get_transient( $cache_key ) ) {
delete_transient( $cache_key );
}
$revisions = wp_get_post_revisions( $data['id'], array( 'order' => 'ASC' ) );
if ( count( $revisions ) > 1 ) {
$revision_ids = array_keys( $revisions );
// delete all revisions.
foreach ( $revision_ids as $id ) {
wp_delete_post_revision( $id );
}
}
return new \WP_REST_Response( array( 'success' => sprintf( 'Chart updated' ) ) );
}
}
/**
* Format chart data.
*
* Note: No matter how tempted, don't use the similar method from Visualizer_Source. That works on a different structure.
*/
public function format_chart_data( $data, $series ) {
foreach ( $series as $i => $row ) {
// if no value exists for the seires, then add null
if ( ! isset( $series[ $i ] ) ) {
$series[ $i ] = null;
}
if ( is_null( $series[ $i ] ) ) {
continue;
}
switch ( $row['type'] ) {
case 'number':
foreach ( $data as $o => $col ) {
$data[ $o ][ $i ] = ( is_numeric( $col[ $i ] ) ) ? floatval( $col[ $i ] ) : ( is_numeric( str_replace( ',', '', $col[ $i ] ) ) ? floatval( str_replace( ',', '', $col[ $i ] ) ) : null );
}
break;
case 'boolean':
foreach ( $data as $o => $col ) {
$data[ $o ][ $i ] = ! empty( $col[ $i ] ) ? filter_var( $col[ $i ], FILTER_VALIDATE_BOOLEAN ) : false;
}
break;
case 'timeofday':
foreach ( $data as $o => $col ) {
$date = new DateTime( '1984-03-16T' . $col[ $i ] );
if ( $date ) {
$data[ $o ][ $i ] = array(
intval( $date->format( 'H' ) ),
intval( $date->format( 'i' ) ),
intval( $date->format( 's' ) ),
0,
);
}
}
break;
case 'string':
foreach ( $data as $o => $col ) {
$data[ $o ][ $i ] = $this->toUTF8( $col[ $i ] );
}
break;
}
}
return $data;
}
/**
* Use toUTF8 function
*/
public function toUTF8( $datum ) {
if ( ! function_exists( 'mb_detect_encoding' ) || mb_detect_encoding( $datum ) !== 'ASCII' ) {
$datum = \ForceUTF8\Encoding::toUTF8( $datum );
}
return $datum;
}
/**
* Handle remote CSV data
*/
public function upload_csv_data( $data ) {
if ( ! current_user_can( 'edit_posts' ) ) {
return false;
}
$remote_data = false;
if ( isset( $data['url'] ) && function_exists( 'wp_http_validate_url' ) ) {
$remote_data = wp_http_validate_url( $data['url'] );
}
if ( false !== $remote_data && ! is_wp_error( $remote_data ) ) {
$source = new Visualizer_Source_Csv_Remote( $remote_data );
if ( $source->fetch() ) {
$temp = $source->getData();
if ( is_string( $temp ) && is_array( unserialize( $temp ) ) ) {
$content['series'] = $source->getSeries();
$content['data'] = $source->getRawData();
return $content;
} else {
return new \WP_REST_Response( array( 'failed' => sprintf( 'Invalid CSV URL' ) ) );
}
} else {
return new \WP_REST_Response( array( 'failed' => sprintf( 'Invalid CSV URL' ) ) );
}
} else {
return new \WP_REST_Response( array( 'failed' => sprintf( 'Invalid CSV URL' ) ) );
}
}
/**
* Get permission data
*/
public function get_permission_data( $data ) {
if ( ! current_user_can( 'edit_posts' ) ) {
return false;
}
$options = array();
switch ( $data['type'] ) {
case 'users':
$query = new WP_User_Query(
array(
'number' => 1000,
'orderby' => 'display_name',
'fields' => array( 'ID', 'display_name' ),
'count_total' => false,
)
);
$users = $query->get_results();
if ( ! empty( $users ) ) {
$i = 0;
foreach ( $users as $user ) {
$options[ $i ]['value'] = $user->ID;
$options[ $i ]['label'] = $user->display_name;
$i++;
}
}
break;
case 'roles':
if ( ! function_exists( 'get_editable_roles' ) ) {
require_once ABSPATH . 'wp-admin/includes/user.php';
}
$roles = get_editable_roles();
if ( ! empty( $roles ) ) {
$i = 0;
foreach ( get_editable_roles() as $name => $info ) {
$options[ $i ]['value'] = $name;
$options[ $i ]['label'] = $name;
$i++;
}
}
break;
}
return $options;
}
/**
* Filter Rest Query
*/
public function add_rest_query_vars( $args, \WP_REST_Request $request ) {
if ( isset( $request['meta_key'] ) && isset( $request['meta_value'] ) ) {
$args['meta_query'] = array(
'relation' => 'OR',
array(
'key' => $request->get_param( 'meta_key' ),
'value' => $request->get_param( 'meta_value' ),
'compare' => '!=',
),
array(
'key' => $request->get_param( 'meta_key' ),
'value' => $request->get_param( 'meta_value' ),
'compare' => 'NOT EXISTS',
),
);
}
return $args;
}
}