forked from Automattic/liveblog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
liveblog.php
1863 lines (1557 loc) · 62 KB
/
liveblog.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
/**
* Plugin Name: Liveblog
* Plugin URI: http://wordpress.org/extend/plugins/liveblog/
* Description: Empowers website owners to provide rich and engaging live event coverage to a large, distributed audience.
* Version: 1.9.6
* Author: WordPress.com VIP, Big Bite Creative and contributors
* Author URI: https://github.com/Automattic/liveblog/graphs/contributors
* Text Domain: liveblog
*/
if ( ! class_exists( 'WPCOM_Liveblog' ) ) :
/**
* The main Liveblog class used to setup everything this plugin needs.
*
* Liveblog currently uses a custom comment-type to circumvent post cache
* issues frequently experienced by other live-blog implimentations. It comes
* with a simple and effective templating mechanism, complete with all of the
* CSS, JS, and AJAX needed to make this a turn-key installation.
*
* This class is a big container for a bunch of static methods, similar to a
* factory but without object inheritance or instantiation.
*/
final class WPCOM_Liveblog {
/** Constants *************************************************************/
const VERSION = '1.9.6';
const REWRITES_VERSION = 1;
const MIN_WP_VERSION = '4.4';
const MIN_WP_REST_API_VERSION = '4.4';
const KEY = 'liveblog';
const URL_ENDPOINT = 'liveblog';
const EDIT_CAP = 'publish_posts';
const NONCE_KEY = '_wpnonce'; // Using these strings since they're hard coded in the rest api. It'll still work fine for < 4.4
const NONCE_ACTION = 'wp_rest';
const REFRESH_INTERVAL = 10; // how often should we refresh
const DEBUG_REFRESH_INTERVAL = 2; // how often we refresh in development mode
const FOCUS_REFRESH_INTERVAL = 30; // how often we refresh in when window not in focus
const MAX_CONSECUTIVE_RETRIES = 100; // max number of failed tries before polling is disabled
const HUMAN_TIME_DIFF_UPDATE_INTERVAL = 60; // how often we change the entry human timestamps: "a minute ago"
const DELAY_THRESHOLD = 5; // how many failed tries after which we should increase the refresh interval
const DELAY_MULTIPLIER = 2; // by how much should we inscrease the refresh interval
const FADE_OUT_DURATION = 5; // how much time should take fading out the background of new entries
const RESPONSE_CACHE_MAX_AGE = DAY_IN_SECONDS; // `Cache-Control: max-age` value for cacheable JSON responses
const USE_REST_API = true; // Use the REST API if current version is at least MIN_WP_REST_API_VERSION. Allows for easy disabling/enabling
const DEFAULT_IMAGE_SIZE = 'full'; // The default image size to use when inserting media frm the media library.
const AUTHOR_LIST_DEBOUNCE_TIME = 500; // This is the time ms to debounce the async author list.
/** Variables *************************************************************/
public static $post_id = null;
private static $entry_query = null;
private static $do_not_cache_response = false;
private static $cache_control_max_age = null;
private static $custom_template_path = null;
public static $is_rest_api_call = false;
public static $auto_archive_days = null;
public static $auto_archive_expiry_key = 'liveblog_autoarchive_expiry_date';
public static $latest_timestamp = false;
/** Load Methods **********************************************************/
/**
* @uses add_action() to hook methods into WordPress actions
* @uses add_filter() to hook methods into WordPress filters
*/
public static function load() {
load_plugin_textdomain( 'liveblog', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
if ( self::is_wp_too_old() ) {
self::add_old_wp_notice();
return;
}
self::includes();
self::add_actions();
self::add_filters();
self::add_admin_actions();
self::add_admin_filters();
self::register_embed_handlers();
WPCOM_Liveblog_Entry_Key_Events::load();
WPCOM_Liveblog_Entry_Key_Events_Widget::load();
WPCOM_Liveblog_Entry_Extend::load();
WPCOM_Liveblog_Lazyloader::load();
WPCOM_Liveblog_Socketio_Loader::load();
WPCOM_Liveblog_Entry_Embed_SDKs::load();
WPCOM_Liveblog_AMP::load();
if ( self::use_rest_api() ) {
WPCOM_Liveblog_Rest_Api::load();
}
// Activate the WP CRON Hooks.
WPCOM_Liveblog_Cron::load();
}
public static function add_custom_post_type_support( $query ) {
if ( ! self::is_entries_ajax_request() ) {
return;
}
$post_types = array_filter( get_post_types(), array( __CLASS__, 'liveblog_post_type' ) );
$query->set( 'post_type', $post_types );
}
public static function liveblog_post_type( $post_type ) {
return post_type_supports( $post_type, self::KEY );
}
private static function add_old_wp_notice() {
add_action( 'admin_notices', array( 'WPCOM_Liveblog', 'show_old_wp_notice' ) );
}
public static function show_old_wp_notice() {
global $wp_version;
$min_version = self::MIN_WP_VERSION;
echo self::get_template_part( 'old-wp-notice.php', compact( 'wp_version', 'min_version' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Include the necessary files
*/
private static function includes() {
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-query.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-key-events.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-key-events-widget.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-extend.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-extend-feature.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-extend-feature-hashtags.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-extend-feature-commands.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-extend-feature-emojis.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-extend-feature-authors.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-lazyloader.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-socketio-loader.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-embed.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-entry-embed-sdks.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-amp.php';
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-amp-template.php';
if ( self::use_rest_api() ) {
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-rest-api.php';
}
// Manually include ms.php theme-side in multisite environments because
// we need its filesize and available space functions.
if ( ! is_admin() && is_multisite() ) {
require_once ABSPATH . 'wp-admin/includes/ms.php';
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-wp-cli.php';
}
require dirname( __FILE__ ) . '/classes/class-wpcom-liveblog-cron.php';
}
/**
* Hook actions in that run on every page-load
*
* @uses add_action()
*/
private static function add_actions() {
add_action( 'init', array( __CLASS__, 'init' ) );
add_action( 'init', array( __CLASS__, 'add_rewrite_rules' ) );
add_action( 'permalink_structure_changed', array( __CLASS__, 'add_rewrite_rules' ) );
// flush the rewrite rules a lot later so that we don't interfere with other plugins using rewrite rules
add_action( 'init', array( __CLASS__, 'flush_rewrite_rules' ), 1000 );
add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'admin_enqueue_scripts' ) );
add_action( 'wp_ajax_set_liveblog_state_for_post', array( __CLASS__, 'admin_ajax_set_liveblog_state_for_post' ) );
add_action( 'after_setup_theme', array( __CLASS__, 'add_custom_post_type_support' ) );
add_action( 'wp_head', array( __CLASS__, 'print_liveblog_metadata' ) );
}
/**
* Hook filters in that run on every page-load
*
* @uses add_filter()
*/
private static function add_filters() {
add_filter( 'template_redirect', array( __CLASS__, 'handle_request' ), 9 );
add_filter( 'comment_class', array( __CLASS__, 'add_comment_class' ), 10, 3 );
add_filter( 'is_protected_meta', array( __CLASS__, 'protect_liveblog_meta_key' ), 10, 2 );
// Add In the Filter hooks to Strip any Restricted Shortcodes before a new post or updating a post.
// Called from the WPCOM_Liveblog_Entry Class.
add_filter( 'liveblog_before_insert_entry', array( 'WPCOM_Liveblog_Entry', 'handle_restricted_shortcodes' ), 10, 1 );
add_filter( 'liveblog_before_update_entry', array( 'WPCOM_Liveblog_Entry', 'handle_restricted_shortcodes' ), 10, 1 );
// We need to check the Liveblog autoarchive date on each time a new entry is added or updated to
// ensure we extend the date out correctly to the next archive point based on the configured offset.
add_filter( 'liveblog_before_insert_entry', array( __CLASS__, 'update_autoarchive_expiry' ), 10, 1 );
}
/**
* Hook actions in that run on every admin page-load
*
* @uses add_action()
* @uses is_admin()
*/
private static function add_admin_actions() {
// Bail if not in admin area
if ( ! is_admin() ) {
return;
}
add_action( 'add_meta_boxes', array( __CLASS__, 'add_meta_box' ) );
add_action( 'restrict_manage_posts', array( __CLASS__, 'add_post_filtering_dropdown_to_manage_posts' ) );
add_action( 'pre_get_posts', array( __CLASS__, 'handle_query_vars_for_post_filtering' ) );
}
/**
* Hook filters in that run on every admin page-load
*
* @uses add_filter()
* @uses is_admin()
*/
private static function add_admin_filters() {
// Bail if not in admin area
if ( ! is_admin() ) {
return;
}
add_filter( 'display_post_states', array( __CLASS__, 'add_display_post_state' ), 10, 2 );
add_filter( 'query_vars', array( __CLASS__, 'add_query_var_for_post_filtering' ) );
}
private static function register_embed_handlers() {
// register it to run later, because the regex is pretty general and we don't want it to prevent more specific handlers from running
wp_embed_register_handler( 'liveblog_image', '/\.(png|jpe?g|gif)(\?.*)?$/', array( 'WPCOM_Liveblog', 'image_embed_handler' ), 99 );
}
/** Public Methods ********************************************************/
/**
* Liveblog initialization functions.
*
* This is where Liveblog sets up any additional things it needs to run
* inside of WordPress. Where some plugins would register post types or
* taxonomies, we modify endpoints and add post type support for Liveblog.
*/
public static function init() {
/**
* Add liveblog support to the 'post' post type. This is done here so
* we can possibly introduce this to other post types later.
*/
add_post_type_support( 'post', self::KEY );
/**
* Apply a Filter to Setup our Auto Archive Days.
* NULL is classed as disabled.
*/
self::$auto_archive_days = apply_filters( 'liveblog_auto_archive_days', self::$auto_archive_days );
do_action( 'after_liveblog_init' );
}
public static function add_rewrite_rules() {
add_rewrite_endpoint( self::URL_ENDPOINT, EP_PERMALINK );
}
public static function flush_rewrite_rules() {
$rewrites_version = (int) get_option( 'liveblog_rewrites_version' );
if ( self::REWRITES_VERSION !== $rewrites_version ) {
flush_rewrite_rules(); // phpcs:ignore WordPressVIPMinimum.VIP.RestrictedFunctions.rewrite_rules_flush_rewrite_rules
update_option( 'liveblog_rewrites_version', self::REWRITES_VERSION );
}
}
/**
* Returns the ID of the Liveblog post.
*
* @throws Exception when called before post ID is set
* @return int Liveblog post ID
*/
public static function get_post_id() {
if ( is_null( self::$post_id ) ) {
throw new Exception( __( 'No Liveblog post ID is set yet', 'liveblog' ) );
}
return self::$post_id;
}
/**
* Returns the avatar for a user
*
* @param $user_id author ID
* @param $size size, in pixels (or named size)
* @return HTML for avatar
*/
public static function get_avatar( $user_id, $size ) {
return apply_filters( 'liveblog_author_avatar', get_avatar( $user_id, $size ), $user_id, $size );
}
/**
* Get current user
*/
public static function get_current_user() {
if ( ! self::is_liveblog_editable() ) {
return false;
}
$user = wp_get_current_user();
return array(
'id' => $user->ID,
'key' => strtolower( $user->user_nicename ),
'name' => $user->display_name,
'avatar' => self::get_avatar( $user->ID, 20 ),
);
}
/**
* This is where a majority of the magic happens.
*
* Hooked to template_redirect, this method tries to add anything it can to
* the current post output. If nothing needs to be added, we redirect back
* to the permalink.
*
* return if request has been handled
*/
public static function handle_request() {
if ( ! self::is_viewing_liveblog_post() ) {
return;
}
self::$post_id = get_the_ID();
self::$custom_template_path = apply_filters( 'liveblog_template_path', self::$custom_template_path, self::$post_id );
if ( ! is_dir( self::$custom_template_path ) ) {
self::$custom_template_path = null;
} else {
// realpath is used here to ensure we have an absolute path which is necessary to avoid APC related bugs
self::$custom_template_path = untrailingslashit( realpath( self::$custom_template_path ) );
}
self::$entry_query = new WPCOM_Liveblog_Entry_Query( self::$post_id, self::KEY );
if ( self::is_initial_page_request() ) {
// we need to add the liveblog after the shortcodes are run, because we already
// process shortcodes in the comment contents and if we left any (like in the original content)
// we wouldn't like them to be processed
add_filter( 'the_content', array( __CLASS__, 'add_liveblog_to_content' ), 20 );
} else {
self::handle_ajax_request();
}
}
private static function handle_ajax_request() {
$endpoint_suffix = get_query_var( self::URL_ENDPOINT );
if ( ! $endpoint_suffix ) {
// we redirect, because if somebody accessed <permalink>/liveblog
// they probably did that in the URL bar, not via AJAX
wp_safe_redirect( get_permalink() );
exit();
}
wp_cache_delete( self::KEY . '_entries_asc_' . self::$post_id, 'liveblog' );
$suffix_to_method = array(
'\d+/\d+' => 'ajax_entries_between',
'crud' => 'ajax_crud_entry',
'entry' => 'ajax_single_entry',
'lazyload' => 'ajax_lazyload_entries',
'preview' => 'ajax_preview_entry',
);
$response_method = 'ajax_unknown';
foreach ( $suffix_to_method as $suffix_re => $method ) {
if ( preg_match( "%^$suffix_re/?%", $endpoint_suffix ) ) {
$response_method = $method;
break;
}
}
/**
* Fires just before the Liveblog's ajax request is handled by one of the methods
*
* @param string $response_method The name of the method used for handling the request.
*/
do_action( 'liveblog_ajax_request', $response_method );
self::$response_method();
}
/**
* Look for any new Liveblog entries, and return them via JSON
* Legacy endpoint for pre 4.4 installs
*/
public static function ajax_entries_between() {
$response_args = array();
// Look for entry boundaries
list( $start_timestamp, $end_timestamp ) = self::get_timestamps_from_query();
// Bail if there is no end timestamp
if ( empty( $end_timestamp ) ) {
self::send_user_error( __( 'A timestamp is missing. Correct URL: <permalink>/liveblog/<from>/</to>/', 'liveblog' ) );
}
// Get liveblog entries within the start and end boundaries
$result_for_json = self::get_entries_by_time( $start_timestamp, $end_timestamp );
self::json_return( $result_for_json );
}
/**
* Get Liveblog entries between a start and end time for a post
*
* @param int $start_timestamp The start time boundary
* @param int $end_timestamp The end time boundary
*
* @return An array of Liveblog entries, possibly empty.
*/
public static function get_entries_by_time( $start_timestamp, $end_timestamp ) {
// Set some defaults
$latest_timestamp = null;
$entries_for_json = array();
$now = time();
// If end timestamp is in future, set a cache TTL until it's not
if ( $end_timestamp > $now ) {
self::$cache_control_max_age = $end_timestamp - $now;
}
if ( empty( self::$entry_query ) ) {
self::$entry_query = new WPCOM_Liveblog_Entry_Query( self::$post_id, self::KEY );
}
// Get liveblog entries within the start and end boundaries
$all_entries = self::$entry_query->get_all_entries_asc();
$entries = self::$entry_query->find_between_timestamps( $all_entries, $start_timestamp, $end_timestamp );
$pages = false;
$per_page = WPCOM_Liveblog_Lazyloader::get_number_of_entries();
if ( ! empty( $entries ) ) {
/**
* Loop through each liveblog entry, set the most recent timestamp, and
* put the JSON data for each entry into a neat little array.
*/
foreach ( $entries as $entry ) {
$latest_timestamp = max( $latest_timestamp, $entry->get_timestamp() );
$entries_for_json[] = $entry->for_json();
}
$pages = ceil( count( self::flatten_entries( $all_entries ) ) / $per_page );
}
// Create the result array
$result = array(
'entries' => $entries_for_json,
'latest_timestamp' => $latest_timestamp,
'refresh_interval' => self::get_refresh_interval(),
'pages' => $pages,
);
if ( ! empty( $entries_for_json ) ) {
do_action( 'liveblog_entry_request', $result );
} else {
do_action( 'liveblog_entry_request_empty' );
}
return $result;
}
/**
* Is a given post_id a liveblog enabled post?
*
* @global WP_Post $post
* @param int $post_id
* @return bool
*/
public static function is_liveblog_post( $post_id = null ) {
$state = self::get_liveblog_state( $post_id );
return (bool) $state;
}
/**
* Are we viewing a liveblog post?
*
* @uses is_single()
* @uses is_liveblog_post()
* @return bool
*/
public static function is_viewing_liveblog_post() {
return (bool) ( is_single() && self::is_liveblog_post() );
}
/**
* One of: 'enable', 'archive', false.
*/
public static function get_liveblog_state( $post_id = null ) {
if ( ! is_single() && ! is_admin() && ! self::$is_rest_api_call ) {
return false;
}
if ( empty( $post_id ) ) {
if ( ! empty( self::$post_id ) ) {
$post_id = self::$post_id;
} else {
global $post;
if ( ! $post ) {
return false;
}
$post_id = $post->ID;
}
}
$state = get_post_meta( $post_id, self::KEY, true );
// backwards compatibility with older values
if ( 1 === $state ) {
$state = 'enable';
}
return $state;
}
/** Private _is_ Methods **************************************************/
/**
* Is this the initial page request?
*
* Note that we do not use get_query_var() - it returns '' for all requests,
* which is valid for /post-name/liveblog/
*
* @global WP_Query $wp_query
* @return bool
*/
private static function is_initial_page_request() {
global $wp_query;
return (bool) ! isset( $wp_query->query_vars[ self::KEY ] );
}
/**
* Is this an ajax request for the entries?
*
* @uses get_query_var() to check for the URL_ENDPOINT
* @return bool
*/
private static function is_entries_ajax_request() {
return (bool) get_query_var( self::URL_ENDPOINT );
}
/**
* Get timestamps from the current WP_Query
*
* Ensures that two timestamps exist, and returns a properly formatted empty
* array if not.
*
* @return array
*/
private static function get_timestamps_from_query() {
// Look for timestamps and bail if none
$stamps = rtrim( get_query_var( self::URL_ENDPOINT ), '/' );
if ( empty( $stamps ) ) {
return array( false, false );
}
// Get timestamps from the query variable
$timestamps = explode( '/', $stamps );
// Bail if there are not 2 timestamps
if ( 2 !== count( $timestamps ) ) {
return array( false, false );
}
// Return integer timestamps in an array
return array_map( 'intval', $timestamps );
}
// HANDLES THE CRUD ACTIONS FOR THE COMMENTS
public static function ajax_crud_entry() {
self::ajax_current_user_can_edit_liveblog();
self::ajax_check_nonce();
$args = array();
$crud_action = isset( $_POST['crud_action'] ) ? sanitize_text_field( wp_unslash( $_POST['crud_action'] ) ) : 0; // input var ok
if ( ! self::is_valid_crud_action( $crud_action ) ) {
// translators: 1: crud action
self::send_user_error( sprintf( __( 'Invalid entry crud_action: %s', 'liveblog' ), $crud_action ) );
}
$args['post_id'] = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0; // input var ok
$args['content'] = isset( $_POST['content'] ) ? sanitize_text_field( wp_unslash( $_POST['content'] ) ) : ''; // input var ok
$args['entry_id'] = isset( $_POST['entry_id'] ) ? intval( $_POST['entry_id'] ) : 0; // input var ok
$args['author_id'] = isset( $_POST['author_id'] ) ? intval( $_POST['author_id'] ) : false; // input var ok
$args['contributor_ids'] = isset( $_POST['contributor_ids'] ) ? sanitize_text_field( wp_unslash( $_POST['contributor_ids'] ) ) : false; // input var ok
$entry = self::do_crud_entry( $crud_action, $args );
if ( is_wp_error( $entry ) ) {
self::send_server_error( $entry->get_error_message() );
}
if ( WPCOM_Liveblog_Socketio_Loader::is_enabled() ) {
WPCOM_Liveblog_Socketio::emit(
'liveblog entry',
$entry->for_json()
);
} else {
// Do not send latest_timestamp. If we send it the client won't get
// older entries. Since we send only the new one, we don't know if there
// weren't any entries in between.
self::json_return(
array(
'entries' => array( $entry->for_json() ),
'latest_timestamp' => null,
),
array( 'cache' => false )
);
}
}
/**
* Perform a specific CRUD action on an entry for a post
*
* @param string $crud_action Allowed actions are insert|update|delete|delete_key
* @param array $args An array of data to be passed to the crud method
*
* @return mixed The result of the crud method
*/
public static function do_crud_entry( $crud_action, $args ) {
$args['user'] = wp_get_current_user();
$entry = call_user_func( array( 'WPCOM_Liveblog_Entry', $crud_action ), $args );
if ( ! is_wp_error( $entry ) ) {
// Do not send latest_timestamp. If we send it the client won't get
// older entries. Since we send only the new one, we don't know if there
// weren't any entries in between.
$entry = array(
'entries' => array( $entry->for_json() ),
'latest_timestamp' => null,
);
}
return $entry;
}
/**
* Fetches the Liveblog entry with the ID given in the $_GET superglobal, and returns it via JSON.
*/
public static function ajax_single_entry() {
// The URL is of the form "entry/entry_id".
$fragments = explode( '/', get_query_var( self::URL_ENDPOINT ) );
$entry_id = isset( $fragments[1] ) ? $fragments[1] : '';
$result_for_json = self::get_single_entry( $entry_id );
self::json_return( $result_for_json );
}
/**
* Get a single Liveblog entry for a post by entry ID
*
* @param int $entry_id The ID of the entry
*
* @return array An array of entry data
*/
public static function get_single_entry( $entry_id ) {
$entries = array();
$previous_timestamp = 0;
$next_timestamp = 0;
if ( empty( self::$entry_query ) ) {
self::$entry_query = new WPCOM_Liveblog_Entry_Query( self::$post_id, self::KEY );
}
// Why not just get the single entry rather than all?
$all_entries = array_values( self::$entry_query->get_all() );
foreach ( $all_entries as $key => $entry ) {
if ( $entry_id !== $entry->get_id() ) {
continue;
}
$entries = array( $entry );
if ( isset( $all_entries[ $key - 1 ] ) ) {
$previous_entry = $all_entries[ $key - 1 ];
$next_timestamp = $previous_entry->get_timestamp();
}
if ( isset( $all_entries[ $key + 1 ] ) ) {
$next_entry = $all_entries[ $key + 1 ];
$previous_timestamp = $next_entry->get_timestamp();
}
break;
}
$entries_for_json = array();
// Set up an array containing the JSON data for Liveblog entry.
foreach ( $entries as $entry ) {
$entries_for_json[] = $entry->for_json();
}
// Set up the data to be returned via JSON.
$result_for_json = array(
'entries' => $entries_for_json,
);
if ( ! empty( $entries_for_json ) ) {
// Entries found
$result_for_json['index'] = (int) filter_input( INPUT_GET, 'index' );
$result_for_json['nextTimestamp'] = $next_timestamp;
$result_for_json['previousTimestamp'] = $previous_timestamp;
do_action( 'liveblog_entry_request', $result_for_json );
self::$do_not_cache_response = true;
} else {
// No entries
do_action( 'liveblog_entry_request_empty' );
}
return $result_for_json;
}
/**
* Fetches all Liveblog entries that are to be lazyloaded, and returns them via JSON.
*/
public static function ajax_lazyload_entries() {
// The URL is of the form "lazyload/optional_max_timestamp/optional_min_timestamp".
$fragments = explode( '/', get_query_var( self::URL_ENDPOINT ) );
// Get all Liveblog entries that are to be lazyloaded.
$result_for_json = self::get_lazyload_entries(
isset( $fragments[1] ) ? (int) $fragments[1] : 0,
isset( $fragments[2] ) ? (int) $fragments[2] : 0
);
self::json_return( $result_for_json );
}
/**
* Get all Liveblog entries that are to be lazyloaded.
*
* @param int $max_timestamp Maximum timestamp for the Liveblog entries.
* @param int $min_timestamp Minimum timestamp for the Liveblog entries.
*
* @return array An array of json encoded results
*/
public static function get_lazyload_entries( $max_timestamp, $min_timestamp ) {
if ( empty( self::$entry_query ) ) {
self::$entry_query = new WPCOM_Liveblog_Entry_Query( self::$post_id, self::KEY );
}
// Get all Liveblog entries that are to be lazyloaded.
$entries = self::$entry_query->get_for_lazyloading( $max_timestamp, $min_timestamp );
$entries_for_json = array();
if ( ! empty( $entries ) ) {
$entries = array_slice( $entries, 0, WPCOM_Liveblog_Lazyloader::get_number_of_entries() );
// Populate an array containing the JSON data for all Liveblog entries.
foreach ( $entries as $entry ) {
$entries_for_json[] = $entry->for_json();
}
}
$result = array(
'entries' => $entries_for_json,
'index' => (int) filter_input( INPUT_GET, 'index' ),
);
if ( ! empty( $entries_for_json ) ) {
do_action( 'liveblog_entry_request', $result );
self::$do_not_cache_response = true;
} else {
do_action( 'liveblog_entry_request_empty' );
}
return $result;
}
/**
* Get single entry
*
* @param int $id entry id
* @return array An array of json encoded results
*/
public static function get_single_liveblog_entry( $id = false ) {
if ( empty( self::$entry_query ) ) {
self::$entry_query = new WPCOM_Liveblog_Entry_Query( self::$post_id, self::KEY );
}
return self::$entry_query->get_by_id( $id );
}
/**
* Get all entries for specific page
*
* @param int $page Requested Page.
* @param string $last_know_entry id-timestamp of the last rendered entry.
* @param int $id entry id
* @return array An array of json encoded results
*/
public static function get_entries_paged( $page, $last_known_entry = false, $id = false ) {
if ( empty( self::$entry_query ) ) {
self::$entry_query = new WPCOM_Liveblog_Entry_Query( self::$post_id, self::KEY );
}
$per_page = WPCOM_Liveblog_Lazyloader::get_number_of_entries();
$entries = self::$entry_query->get_all_entries_asc();
$entries = self::flatten_entries( $entries );
if ( $last_known_entry ) {
$last_known_entry = explode( '-', $last_known_entry );
if ( isset( $last_known_entry[0], $last_known_entry[1] ) ) {
$last_entry_id = (int) $last_known_entry[0];
$index = array_search( $last_entry_id, array_keys( $entries ), true );
$entries = array_slice( $entries, $index, null, true );
}
}
$pages = ceil( count( $entries ) / $per_page );
//If no page is passed but entry id is, we search for the correct page.
if ( false === $page && false !== $id ) {
$index = array_search( (int) $id, array_keys( $entries ), true );
$index++;
$page = ceil( $index / $per_page );
}
$offset = $per_page * ( $page - 1 );
$entries = array_slice( $entries, $offset, $per_page );
$entries = self::entries_for_json( $entries );
$result = array(
'entries' => $entries,
'page' => (int) $page,
'pages' => (int) $pages,
);
if ( ! empty( $entries ) ) {
do_action( 'liveblog_entry_request', $result );
self::$do_not_cache_response = true;
} else {
do_action( 'liveblog_entry_request_empty' );
}
return $result;
}
/**
* Convert array of entries to their json response
* @param type $entries
* @return array
*/
public static function entries_for_json( $entries ) {
$entries_for_json = array();
foreach ( $entries as $entry ) {
$entries_for_json[] = $entry->for_json();
}
return $entries_for_json;
}
/**
* Flattens Entries by running updates and deletes to get actual
* list of entries
*
* @param array $entires
* @return array
*/
public static function flatten_entries( $entries ) {
if ( empty( $entries ) || ! is_array( $entries ) ) {
return array();
}
$flatten = array();
foreach ( $entries as $entry ) {
$type = $entry->get_type();
$id = $entry->get_id();
if ( ! empty( $entry->replaces ) ) {
$id = $entry->replaces;
}
switch ( $type ) {
case 'new':
$flatten[ $id ] = $entry;
break;
case 'update':
$flatten[ $id ] = $entry;
break;
case 'delete':
unset( $flatten[ $id ] );
break;
}
}
return array_reverse( $flatten, true );
}
public static function ajax_preview_entry() {
$entry_content = isset( $_REQUEST['entry_content'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['entry_content'] ) ) : ''; // input var ok
$entry_content = self::format_preview_entry( $entry_content );
self::json_return( $entry_content );
}
/**
* Format the passed in content and give it back in an array
*
* @param string $entry_content The entry content to be previewed
*
* @return array The entry content wrapped in HTML elements
*/
public static function format_preview_entry( $entry_content ) {
$entry_content = stripslashes( wp_filter_post_kses( $entry_content ) );
$entry_content = apply_filters( 'liveblog_before_preview_entry', array( 'content' => $entry_content ) );
$entry_content = $entry_content['content'];
$entry_content = WPCOM_Liveblog_Entry::render_content( $entry_content );
do_action( 'liveblog_preview_entry', $entry_content );
return array( 'html' => $entry_content );
}
public static function ajax_unknown() {
self::send_user_error( __( 'Unknown liveblog action', 'liveblog' ) );
}
/** Comment Methods *******************************************************/
/**
* Add a liveblog class to each comment, so they can be styled
*
* @param array $classes
* @return string
*/
public static function add_comment_class( $classes, $class, $comment_id ) {
if ( self::KEY === get_comment_type( $comment_id ) ) {
$classes[] = 'liveblog-entry';
$classes[] = 'liveblog-entry-class-' . $comment_id;
}
return $classes;
}
public static function admin_enqueue_scripts( $hook_suffix ) {
global $post;
// Enqueue admin scripts only if adding or editing a supported post type.
if ( in_array( $hook_suffix, array( 'post.php', 'post-new.php' ), true ) && post_type_supports( get_post_type(), self::KEY ) ) {
$endpoint_url = '';
$use_rest_api = 0;
if ( self::use_rest_api() ) {
$endpoint_url = WPCOM_Liveblog_Rest_Api::build_endpoint_base() . $post->ID . '/post_state';
$use_rest_api = 1;
}
wp_enqueue_style( self::KEY, plugins_url( 'assets/dashboard/app.css', __FILE__ ), array(), self::VERSION );
wp_enqueue_script( 'liveblog-admin', plugins_url( 'assets/dashboard/app.js', __FILE__ ), array(), self::VERSION, false );
wp_localize_script(
'liveblog-admin',
'liveblog_admin_settings',
array(
'nonce_key' => self::NONCE_KEY,
'nonce' => wp_create_nonce( self::NONCE_ACTION ),
'error_message_template' => __( 'Error {error-code}: {error-message}', 'liveblog' ),
'short_error_message_template' => __( 'Error: {error-message}', 'liveblog' ),
'use_rest_api' => $use_rest_api,
'endpoint_url' => $endpoint_url,
)
);
}
}
/**
* Enqueue the necessary CSS and JS that liveblog needs to function.
*
* @return If not a liveblog post
*/