-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathclass-wp-press-this-plugin.php
More file actions
1827 lines (1592 loc) · 61.1 KB
/
class-wp-press-this-plugin.php
File metadata and controls
1827 lines (1592 loc) · 61.1 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
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
/**
* Press This class and display functionality
*
* @package Press_This_Plugin
* @subpackage Press_This
* @since 1.0.0
*/
/**
* Press This class.
*
* @since 1.0.0
*/
class WP_Press_This_Plugin {
/**
* Used to trigger the bookmarklet update notice.
* Increment when bookmarklet functionality changes.
*
* @since 2.0.1
*/
const VERSION = 11;
/**
* Bookmarklet version number.
*
* @var int
*/
public $version = 11;
/**
* Images from the Pressed site.
*
* @var array
*/
private $images = array();
/**
* Embeds from the Pressed site.
*
* @var array
*/
private $embeds = array();
/**
* Domain of the Pressed site.
*
* @var string
*/
private $domain = '';
/**
* Whether the popup-blocked fallback is active (data in window.name).
*
* @var bool
*/
private $window_name_mode = false;
/**
* Constructor.
*
* @since 1.0.0
*/
public function __construct() {}
/**
* App and site settings data, including i18n strings for the client-side.
*
* @since 1.0.0
*
* @return array Site settings.
*/
public function site_settings() {
return array(
/**
* Filters whether or not Press This should redirect the user in the parent window upon save.
*
* @since 1.0.0
*
* @param bool $redirect Whether to redirect in parent window or not. Default false.
*/
'redirInParent' => apply_filters( 'press_this_redirect_in_parent', false ),
);
}
/**
* Get the source's images and save them locally, for posterity, unless we can't.
*
* @since 1.0.0
*
* @param int $post_id Post ID.
* @param string $content Optional. Current expected markup for Press This. Expects slashed. Default empty.
* @return string New markup with old image URLs replaced with the local attachment ones if swapped.
*/
public function side_load_images( $post_id, $content = '' ) {
$content = wp_unslash( $content );
if ( preg_match_all( '/<img [^>]+>/', $content, $matches ) && current_user_can( 'upload_files' ) ) {
foreach ( (array) $matches[0] as $image ) {
// This is inserted from our JS so HTML attributes should always be in double quotes.
if ( ! preg_match( '/src="([^"]+)"/', $image, $url_matches ) ) {
continue;
}
$image_src = $url_matches[1];
// Don't try to sideload a file without a file extension, leads to WP upload error.
if ( ! preg_match( '/[^\?]+\.(?:jpe?g|jpe|gif|png|webp)(?:\?|$)/i', $image_src ) ) {
continue;
}
// Sideload image, which gives us a new image src.
$new_src = media_sideload_image( $image_src, $post_id, null, 'src' );
if ( ! is_wp_error( $new_src ) ) {
// Replace the POSTED content <img> with correct uploaded ones.
// Need to do it in two steps so we don't replace links to the original image if any.
$new_image = str_replace( $image_src, $new_src, $image );
$content = str_replace( $image, $new_image, $content );
}
}
}
// Expected slashed.
return wp_slash( $content );
}
/**
* Ajax handler for saving the post as draft or published.
*
* @since 1.0.0
* @since 2.0.1 Added input sanitization for categories and taxonomies.
*/
public function save_post() {
// Verify a post ID is set first, then process the nonce since it uses the post ID.
$post_id = ( ! empty( $_POST['post_ID'] ) ? (int) $_POST['post_ID'] : null ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
if ( ! $post_id ) {
wp_send_json_error( array( 'errorMessage' => __( 'Missing post ID.', 'press-this' ) ) );
}
if ( empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'update-post_' . $post_id ) ||
! current_user_can( 'edit_post', $post_id ) ) {
wp_send_json_error( array( 'errorMessage' => __( 'Invalid post.', 'press-this' ) ) );
}
// Get the existing post to preserve its post type.
$existing_post = get_post( $post_id );
$post_type = $existing_post ? $existing_post->post_type : 'post';
$post_data = array(
'ID' => $post_id,
'post_title' => ( ! empty( $_POST['post_title'] ) ) ? sanitize_text_field( trim( $_POST['post_title'] ) ) : '',
'post_content' => ( ! empty( $_POST['post_content'] ) ) ? trim( $_POST['post_content'] ) : '',
'post_type' => $post_type,
'post_status' => 'draft',
'post_format' => ( ! empty( $_POST['post_format'] ) ) ? sanitize_text_field( $_POST['post_format'] ) : '',
);
// Sanitize category IDs with absint and verify capability.
$category_tax = get_taxonomy( 'category' );
if ( current_user_can( $category_tax->cap->assign_terms ) ) {
if ( ! empty( $_POST['post_category'] ) ) {
// Convert all values to integers and filter out zeros (invalid IDs).
$categories = array_map( 'absint', (array) $_POST['post_category'] );
$categories = array_filter( $categories );
$post_data['post_category'] = $categories;
} else {
$post_data['post_category'] = array();
}
}
// Sanitize taxonomy inputs with proper type handling.
if ( ! empty( $_POST['tax_input'] ) ) {
$tax_input = array();
foreach ( (array) $_POST['tax_input'] as $tax => $terms ) {
// Sanitize taxonomy key.
$tax = sanitize_key( $tax );
// Validate taxonomy exists.
$tax_object = get_taxonomy( $tax );
if ( ! $tax_object ) {
continue;
}
// Verify user has capability to assign terms.
if ( ! current_user_can( $tax_object->cap->assign_terms ) ) {
continue;
}
// Sanitize terms based on taxonomy type.
if ( is_taxonomy_hierarchical( $tax ) ) {
// Hierarchical taxonomies use term IDs (integers).
$tax_input[ $tax ] = array_map( 'absint', (array) $terms );
$tax_input[ $tax ] = array_filter( $tax_input[ $tax ] );
} else {
// Non-hierarchical taxonomies use term names (strings).
$tax_input[ $tax ] = array_map( 'sanitize_text_field', (array) $terms );
$tax_input[ $tax ] = array_filter( $tax_input[ $tax ] );
}
}
if ( ! empty( $tax_input ) ) {
$post_data['tax_input'] = $tax_input;
}
}
// Toggle status to pending if user cannot actually publish.
if ( ! empty( $_POST['post_status'] ) && 'publish' === $_POST['post_status'] ) {
if ( current_user_can( 'publish_posts' ) ) {
$post_data['post_status'] = 'publish';
} else {
$post_data['post_status'] = 'pending';
}
}
$post_data['post_content'] = $this->side_load_images( $post_id, $post_data['post_content'] );
/**
* Filters the post data of a Press This post before saving/updating.
*
* The {@see 'side_load_images'} action has already run at this point.
*
* @since 1.0.0
*
* @param array $post_data The post data.
*/
$post_data = apply_filters( 'press_this_save_post', $post_data );
$updated = wp_update_post( $post_data, true );
if ( is_wp_error( $updated ) ) {
wp_send_json_error( array( 'errorMessage' => $updated->get_error_message() ) );
} else {
if ( isset( $post_data['post_format'] ) ) {
if ( current_theme_supports( 'post-formats', $post_data['post_format'] ) ) {
set_post_format( $post_id, $post_data['post_format'] );
} elseif ( $post_data['post_format'] ) {
set_post_format( $post_id, false );
}
}
$force_redirect = false;
if ( 'publish' === get_post_status( $post_id ) ) {
$redirect = get_post_permalink( $post_id );
} elseif ( isset( $_POST['pt-force-redirect'] ) && 'true' === $_POST['pt-force-redirect'] ) {
$force_redirect = true;
$redirect = get_edit_post_link( $post_id, 'js' );
} else {
$redirect = false;
}
/**
* Filters the URL to redirect to when Press This saves.
*
* @since 1.0.0
*
* @param string $url Redirect URL. If `$status` is 'publish', this will be the post permalink.
* Otherwise, the default is false resulting in no redirect.
* @param int $post_id Post ID.
* @param string $status Post status.
*/
$redirect = apply_filters( 'press_this_save_redirect', $redirect, $post_id, $post_data['post_status'] );
if ( $redirect ) {
wp_send_json_success(
array(
'redirect' => $redirect,
'force' => $force_redirect,
)
);
} else {
wp_send_json_success( array( 'postSaved' => true ) );
}
}
}
/**
* Ajax handler for adding a new category.
*
* @since 1.0.0
*/
public function add_category() {
if ( false === wp_verify_nonce( $_POST['new_cat_nonce'], 'add-category' ) ) {
wp_send_json_error();
}
$taxonomy = get_taxonomy( 'category' );
if ( ! current_user_can( $taxonomy->cap->edit_terms ) || empty( $_POST['name'] ) ) {
wp_send_json_error();
}
$parent = isset( $_POST['parent'] ) && (int) $_POST['parent'] > 0 ? (int) $_POST['parent'] : 0;
$names = explode( ',', $_POST['name'] );
$added = array();
$data = array();
foreach ( $names as $cat_name ) {
$cat_name = trim( $cat_name );
$cat_nicename = sanitize_title( $cat_name );
if ( empty( $cat_nicename ) ) {
continue;
}
// @todo Find a more performant way to check existence, maybe get_term() with a separate parent check.
if ( term_exists( $cat_name, $taxonomy->name, $parent ) ) {
if ( count( $names ) === 1 ) {
wp_send_json_error( array( 'errorMessage' => __( 'This category already exists.', 'press-this' ) ) );
} else {
continue;
}
}
$cat_id = wp_insert_term( $cat_name, $taxonomy->name, array( 'parent' => $parent ) );
if ( is_wp_error( $cat_id ) ) {
continue;
} elseif ( is_array( $cat_id ) ) {
$cat_id = $cat_id['term_id'];
}
$added[] = $cat_id;
}
if ( empty( $added ) ) {
wp_send_json_error( array( 'errorMessage' => __( 'This category cannot be added. Please change the name and try again.', 'press-this' ) ) );
}
foreach ( $added as $new_cat_id ) {
$new_cat = get_category( $new_cat_id );
if ( is_wp_error( $new_cat ) ) {
wp_send_json_error( array( 'errorMessage' => __( 'Error while adding the category. Please try again later.', 'press-this' ) ) );
}
$data[] = array(
'term_id' => $new_cat->term_id,
'name' => $new_cat->name,
'parent' => $new_cat->parent,
);
}
wp_send_json_success( $data );
}
/**
* Utility method to limit an array to 50 values.
*
* @ignore
* @since 1.0.0
*
* @param array $value Array to limit.
* @return array Original array if fewer than 50 values, limited array, empty array otherwise.
*/
private function limit_array( $value ) {
if ( is_array( $value ) ) {
if ( count( $value ) > 50 ) {
return array_slice( $value, 0, 50 );
}
return $value;
}
return array();
}
/**
* Utility method to limit the length of a given string to 5,000 characters.
*
* @ignore
* @since 1.0.0
*
* @param string $value String to limit.
* @return bool|int|string If boolean or integer, that value. If a string, the original value
* if fewer than 5,000 characters, a truncated version, otherwise an
* empty string.
*/
private function limit_string( $value ) {
$return = '';
if ( is_numeric( $value ) || is_bool( $value ) ) {
$return = $value;
} elseif ( is_string( $value ) ) {
if ( mb_strlen( $value ) > 5000 ) {
$return = mb_substr( $value, 0, 5000 );
} else {
$return = $value;
}
$return = html_entity_decode( $return, ENT_QUOTES, 'UTF-8' );
$return = sanitize_text_field( trim( $return ) );
}
return $return;
}
/**
* Utility method to limit and validate a given URL.
*
* Applies defense-in-depth validation including:
* - String type check
* - 2048 character length limit
* - WordPress URL validation via wp_http_validate_url()
* - Scheme restriction to http/https only
*
* @ignore
* @since 1.0.0
* @since 2.0.1 Enhanced validation with wp_http_validate_url() and strict scheme checking.
*
* @param string $url URL to check for length and validity.
* @return string Escaped URL if valid. Empty string otherwise.
*/
private function limit_url( $url ) {
// Type check.
if ( ! is_string( $url ) ) {
return '';
}
// Length limit (2048 characters is de-facto browser standard).
if ( strlen( $url ) > 2048 ) {
return '';
}
// Decode URL-encoded characters for validation.
$decoded_url = urldecode( $url );
// If the URL is root-relative, prepend the protocol and domain name.
if ( $decoded_url && $this->domain && preg_match( '%^/[^/]+%', $decoded_url ) ) {
$decoded_url = $this->domain . $decoded_url;
}
// Use WordPress URL validation for comprehensive checks.
$validated = wp_http_validate_url( $decoded_url );
if ( ! $validated ) {
// Fall back to esc_url_raw with scheme restriction.
$validated = esc_url_raw( $decoded_url, array( 'http', 'https' ) );
}
// Empty after validation means invalid.
if ( empty( $validated ) ) {
return '';
}
// Final scheme check - must be http or https.
if ( ! preg_match( '#^https?://#i', $validated ) ) {
return '';
}
return $validated;
}
/**
* Utility method to limit image source URLs.
*
* Excluded URLs include share-this type buttons, loaders, spinners, spacers, WordPress interface images,
* tiny buttons or thumbs, mathtag.com or quantserve.com images, or the WordPress.com stats gif.
*
* @ignore
* @since 1.0.0
*
* @param string $src Image source URL.
* @return string If not matched an excluded URL type, the original URL, empty string otherwise.
*/
private function limit_img( $src ) {
$src = $this->limit_url( $src );
if ( preg_match( '!/ad[sx]?/!i', $src ) ) {
// Ads.
return '';
} elseif ( preg_match( '!(/share-?this[^.]+?\.[a-z0-9]{3,4})(\?.*)?$!i', $src ) ) {
// Share-this type button.
return '';
} elseif ( preg_match( '!/(spinner|loading|spacer|blank|rss)\.(gif|jpg|png)!i', $src ) ) {
// Loaders, spinners, spacers.
return '';
} elseif ( preg_match( '!/([^./]+[-_])?(spinner|loading|spacer|blank)s?([-_][^./]+)?\.[a-z0-9]{3,4}!i', $src ) ) {
// Fancy loaders, spinners, spacers.
return '';
} elseif ( preg_match( '!([^./]+[-_])?thumb[^.]*\.(gif|jpg|png)$!i', $src ) ) {
// Thumbnails, too small, usually irrelevant to context.
return '';
} elseif ( false !== stripos( $src, '/wp-includes/' ) ) {
// Classic WordPress interface images.
return '';
} elseif ( preg_match( '![^\d]\d{1,2}x\d+\.(gif|jpg|png)$!i', $src ) ) {
// Most often tiny buttons/thumbs (< 100px wide).
return '';
} elseif ( preg_match( '!/pixel\.(mathtag|quantserve)\.com!i', $src ) ) {
// See https://www.quantcast.com/how-we-do-it/iab-standard-measurement/how-we-collect-data/ and mathtag.com.
return '';
} elseif ( preg_match( '!/[gb]\.gif(\?.+)?$!i', $src ) ) {
// WordPress.com stats gif.
return '';
}
return $src;
}
/**
* Limit embed source URLs to specific providers.
*
* Not all core oEmbed providers are supported. Supported providers include YouTube, Vimeo,
* Daily Motion, SoundCloud, and Twitter.
*
* @ignore
* @since 1.0.0
*
* @param string $src Embed source URL.
* @return string If not from a supported provider, an empty string. Otherwise, a reformatted embed URL.
*/
private function limit_embed( $src ) {
$src = $this->limit_url( $src );
if ( empty( $src ) ) {
return '';
}
if ( preg_match( '!//(m|www)\.youtube\.com/(embed|v)/([^?]+)\?.+$!i', $src, $src_matches ) ) {
// Embedded Youtube videos (www or mobile).
$src = 'https://www.youtube.com/watch?v=' . $src_matches[3];
} elseif ( preg_match( '!//player\.vimeo\.com/video/([\d]+)([?/].*)?$!i', $src, $src_matches ) ) {
// Embedded Vimeo iframe videos.
$src = 'https://vimeo.com/' . (int) $src_matches[1];
} elseif ( preg_match( '!//vimeo\.com/moogaloop\.swf\?clip_id=([\d]+)$!i', $src, $src_matches ) ) {
// Embedded Vimeo Flash videos.
$src = 'https://vimeo.com/' . (int) $src_matches[1];
} elseif ( preg_match( '!//(www\.)?dailymotion\.com/embed/video/([^/?]+)([/?].+)?!i', $src, $src_matches ) ) {
// Embedded Daily Motion videos.
$src = 'https://www.dailymotion.com/video/' . $src_matches[2];
} else {
$oembed = _wp_oembed_get_object();
if ( ! $oembed->get_provider( $src, array( 'discover' => false ) ) ) {
$src = '';
}
}
return $src;
}
/**
* Process a meta data entry from the source.
*
* @ignore
* @since 1.0.0
*
* @param string $meta_name Meta key name.
* @param mixed $meta_value Meta value.
* @param array $data Associative array of source data.
* @return array Processed data array.
*/
private function process_meta_entry( $meta_name, $meta_value, $data ) {
if ( preg_match( '/:?(title|description|keywords|site_name)$/', $meta_name ) ) {
$data['_meta'][ $meta_name ] = $meta_value;
} else {
switch ( $meta_name ) {
case 'og:url':
case 'og:video':
case 'og:video:secure_url':
$meta_value = $this->limit_embed( $meta_value );
if ( ! isset( $data['_embeds'] ) ) {
$data['_embeds'] = array();
}
if ( ! empty( $meta_value ) && ! in_array( $meta_value, $data['_embeds'], true ) ) {
$data['_embeds'][] = $meta_value;
}
break;
case 'og:image':
case 'og:image:secure_url':
case 'twitter:image0:src':
case 'twitter:image0':
case 'twitter:image:src':
case 'twitter:image':
$meta_value = $this->limit_img( $meta_value );
if ( ! isset( $data['_images'] ) ) {
$data['_images'] = array();
}
if ( ! empty( $meta_value ) && ! in_array( $meta_value, $data['_images'], true ) ) {
$data['_images'][] = $meta_value;
}
break;
}
}
return $data;
}
/**
* Get the bookmarklet version from request data.
*
* Supports both legacy 'v' parameter (from URL) and new 'pt_version' (from POST).
*
* @since 2.0.1
*
* @return int|null Bookmarklet version number or null if not provided.
*/
private function get_bookmarklet_version() {
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended -- Bookmarklet data from external sites cannot include nonces.
// Modern bookmarklet sends pt_version via POST.
if ( ! empty( $_POST['pt_version'] ) ) {
return (int) $_POST['pt_version'];
}
// Legacy bookmarklet sends v via GET or POST.
if ( ! empty( $_POST['v'] ) ) {
return (int) $_POST['v'];
}
if ( ! empty( $_GET['v'] ) ) {
return (int) $_GET['v'];
}
// phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
return null;
}
/**
* Handles backward-compat with the legacy version of Press This by supporting its query string params.
*
* Server-side scraping has been removed in v2.0.1. All content extraction is now handled
* client-side by the bookmarklet. Legacy GET parameters (u, t, s, v) are still supported
* for backward compatibility with older bookmarklets.
*
* @since 1.0.0
* @since 2.0.1 Removed server-side scraping fallback. Added support for pt_version,
* _og_video, _jsonld, and alternate_canonical from enhanced bookmarklet.
*
* @return array
*/
public function merge_or_fetch_data() {
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended -- Bookmarklet data from external sites cannot include nonces.
// Get data from $_POST and $_GET, as appropriate ($_POST > $_GET), to remain backward compatible.
$data = array();
// Only instantiate the keys we want. Sanity check and sanitize each one.
// Legacy URL format: ?u=URL&t=TITLE&s=SELECTION&v=VERSION.
foreach ( array( 'u', 's', 't', 'v' ) as $key ) {
if ( ! empty( $_POST[ $key ] ) ) {
$value = wp_unslash( $_POST[ $key ] );
} elseif ( ! empty( $_GET[ $key ] ) ) {
$value = wp_unslash( $_GET[ $key ] );
} else {
continue;
}
if ( 'u' === $key ) {
$value = $this->limit_url( $value );
if ( preg_match( '%^(?:https?:)?//[^/]+%i', $value, $domain_match ) ) {
$this->domain = $domain_match[0];
}
} else {
$value = $this->limit_string( $value );
}
if ( ! empty( $value ) ) {
$data[ $key ] = $value;
}
}
// Get bookmarklet version (supports both legacy 'v' and modern 'pt_version').
$bookmarklet_version = $this->get_bookmarklet_version();
if ( null !== $bookmarklet_version ) {
$data['v'] = $bookmarklet_version;
}
/**
* Filters whether to enable in-source media discovery in Press This.
*
* @since 1.0.0
*
* @param bool $enable Whether to enable media discovery.
*/
if ( apply_filters( 'enable_press_this_media_discovery', true ) ) {
// Process POST data from modern bookmarklet (no server-side fallback).
foreach ( array( '_images', '_embeds', '_og_video' ) as $type ) {
if ( empty( $_POST[ $type ] ) ) {
continue;
}
if ( ! isset( $data[ $type ] ) ) {
$data[ $type ] = array();
}
$items = $this->limit_array( $_POST[ $type ] );
foreach ( $items as $key => $value ) {
if ( '_images' === $type ) {
$value = $this->limit_img( wp_unslash( $value ) );
} else {
// Both _embeds and _og_video are embed URLs.
$value = $this->limit_embed( wp_unslash( $value ) );
}
if ( ! empty( $value ) && ! in_array( $value, $data[ $type ], true ) ) {
// For _og_video, add to _embeds array instead of separate key.
if ( '_og_video' === $type ) {
if ( ! isset( $data['_embeds'] ) ) {
$data['_embeds'] = array();
}
if ( ! in_array( $value, $data['_embeds'], true ) ) {
$data['_embeds'][] = $value;
}
} else {
$data[ $type ][] = $value;
}
}
}
}
foreach ( array( '_meta', '_links', '_jsonld' ) as $type ) {
if ( empty( $_POST[ $type ] ) ) {
continue;
}
if ( ! isset( $data[ $type ] ) ) {
$data[ $type ] = array();
}
$items = $this->limit_array( $_POST[ $type ] );
foreach ( $items as $key => $value ) {
// Sanity check. These are associative arrays, $key is usually things like 'title', 'description', 'keywords', etc.
if ( empty( $key ) || strlen( $key ) > 100 ) {
continue;
}
if ( '_meta' === $type ) {
$value = $this->limit_string( wp_unslash( $value ) );
if ( ! empty( $value ) ) {
$data = $this->process_meta_entry( $key, $value, $data );
}
} elseif ( '_links' === $type ) {
// Support canonical, shortlink, icon, and alternate_canonical.
if ( in_array( $key, array( 'canonical', 'shortlink', 'icon', 'alternate_canonical' ), true ) ) {
$data[ $type ][ $key ] = $this->limit_url( wp_unslash( $value ) );
}
} elseif ( '_jsonld' === $type ) {
// Process JSON-LD structured data.
if ( in_array( $key, array( 'canonical', 'headline', 'description', 'image' ), true ) ) {
if ( 'canonical' === $key || 'image' === $key ) {
$data[ $type ][ $key ] = $this->limit_url( wp_unslash( $value ) );
} else {
$data[ $type ][ $key ] = $this->limit_string( wp_unslash( $value ) );
}
}
}
}
}
// Support passing a single image src as `i`.
if ( ! empty( $_REQUEST['i'] ) ) {
$img_src = $this->limit_img( wp_unslash( $_REQUEST['i'] ) );
if ( $img_src ) {
if ( empty( $data['_images'] ) ) {
$data['_images'] = array( $img_src );
} elseif ( ! in_array( $img_src, $data['_images'], true ) ) {
array_unshift( $data['_images'], $img_src );
}
}
}
}
// Detect window.name fallback mode (popup blocked on mobile).
// When window.open() fails, the bookmarklet stores scraped data in window.name
// and navigates with &wn=1. The React app reads window.name client-side;
// no server-side data parsing is needed.
$this->window_name_mode = ( ! empty( $_GET['wn'] ) && '1' === $_GET['wn'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
// phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
/**
* Filters the Press This data array.
*
* @since 1.0.0
*
* @param array $data Press This Data array.
*/
return apply_filters( 'press_this_data', $data );
}
/**
* Outputs the post format selection HTML.
*
* @since 1.0.0
*
* @param WP_Post $post Post object.
*/
public function post_formats_html( $post ) {
if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) ) {
$post_formats = get_theme_support( 'post-formats' );
if ( is_array( $post_formats[0] ) ) {
$post_format = get_post_format( $post->ID );
if ( ! $post_format ) {
$post_format = '0';
}
// Add in the current one if it isn't there yet, in case the current theme doesn't support it.
if ( $post_format && ! in_array( $post_format, $post_formats[0], true ) ) {
$post_formats[0][] = $post_format;
}
?>
<div id="post-formats-select">
<fieldset><legend class="screen-reader-text"><?php esc_html_e( 'Post Formats', 'press-this' ); ?></legend>
<input type="radio" name="post_format" class="post-format" id="post-format-0" value="0" <?php checked( $post_format, '0' ); ?> />
<label for="post-format-0" class="post-format-icon post-format-standard"><?php echo esc_html( get_post_format_string( 'standard' ) ); ?></label>
<?php
foreach ( $post_formats[0] as $format ) {
?>
<br />
<input type="radio" name="post_format" class="post-format" id="post-format-<?php echo esc_attr( $format ); ?>" value="<?php echo esc_attr( $format ); ?>" <?php checked( $post_format, $format ); ?> />
<label for="post-format-<?php echo esc_attr( $format ); ?>" class="post-format-icon post-format-<?php echo esc_attr( $format ); ?>"><?php echo esc_html( get_post_format_string( $format ) ); ?></label>
<?php
}
?>
</fieldset>
</div>
<?php
}
}
}
/**
* Outputs the categories HTML.
*
* @since 1.0.0
*
* @param WP_Post $post Post object.
*/
public function categories_html( $post ) {
$taxonomy = get_taxonomy( 'category' );
// Bail if user cannot assign terms.
if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
return;
}
// Only show "add" if user can edit terms.
if ( current_user_can( $taxonomy->cap->edit_terms ) ) {
?>
<button type="button" class="add-cat-toggle button-link" aria-expanded="false">
<span class="dashicons dashicons-plus"></span><span class="screen-reader-text"><?php esc_html_e( 'Toggle add category', 'press-this' ); ?></span>
</button>
<div class="add-category is-hidden">
<label class="screen-reader-text" for="new-category"><?php echo esc_html( $taxonomy->labels->add_new_item ); ?></label>
<input type="text" id="new-category" class="add-category-name" placeholder="<?php echo esc_attr( $taxonomy->labels->new_item_name ); ?>" value="" aria-required="true">
<label class="screen-reader-text" for="new-category-parent"><?php echo esc_html( $taxonomy->labels->parent_item_colon ); ?></label>
<div class="postform-wrapper">
<?php
wp_dropdown_categories(
array(
'taxonomy' => 'category',
'hide_empty' => 0,
'name' => 'new-category-parent',
'orderby' => 'name',
'hierarchical' => 1,
'show_option_none' => '— ' . $taxonomy->labels->parent_item . ' —',
)
);
?>
</div>
<button type="button" class="add-cat-submit"><?php esc_html_e( 'Add', 'press-this' ); ?></button>
</div>
<?php
}
?>
<div class="categories-search-wrapper">
<input id="categories-search" type="search" class="categories-search" placeholder="<?php esc_attr_e( 'Search categories by name', 'press-this' ); ?>">
<label for="categories-search">
<span class="dashicons dashicons-search"></span><span class="screen-reader-text"><?php esc_html_e( 'Search categories', 'press-this' ); ?></span>
</label>
</div>
<div aria-label="<?php esc_attr_e( 'Categories', 'press-this' ); ?>">
<ul class="categories-select">
<?php
wp_terms_checklist(
$post->ID,
array(
'taxonomy' => 'category',
'list_only' => true,
)
);
?>
</ul>
</div>
<?php
}
/**
* Outputs the tags HTML.
*
* @since 1.0.0
*
* @param WP_Post $post Post object.
*/
public function tags_html( $post ) {
$taxonomy = get_taxonomy( 'post_tag' );
$user_can_assign_terms = current_user_can( $taxonomy->cap->assign_terms );
$esc_tags = get_terms_to_edit( $post->ID, 'post_tag' );
if ( ! $esc_tags || is_wp_error( $esc_tags ) ) {
$esc_tags = '';
}
?>
<div class="tagsdiv" id="post_tag">
<div class="jaxtag">
<input type="hidden" name="tax_input[post_tag]" class="the-tags" value="<?php echo esc_attr( $esc_tags ); ?>">
<?php
if ( $user_can_assign_terms ) {
?>
<div class="ajaxtag hide-if-no-js">
<label class="screen-reader-text" for="new-tag-post_tag"><?php esc_html_e( 'Tags', 'press-this' ); ?></label>
<p>
<input type="text" id="new-tag-post_tag" name="newtag[post_tag]" class="newtag form-input-tip" size="16" autocomplete="off" value="" aria-describedby="new-tag-desc" />
<button type="button" class="tagadd"><?php esc_html_e( 'Add', 'press-this' ); ?></button>
</p>
</div>
<p class="howto" id="new-tag-desc">
<?php echo esc_html( $taxonomy->labels->separate_items_with_commas ); ?>
</p>
<?php
}
?>
</div>
<div class="tagchecklist"></div>
</div>
<?php
if ( $user_can_assign_terms ) {
?>
<button type="button" class="button-link tagcloud-link" id="link-post_tag" aria-expanded="false"><?php echo esc_html( $taxonomy->labels->choose_from_most_used ); ?></button>
<?php
}
}
/**
* Get a list of embeds with no duplicates.
*
* @since 1.0.0
*
* @param array $data The site's data.
* @return array Embeds selected to be available.
*/
public function get_embeds( $data ) {
$selected_embeds = array();
// Make sure to add the Pressed page if it's a valid oembed itself.
if ( ! empty( $data['u'] ) && $this->limit_embed( $data['u'] ) ) {
$data['_embeds'][] = $data['u'];
}
if ( ! empty( $data['_embeds'] ) ) {
foreach ( $data['_embeds'] as $src ) {
$prot_relative_src = preg_replace( '/^https?:/', '', $src );
if ( in_array( $prot_relative_src, $this->embeds, true ) ) {
continue;
}
$selected_embeds[] = $src;
$this->embeds[] = $prot_relative_src;
}
}
return $selected_embeds;
}
/**
* Get a list of images with no duplicates.
*
* @since 1.0.0
*
* @param array $data The site's data.
* @return array
*/
public function get_images( $data ) {
$selected_images = array();