-
Notifications
You must be signed in to change notification settings - Fork 6
/
inline-gdocs-viewer.php
1464 lines (1378 loc) · 61.4 KB
/
inline-gdocs-viewer.php
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* The Inline Google Spreadsheets Viewer plugin for WordPress.
*
* WordPress plugin header information:
*
* * Plugin Name: Inline Google Spreadsheet Viewer
* * Plugin URI: https://wordpress.org/plugins/inline-google-spreadsheet-viewer/
* * Description: Retrieves data from a public Google Spreadsheet or CSV file and displays it as an HTML table or interactive chart. <strong>Like this plugin? Please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=TJLPJYXHSRBEE&lc=US&item_name=Inline%20Google%20Spreadsheet%20Viewer&item_number=Inline%20Google%20Spreadsheet%20Viewer&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted" title="Send a donation to the developer of Inline Google Spreadsheet Viewer">donate</a>. ♥ Thank you!</strong>
* * Version: 0.13.2
* * Text Domain: inline-gdocs-viewer
* * Domain Path: /languages
*
* @link https://developer.wordpress.org/plugins/the-basics/header-requirements/
*
* @license https://www.gnu.org/licenses/gpl-3.0.en.html
*
* @package WordPress\Plugin\InlineGoogleSpreadsheetViewer
*/
namespace WP_IGSV;
if ( ! defined( 'ABSPATH' ) ) { exit(); } // Disallow direct HTTP access.
/**
* Plugin class.
*/
class InlineGoogleSpreadsheetViewerPlugin {
/**
* The shortcode itself.
*
* @var string
*/
const shortcode = 'gdoc';
/**
* Internal prefix for settings, etc., derived from shortcode.
*
* @var string
*/
const prefix = 'gdoc_';
/**
* Default table class.
*
* @var string
*/
private static $dt_class = 'igsv-table';
/**
* Default for the DataTables defaults object in JSON format.
*
* @var string
*/
private static $dt_defaults;
/**
* Number of invocations for each page load.
*
* @var int
*/
private $invocations = 0;
/**
* List of custom capabilities.
*
* @var array
*/
private $capabilities; //< List of custom capabilities.
/**
* Regular expression to match a Google Sheet address in an URI.
*
* @var string
*/
private static $gdoc_url_regex =
'!https://(?:docs\.google\.com/spreadsheets/d/|script\.google\.com/macros/s/)([^/]+)!';
/**
* Constructor.
*/
public function __construct () {
self::$dt_defaults = json_encode( array(
'dom' => "B<'clear'>lfrtip",
'buttons' => array(
'colvis', 'copy', 'csv', 'excel', 'pdf', 'print'
)
) );
$this->capabilities = array(
self::prefix . 'query_sql_databases'
);
}
/**
* Entry code for WordPress framework.
*/
public static function register () {
add_action( 'plugins_loaded', array( __CLASS__, 'registerL10n' ) );
add_action( 'init', array( __CLASS__, 'maybeFetchGvizDataSource' ) );
add_action( 'admin_init', array( __CLASS__, 'registerSettings' ) );
add_action( 'admin_menu', array( __CLASS__, 'registerAdminMenu' ) );
add_action( 'admin_head', array( __CLASS__, 'registerContextualHelp' ) );
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'addAdminScripts' ) );
add_action( 'wp_enqueue_scripts', array( __CLASS__, 'addFrontEndScripts' ) );
$plugin = new self();
add_shortcode( self::shortcode, array( $plugin, 'displayShortcode' ) );
wp_embed_register_handler(
self::shortcode . 'spreadsheet',
self::$gdoc_url_regex,
array( __CLASS__, 'oEmbedHandler' )
);
register_activation_hook( __FILE__, array( __CLASS__, 'activate' ) );
}
/**
* Sets up plugin during activation.
*/
public static function activate () {
$options = get_option( self::prefix . 'settings' );
if ( ! isset( $options['datatables_classes'] ) ) {
$options['datatables_classes'] = self::$dt_class;
}
if ( empty( $options['datatables_defaults_object'] ) ) {
$options['datatables_defaults_object'] = json_decode( self::$dt_defaults );
}
update_option( self::prefix . 'settings', $options );
$admin_role = get_role( 'administrator' );
$admin_role->add_cap( self::prefix . 'query_sql_databases', true );
}
/**
* Loads i18n from languages directory.
*/
public static function registerL10n () {
load_plugin_textdomain( 'inline-gdocs-viewer', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
/**
* @see https://developer.wordpress.org/reference/hooks/admin_init/
*/
public static function registerSettings () {
register_setting(
self::prefix . 'settings',
self::prefix . 'settings',
array( __CLASS__, 'validateSettings' )
);
}
/**
* Adds the option page.
*/
public static function registerAdminMenu () {
add_options_page(
__( 'Inline Google Spreadsheet Viewer Settings', 'inline-gdocs-viewer' ),
__( 'Inline Google Spreadsheet Viewer', 'inline-gdocs-viewer' ),
'manage_options',
self::prefix . 'settings',
array( __CLASS__, 'renderOptionsPage' )
);
}
/**
* @see https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/
*/
public static function addAdminScripts () {
wp_enqueue_style( 'wp-jquery-ui-dialog' );
wp_enqueue_script( 'jquery-ui-dialog' );
wp_enqueue_script( 'jquery-ui-tabs' );
wp_enqueue_style(
'inline-gdocs-viewer',
plugins_url( 'inline-gdocs-viewer.css', __FILE__ )
);
}
/**
* @see https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/
*/
public static function addFrontEndScripts () {
$styles = array(
'jquery-datatables' => array(
'src' => 'https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css'
),
'datatables-buttons' => array(
'src' => 'https://cdn.datatables.net/buttons/1.6.1/css/buttons.dataTables.min.css'
),
'datatables-select' => array(
'src' => 'https://cdn.datatables.net/select/1.3.1/css/select.dataTables.min.css'
),
'datatables-fixedheader' => array(
'src' => 'https://cdn.datatables.net/fixedheader/3.1.6/css/fixedHeader.dataTables.min.css'
),
'datatables-fixedcolumns' => array(
'src' => 'https://cdn.datatables.net/fixedcolumns/3.3.0/css/fixedColumns.dataTables.min.css'
),
'datatables-responsive' => array(
'src' => 'https://cdn.datatables.net/responsive/2.2.3/css/responsive.dataTables.min.css'
)
);
$scripts = array(
'jquery-datatables' => array(
'src' => 'https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js',
'deps' => array( 'jquery' )
),
'datatables-buttons' => array(
'src' => 'https://cdn.datatables.net/buttons/1.6.1/js/dataTables.buttons.min.js',
'deps' => array( 'jquery-datatables' )
),
'datatables-buttons-colvis' => array(
'src' => '//cdn.datatables.net/buttons/1.6.1/js/buttons.colVis.min.js',
'deps' => array( 'datatables-buttons' )
),
'datatables-buttons-print' => array(
'src' => '//cdn.datatables.net/buttons/1.6.1/js/buttons.print.min.js',
'deps' => array( 'datatables-buttons' )
),
// PDFMake (required for DataTables' PDF buttons)
'pdfmake' => array(
'src' => '//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js',
'deps' => array( 'datatables-buttons' )
),
'pdfmake-fonts' => array(
'src' => '//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js',
'deps' => array( 'pdfmake' )
),
// JSZip (required for DataTables' Excel button)
'jszip' => array(
'src' => '//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js',
'deps' => array( 'datatables-buttons' )
),
'datatables-buttons-html5' => array(
'src' => '//cdn.datatables.net/buttons/1.6.1/js/buttons.html5.min.js',
'deps' => array( 'datatables-buttons' )
),
'datatables-select' => array(
'src' => 'https://cdn.datatables.net/select/1.3.1/js/dataTables.select.min.js',
'deps' => array( 'jquery-datatables' )
),
'datatables-fixedheader' => array(
'src' => 'https://cdn.datatables.net/fixedheader/3.1.6/js/dataTables.fixedHeader.min.js',
'deps' => array( 'jquery-datatables' )
),
'datatables-fixedcolumns' => array(
'src' => 'https://cdn.datatables.net/fixedcolumns/3.3.0/js/dataTables.fixedColumns.min.js',
'deps' => array( 'jquery-datatables' )
),
'datatables-responsive' => array(
'src' => 'https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js',
'deps' => array( 'jquery-datatables' )
),
'igsv-datatables' => array(
'src' => plugins_url( 'igsv-datatables.js', __FILE__ ),
'deps' => array( 'jquery-datatables' )
),
// Google Charts and Visualization libraries
'google-ajax-api' => array(
'src' => '//www.google.com/jsapi'
),
'igsv-gvizcharts' => array(
'src' => plugins_url( 'igsv-gvizcharts.js', __FILE__ ),
'deps' => array( 'google-ajax-api' )
)
);
$styles = apply_filters( self::prefix . 'enqueued_front_end_styles', $styles );
$scripts = apply_filters( self::prefix . 'enqueued_front_end_scripts', $scripts );
foreach ( $styles as $handle => $style ) {
wp_enqueue_style(
$handle,
$style['src']
);
}
foreach ( $scripts as $handle => $script ) {
wp_enqueue_script(
$handle,
$script['src'],
( isset( $script['deps'] ) ) ? $script['deps'] : array()
);
}
if ( wp_script_is( 'igsv-datatables', 'enqueued') ) {
wp_localize_script( 'igsv-datatables', 'igsv_plugin_vars', self::getLocalizedPluginVars() );
}
}
/**
* Deterministically makes a unique transient name.
*
* @param string $key The ID of the document, extracted from the key attribute of the shortcode.
* @param string $q The query, if one exists, from the query attribute of the shortcode.
*
* @return string A 40 character unique string representing the name of the transient for this key and query.
*
* @see https://codex.wordpress.org/Transients_API
*/
private function getTransientName ( $key, $q, $gid ) {
return substr( self::shortcode . hash( 'sha1', self::shortcode . $key . $q . $gid ), 0, 40 );
}
/**
* Gets the transient.
*
* This simple getter/setter pair works around a bug in WP's own
* serialization, apparently, by serializing the data ourselves
* and then base64 encoding it.
*
* @return mixed
*/
private function getTransient ( $transient ) {
return unserialize( base64_decode( get_transient( $transient ) ) );
}
/**
* Saves data as a WordPress transient.
*
* @return bool
*/
private function setTransient ( $transient, $data, $expiry ) {
return set_transient( $transient, base64_encode( serialize( $data ) ), $expiry );
}
/**
* Lazily tests the provided Google Doc "key" (URL or document ID)
* to determine what type of document it really is. Valid doc
* types are one of: `spreadsheet`, `gasapp`, `docsviewer`, or `csv`.
*
* @param string $key The key passed from the shortcode.
* @return string A keyword referring to the type of document the key refers to.
*/
private static function getDocTypeByKey ( $key ) {
$type = '';
$p = parse_url( $key );
if ( 'csv' === strtolower( pathinfo( $p['path'], PATHINFO_EXTENSION ) ) ) {
$type = 'csv';
} else if ( empty( $p['scheme'] ) && 'wordpress' === $p['path'] ) {
$type = 'wpdb';
} else if ( isset( $p['scheme'] ) && 'mysql' === $p['scheme'] ) {
$type = 'mysql';
} else if ( isset( $p['host'] ) ) {
switch ( $p['host'] ) {
case 'docs.google.com':
$type = 'spreadsheet';
break;
case 'script.google.com':
$type = 'gasapp';
break;
default:
$type = 'docsviewer';
break;
}
} else {
$type = 'spreadsheet';
}
return $type;
}
/**
* Gets a Google spreadsheet URL from its key.
*
* @param array $atts Shortcode attributes.
*
* @return string
*/
private function getSpreadsheetUrl ( $atts ) {
$url = '';
$parts = parse_url( $atts['key'] );
// Force a full URL path if only the document ID was passed in.
$path = ( false === strpos( $parts['path'], '/' ) )
? "/spreadsheets/d/{$parts['path']}/view"
: $parts['path'];
if ( ! empty( $parts['fragment'] ) ) {
$frag = array();
parse_str( $parts['fragment'], $frag );
if ( $frag['gid'] ) {
$atts['gid'] = $frag['gid'];
}
}
$atts['key'] = ( empty( $parts['scheme'] ) ) ? 'https' : $parts['scheme'];
$atts['key'] .= '://';
$atts['key'] .= ( empty( $parts['host'] ) ) ? 'docs.google.com' : $parts['host'];
$atts['key'] .= $path;
$action = ( $atts['query'] || $atts['chart'] )
? 'gviz/tq?tqx=out:csv&tq=' . rawurlencode( $atts['query'] ) . '&headers=' . absint( $atts['csv_headers'] )
: 'export?format=csv';
$m = array();
preg_match( '/\/(edit|view|pubhtml|htmlview).*$/', $atts['key'], $m );
$url = str_replace( empty( $m[1] ) ? '' : $m[1], $action, $atts['key'] );
if ( $atts['gid'] ) {
$url .= '&gid=' . $atts['gid'];
}
return $url;
}
/**
* Returns a URL for a Google Visualization Query.
*
* @param string $key
* @param string $query
* @param string $format
*
* @return string
*/
private function getGVizDataSourceUrl ( $key, $query, $format ) {
$format = ( $format ) ? $format : 'json';
$base = trailingslashit( get_site_url() ) . '?';
$qs = 'url=';
$qs .= rawurlencode( $key ) . '&tq=' . rawurlencode( $query ) . "&tqx=out:$format";
return $base . $qs;
}
/**
* Sanitizes the "query" part of the shortcode.
*
* @param string $query
*
* @return string
*/
private static function sanitizeQuery ( $query ) {
// Due to shortcode parsing limitations of angle brackets (< and > characters),
// manually decode only the URL encoded values for those values, which are
// themselves expected to be entered manually by the user. That is, to supply
// the shortcode with a less than sign, the user ought enter %3C, but after
// the initial urlencode($query), this will encode the percent sign, returning
// instead the value %253C, so we manually replace this in the query ourselves.
return rawurldecode(
str_replace(
'%253E',
'%3E',
str_replace( '%253C', '%3C', rawurlencode( $query ) )
)
);
}
/**
* Gets the shortcode's ID for output as an HTML ID attribute.
*
* @param string $key
*
* @uses sanitize_title_with_dashes()
* @uses wp_salt()
*
* @return string
*/
private function getDocId ( $key ) {
$m = array();
preg_match( self::$gdoc_url_regex, $key, $m );
if ( ! empty( $m[1] ) ) {
$id = $m[1];
} else {
$id = sanitize_title_with_dashes( $key );
}
if ( 'mysql' === self::getDocTypeByKey( $key ) ) {
$p = parse_url( $key ); // Omit the password from the hash.
$id = hash( 'sha256', wp_salt() . "{$p['scheme']}://{$p['user']}@{$p['host']}{$p['path']}" );
}
return $id;
}
/**
* Gets the roles permitted to use SQL statements in shortcodes.
*
* @return array The roles capable of executing SQL directly from a shortcode.
*/
private static function getSqlCapableRoles () {
global $wp_roles;
$sql_capable_roles = array();
foreach ( $wp_roles->roles as $k => $v ) {
if ( array_key_exists( self::prefix . 'query_sql_databases', $v['capabilities'] ) ) {
$sql_capable_roles[ $k ] = $v;
}
}
return $sql_capable_roles;
}
/**
* Retrieves data from the transient cache if available, or via HTTP if not.
*
* @param string $url The URL to fetch, if not in cache.
* @param array $x Values from the shortcode attributes.
*/
private function fetchData ($url, $x) {
$transient = $this->getTransientName($x['key'], $x['query'], $x['gid']);
if (false === $x['use_cache'] || 'no' === strtolower($x['use_cache'])) {
delete_transient($transient);
$http_response = $this->doHttpRequest($url, $x['http_opts']);
} else {
if (false === ($http_response = $this->getTransient($transient))) {
$http_response = $this->doHttpRequest($url, $x['http_opts']);
$this->setTransient($transient, $http_response, (int) $x['expire_in']);
}
}
return $http_response;
}
/**
* Performs an HTTP request as instructed by the shortcode's parameters.
*
* @param string $url The URL to request.
* @param string $http_opts A JSON string representing options to pass to the WordPress HTTP API.
*
* @return array $resp The HTTP response from the WordPress HTTP API.
*
* @throws \RuntimeException
*
* @see https://developer.wordpress.org/reference/classes/WP_HTTP/
*/
private static function doHttpRequest ( $url, $opts ) {
$http_args = array();
if ( $opts ) {
try {
foreach ( json_decode( $opts ) as $k => $v ) {
$http_args[ $k ] = $v;
}
} catch ( \Exception $e ) {
throw new \RuntimeException( __( 'Error parsing HTTP options attribute:', 'inline-gdocs-viewer' ) . $e->getMessage() );
}
}
$resp = ( empty( $http_args ) ) ? wp_remote_get( $url ) : wp_remote_request( $url, $http_args );
if ( is_wp_error( $resp ) ) { // bail on error
throw new \RuntimeException( __( 'Error requesting data:', 'inline-gdocs-viewer' ) . ' ' . $resp->get_error_message() );
}
return $resp;
}
/**
* @param string csv_str
*
* @return array
*/
public static function parseCsv ( $csv_str ) {
return self::str_getcsv( $csv_str ); // Yo, why is PHP's built-in str_getcsv() frakking things up?
}
/**
* Prints an appropriate HTML attribute string for any HTML5 Data
* attributes that DataTables can use.
*
* @param array $atts Values passed from the shortcode.
*
* @return A string representing attribute-value pairs in HTML.
*/
private function dataTablesAttributes ( $atts ) {
$str = '';
foreach ( $atts as $k => $v ) {
if ( 0 === strpos( $k, 'datatables_' ) && false !== $v ) {
$k = str_replace( 'datatables', 'data', str_replace( '_', '-', $k ) );
// We urldecode() the value here because WordPress shortcodes
// use square brackets, but so do JavaScript arrays so users
// are advised to sometimes enter URL-encoded equivalents.
$str .= esc_attr( $k ) . '=\'' . esc_attr( urldecode( $v ) ) . '\' ';
}
}
return $str;
}
/**
* Converts a two-dimensional array representing rows and cells of data
* into an HTML representation of that data, according to any additional
* options passed to it.
*
* @param array $r Multidimensional array representing table data.
* @param array $options Values passed from the shortcode.
* @param string $caption Passed via shortcode, should be the table caption.
* @return An HTML string of the complete <table> element.
* @see displayShortcode
*/
private function dataToHtml ($r, $options, $caption = '') {
if ( $options['strip'] > 0 ) {
$r = array_slice( $r, $options['strip'] ); // discard
}
// Split into table headers and body.
$thead = ( (int) $options['header_rows'] ) ? array_splice( $r, 0, $options['header_rows'] ) : array_splice( $r, 0, 1 );
$tfoot = ( (int) $options['footer_rows'] ) ? array_splice( $r, -$options['footer_rows'] ) : array();
$tbody = $r;
$ir = 1; // row number counter
$ic = 1; // column number counter
$id = ( 0 === $this->invocations )
? 'igsv-' . $this->getDocId( $options['key'] )
: "igsv-{$this->invocations}-" . $this->getDocId( $options['key'] );
$html = '<table id="' . esc_attr( $id ) . '"';
// Prepend a space character onto the 'class' value, if one exists.
if ( ! empty( $options['class'] ) ) {
$options['class'] = " {$options['class']}";
}
$html .= ' class="' . self::$dt_class . esc_attr( $options['class'] ) . '"';
$html .= ' lang="' . esc_attr( $options['lang'] ) . '"';
$html .= ( false === $options['summary'] ) ? '' : ' summary="' . esc_attr( $options['summary'] ) . '"';
$html .= ( false === $options['title'] ) ? '' : ' title="' . esc_attr( $options['title'] ) . '"';
$html .= ' style="' . esc_attr($options['style']) . '"';
$html .= ( array_search( 'no-datatables', explode( ' ', $options['class'] ) ) )
? ''
: ' ' . $this->dataTablesAttributes( $options );
$html .= '>';
if ( ! empty( $caption ) ) {
$html .= '<caption>' . esc_html( $caption ) . '</caption>';
}
$html .= "<thead>\n";
foreach ( $thead as $v ) {
$html .= '<tr id="' . esc_attr( $id ) . '-row-' . esc_attr( $ir ) . '"';
$html .= ' class="row-' . esc_attr( $ir ) . ' ' . esc_attr( $this->evenOrOdd( $ir ) ) . '">';
$ir++;
$ic = 1; // reset column counting
foreach ( $v as $th ) {
$th = nl2br( esc_html( $th ) );
$html .= '<th class="col-' . esc_attr( $ic ) . ' ' . esc_attr( $this->evenOrOdd( $ic ) ) . '">';
$html .= "<div>$th</div>";
$html .= '</th>';
$ic++;
}
$html .= "</tr>";
}
$html .= "</thead>";
if ( $tfoot ) {
$html .= "<tfoot>\n";
foreach ( $tfoot as $v ) {
$html .= '<tr id="' . esc_attr( $id ) . '-row-' . esc_attr( $ir ) . '"';
$html .= ' class="row-' . esc_attr( $ir ) . ' ' . esc_attr( $this->evenOrOdd( $ir ) ) . '">';
$ir++;
$ic = 1; // reset column counting
foreach ( $v as $td ) {
$td = nl2br( esc_html( $td ) );
$el = ( $ic <= $options['header_cols'] ) ? 'th' : 'td';
$html .= "<$el class=\"col-$ic " . $this->evenOrOdd( $ic ) . "\">$td</$el>";
$ic++;
}
$html .= "</tr>";
}
$html .= '</tfoot>';
}
$html .= "<tbody>\n";
foreach ( $tbody as $v ) {
$html .= '<tr id="' . esc_attr( $id ) . '-row-' . esc_attr( $ir ) . '"';
$html .= ' class="row-' . esc_attr( $ir ) . ' ' . esc_attr( $this->evenOrOdd( $ir ) ) . '">';
$ir++;
$ic = 1; // reset column counting
foreach ( $v as $td ) {
$td = nl2br( esc_html( $td ) );
$el = ( $ic <= $options['header_cols'] ) ? 'th' : 'td';
$html .= "<$el class=\"col-$ic " . $this->evenOrOdd( $ic ) . "\">$td</$el>";
$ic++;
}
$html .= "</tr>";
}
$html .= '</tbody>';
$html .= '</table>';
$html = apply_filters( self::shortcode . '_table_html', $html );
if ( false === $options['linkify'] || 'no' === strtolower( $options['linkify'] ) ) {
return $html;
} else {
return make_clickable( $html );
}
}
/**
* Prints either `odd` or `even`.
*
* @param int $x
*
* @return string
*/
private function evenOrOdd ($x) {
return ( (int) $x % 2 ) ? 'odd' : 'even'; // cast to integer just in case
}
/**
* Simple CSV parsing, taken directly from PHP manual.
* @see http://www.php.net/manual/en/function.str-getcsv.php#100579
*/
private static function str_getcsv ($input, $delimiter=',', $enclosure='"', $escape=null, $eol=null) {
$temp=fopen("php://memory", "rw");
fwrite($temp, $input);
fseek($temp, 0);
$r = array();
while (($data = fgetcsv($temp, 4096, $delimiter, $enclosure)) !== false) {
$r[] = $data;
}
fclose($temp);
return $r;
}
/**
* Handles oEmbed calls.
*
* @return string
*/
public static function oEmbedHandler ( $matches, $attr, $url, $rawattr ) {
$plugin = new self();
return $plugin->displayShortcode( array( 'key' => $url ) );
}
/**
* Initialization hook to proxy own requests for Google Visualizations.
*
* @see https://developer.wordpress.org/reference/hooks/init/
*/
public static function maybeFetchGvizDataSource () {
if (
! isset( $_GET[self::prefix . 'get_datasource_nonce'] )
||
! self::isValidNonce( $_GET[self::prefix . 'get_datasource_nonce'], self::prefix . 'get_datasource_nonce' )
) { return; }
$url = rawurldecode( $_GET['url'] );
try {
$http_response = self::doHttpRequest( esc_url( $url ), false );
} catch ( \Exception $e ) {
error_log( '[' . self::shortcode . ' Error fetching GViz data source]: ' . $e->getMessage(), 'inline-gdocs-viewer' );
exit();
}
if ( isset( $_GET['chart'] ) ) {
$http_response['body'] = self::setGVizCsvDataTypes( $http_response['body'] );
}
require_once dirname( __FILE__ ) . '/lib/vistable.php';
$vt = new csv_vistable(
( isset( $_GET['tqx'] ) ) ? $_GET['tqx'] : '',
( isset( $_GET['tq'] ) ) ? $_GET['tq'] : '',
( isset( $_GET['tqrt'] ) ) ? $_GET['tqrt']: '',
( isset($_GET['tz'] ) ) ? $_GET['tz'] : 'PDT', // TODO: will get_option('timezone_string') work?
get_locale(),
array()
);
$vt->setup_table( $http_response['body'] );
print @$vt->execute();
exit();
}
/**
* When trying to do a chart on standard CSV data,
* the vistable library needs help to hint at the
* data types of columns, or else it'll always treat
* the data as a string.
*
* @param string $csv_str The raw CSV data.
*
* @return string The same CSV data with a type-hinted header row.
*/
private static function setGVizCsvDataTypes ( $csv_str ) {
$data = self::parseCsv( $csv_str );
$head = array_shift( $data );
$cols = array();
// peek at lines 2 through 20 (not the header)
$peek = ( count( $data ) > 20 ) ? 20 : count( $data );
for ( $i = 0; $i < $peek; $i++ ) {
foreach ( $data[ $i ] as $k => $v ) {
if ( ctype_digit( $v ) || preg_match( '/^[0-9]+(?:\.[0-9]*)?$/', $v ) ) {
$cols[ $k ] = 'number';
} else if ( strtotime( $v ) ) {
$cols[ $k ] = 'datetime';
} else {
$cols[ $k ] = 'string';
}
}
}
$head_typed = array();
foreach ( $head as $k => $v ) {
if ( 'string' === $cols[ $k ] ) {
$head_typed[] = $v;
} else {
$head_typed[] = $v . ' as ' . $cols[ $k ];
}
}
array_unshift( $data, $head_typed );
$lines = array();
foreach ( $data as $row ) {
$lines[] = implode( ',', $row );
}
return implode( "\n", $lines );
}
/**
* Returns the given URL with a nonce attached.
*
* @param string $url
*
* @return string
*/
private function makeNonceUrl ( $url ) {
$options = get_option( self::prefix . 'settings' );
$options[self::prefix . 'get_datasource_nonce'] = wp_create_nonce( self::prefix . 'get_datasource_nonce' );
update_option( self::prefix . 'settings', $options );
$p = parse_url( $url );
return $p['scheme']
. '://' . $p['host'] . $p['path']
. '?' . $p['query'] . '&'
. self::prefix . 'get_datasource_nonce=' . $options[self::prefix . 'get_datasource_nonce'];
}
/**
* Checks whether or not a recently-created valid nonce is valid.
*
* @param string $nonce
* @param string $nonce_name
*
* @return bool
*/
private static function isValidNonce ( $nonce, $nonce_name ) {
$options = get_option( self::prefix . 'settings' );
$is_valid = ( $nonce === $options[ $nonce_name ] ) ? true : false;
update_option( self::prefix . 'settings', $options );
return $is_valid;
}
/**
* WordPress Shortcode handler.
*
* @param array $atts
* @param mixed $content
*
* @return string
*/
public function displayShortcode ( $atts, $content = null ) {
$atts = shortcode_atts( array(
'key' => false, // Google Doc URL or ID
'title' => false, // Title (attribute) text or visible chart title
'class' => '', // Container element's custom class value
// TODO: Determine if `gid` attribute is still required by code.
'gid' => false, // Sheet ID for a Google Spreadsheet, if only one
'summary' => false, // If spreadsheet, value for summary attribute
'width' => '100%',
'height' => false,
'style' => false,
'strip' => 0, // If spreadsheet, how many rows to omit from top
'csv_headers' => 0, // Whether to include headers in Google Sheet CSV
'header_cols' => 0, // Number of columns to write as <th> elements
'header_rows' => 1, // Number of rows in <thead>
'footer_rows' => 0, // Number of rows in <tfoot>
'use_cache' => true, // Whether to use Transients API for fetched data.
'http_opts' => false, // Arguments to pass to the WordPress HTTP API.
// TODO: Make a plugin option setting for default transient expiry time.
'expire_in' => 10*MINUTE_IN_SECONDS,// Custom time-to-live of cached transient data.
'lang' => get_bloginfo('language'),
'linkify' => true, // Whether to run make_clickable() on parsed data.
'query' => false, // Google Visualization Query Language querystring
'chart' => false, // Type of Chart (for an interactive chart)
// Depending on the type of chart, the following options may be available.
'chart_aggregation_target' => false,
'chart_all_values_suffix' => false,
'chart_allow_html' => false,
'chart_allow_redraw' => false,
'chart_animation' => false,
'chart_annotations' => false,
'chart_annotations_width' => false,
'chart_area_opacity' => false,
'chart_avoid_overlapping_grid_lines' => false,
'chart_axis_titles_position' => false,
'chart_background_color' => false,
'chart_bars' => false,
'chart_bubble' => false,
'chart_candlestick' => false,
'chart_chart_area' => false,
'chart_color_axis' => false,
'chart_colors' => false,
'chart_crosshair' => false,
'chart_curve_type' => false,
'chart_data_opacity' => false,
'chart_dataless_region_color' => false,
'chart_date_format' => false,
'chart_default_color' => false,
'chart_dimensions' => false,
'chart_display_annotations' => false,
'chart_display_annotations_filter' => false,
'chart_display_date_bar_separator' => false,
'chart_display_exact_values' => false,
'chart_display_legend_dots' => false,
'chart_display_legend_values' => false,
'chart_display_mode' => false,
'chart_display_range_selector' => false,
'chart_display_zoom_buttons' => false,
'chart_domain' => false,
'chart_enable_interactivity' => false,
'chart_enable_region_interactivity'=> false,
'chart_explorer' => false,
'chart_fill' => false,
'chart_focus_target' => false,
'chart_font_name' => false,
'chart_font_size' => false,
'chart_force_i_frame' => false,
'chart_green_color' => false,
'chart_green_from' => false,
'chart_green_to' => false,
'chart_h_axes' => false,
'chart_h_axis' => false,
'chart_height' => false,
'chart_highlight_dot' => false,
'chart_interpolate_nulls' => false,
'chart_is_stacked' => false,
'chart_keep_aspect_ratio' => false,
'chart_legend' => false,
'chart_line_width' => false,
'chart_magnifying_glass' => false,
'chart_major_ticks' => false,
'chart_marker_opacity' => false,
'chart_max' => false,
'chart_min' => false,
'chart_minor_ticks' => false,
'chart_number_formats' => false,
'chart_orientation' => false,
'chart_pie_hole' => false,
'chart_pie_residue_slice_color' => false,
'chart_pie_residue_slice_label' => false,
'chart_pie_slice_border_color' => false,
'chart_pie_slice_text' => false,
'chart_pie_slice_text_style' => false,
'chart_pie_start_angle' => false,
'chart_point_shape' => false,
'chart_point_size' => false,
'chart_red_color' => false,
'chart_red_from' => false,
'chart_red_to' => false,
'chart_region' => false,
'chart_resolution' => false,
'chart_reverse_categories' => false,
'chart_scale_columns' => false,
'chart_scale_format' => false,
'chart_scale_type' => false,
'chart_selection_mode' => false,
'chart_series' => false,
'chart_size_axis' => false,
'chart_slice_visibility_threshold' => false,
'chart_slices' => false,
'chart_table' => false,
'chart_theme' => false,
'chart_thickness' => false,
'chart_timeline' => false,
'chart_title_position' => false,
'chart_title_text_style' => false,
'chart_tooltip' => false,
'chart_trendlines' => false,
'chart_v_axes' => false,
'chart_v_axis' => false,
'chart_width' => false,
'chart_wmode' => false,
'chart_yellow_color' => false,
'chart_yellow_from' => false,
'chart_yellow_to' => false,
'chart_zoom_end_time' => false,
'chart_zoom_start_time' => false,
// For some reason this isn't parsing?
//'chart_is3D' => false,
// DataTables's HTML5 data- attributes.
// DataTables Features
// @see https://www.datatables.net/reference/option/#Features
'datatables_auto_width' => false,
'datatables_buttons' => false,
'datatables_defer_render' => false,
'datatables_info' => false,
'datatables_j_query_UI' => false,
'datatables_length_change' => false,
'datatables_ordering' => false,
'datatables_paging' => false,
'datatables_processing' => false,
'datatables_scroll_x' => false,
'datatables_scroll_y' => false,
'datatables_searching' => false,
'datatables_select' => false,
'datatables_server_side' => false,
'datatables_state_save' => false,
// DataTables Data
// @see https://www.datatables.net/reference/option/#Data
'datatables_ajax' => false,
'datatables_data' => false,
// DataTables Options
// @see https://www.datatables.net/reference/option/#Options
'datatables_defer_loading' => false,
'datatables_destroy' => false,
'datatables_display_start' => false,
'datatables_dom' => false,
'datatables_length_menu' => false,
'datatables_order_cells_top' => false,
'datatables_order_classes' => false,
'datatables_order' => false,
'datatables_order_fixed' => false,
'datatables_order_multi' => false,
'datatables_page_length' => false,
'datatables_paging_type' => false,
'datatables_renderer' => false,
'datatables_retrieve' => false,
'datatables_scroll_collapse' => false,