Repository navigation
Expand file tree
/
Copy pathpress-this-plugin.php
More file actions
1712 lines (1516 loc) · 52.4 KB
/
Copy pathpress-this-plugin.php
File metadata and controls
1712 lines (1516 loc) · 52.4 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
*
* Plugin Name: Press This
* Plugin URI: https://wordpress.org
* Description: A little tool that lets you grab bits of the web and create new posts with ease. Now powered by the Gutenberg block editor.
* Version: 2.1.0
* Author: WordPress Contributors
* Author URI: https://wordpress.org
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* Text Domain: press-this
* Domain Path: /languages
* Requires at least: 6.9
* Requires PHP: 7.4
*
* @package wordpress/press-this
*/
/*
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License version 2, as published by the Free Software Foundation. You may NOT assume
* that you can use any other version of the GPL.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
/**
* Plugin version constant.
*
* @since 1.0.0
* @since 2.0.1 Updated for Gutenberg block editor integration.
*/
define( 'PRESS_THIS__VERSION', '2.1.0' );
/**
* Minimum WordPress version required for the Gutenberg features.
*
* @since 2.0.1
*/
define( 'PRESS_THIS__MIN_WP_VERSION', '6.9' );
/**
* Check if the current WordPress version is compatible.
*
* @since 2.0.1
*
* @return bool True if compatible, false otherwise.
*/
function press_this_is_compatible() {
global $wp_version;
return version_compare( $wp_version, PRESS_THIS__MIN_WP_VERSION, '>=' );
}
/**
* Display admin notice for incompatible WordPress version.
*
* @since 2.0.1
*/
function press_this_incompatible_notice() {
?>
<div class="notice notice-error">
<p>
<?php
printf(
/* translators: %s: Minimum WordPress version required. */
esc_html__( 'Press This 2.0 requires WordPress %s or higher. Please upgrade WordPress to use this version.', 'press-this' ),
esc_html( PRESS_THIS__MIN_WP_VERSION )
);
?>
</p>
</div>
<?php
}
// Backward compatibility check.
if ( ! press_this_is_compatible() ) {
add_action( 'admin_notices', 'press_this_incompatible_notice' );
return;
}
// Register AJAX handlers (legacy, kept for backward compatibility).
add_action( 'wp_ajax_press-this-plugin-save-post', 'wp_ajax_press_this_plugin_save_post' );
add_action( 'wp_ajax_press-this-plugin-add-category', 'wp_ajax_press_this_plugin_add_category' );
// Register REST API routes.
add_action( 'rest_api_init', 'press_this_register_rest_routes' );
// Register URL validation filter for HTTP requests.
add_filter( 'pre_http_request', 'press_this_validate_http_request_ip', 10, 3 );
// Register Tools page integration.
add_action( 'tool_box', 'press_this_tool_box' );
// Load text domain for translations.
add_action( 'init', 'press_this_load_textdomain' );
// Register WP-CLI commands.
if ( defined( 'WP_CLI' ) && WP_CLI ) {
require_once __DIR__ . '/includes/class-press-this-cli-commands.php';
WP_CLI::add_command( 'press-this', 'Press_This_CLI_Commands' );
}
/**
* Load plugin text domain for translations.
*
* @since 2.0.1
*/
function press_this_load_textdomain() {
load_plugin_textdomain( 'press-this', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
/**
* Ajax handler for saving a post from Press This.
*
* @since 1.0.0
*/
function wp_ajax_press_this_plugin_save_post() {
include_once plugin_dir_path( __FILE__ ) . 'class-wp-press-this-plugin.php';
$wp_press_this = new WP_Press_This_Plugin();
// Enable URL validation for image sideloading.
press_this_http_request_context( true );
$wp_press_this->save_post();
press_this_http_request_context( false );
}
/**
* Ajax handler for creating new category from Press This.
*
* @since 1.0.0
*/
function wp_ajax_press_this_plugin_add_category() {
include_once plugin_dir_path( __FILE__ ) . 'class-wp-press-this-plugin.php';
$wp_press_this = new WP_Press_This_Plugin();
$wp_press_this->add_category();
}
/**
* Register REST API routes for Press This.
*
* @since 2.0.1
*/
function press_this_register_rest_routes() {
// Web App Manifest for Add to Home Screen / PWA support.
register_rest_route(
'press-this/v1',
'/manifest',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'press_this_rest_manifest',
'permission_callback' => '__return_true',
)
);
// URL scraping endpoint for Direct Access Mode.
register_rest_route(
'press-this/v1',
'/scrape',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'press_this_rest_scrape_url',
'permission_callback' => 'press_this_rest_scrape_permission',
'args' => array(
'url' => array(
'required' => true,
'type' => 'string',
'sanitize_callback' => 'esc_url_raw',
),
),
)
);
// Save endpoint.
register_rest_route(
'press-this/v1',
'/save',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'press_this_rest_save_post',
'permission_callback' => 'press_this_rest_save_permission',
'args' => array(
'post_id' => array(
'required' => true,
'type' => 'integer',
'sanitize_callback' => 'absint',
),
'title' => array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => '',
),
'content' => array(
'type' => 'string',
'default' => '',
),
'status' => array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => 'draft',
'enum' => array( 'draft', 'publish', 'future' ),
),
'date' => array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
// Validates format only (ISO 8601 datetime). Semantic validation
// (e.g. month/day ranges, leap years) is handled server-side by
// strtotime() in the save handler, which rejects unparseable
// dates and normalizes edge cases like Feb 30 → Mar 2.
'validate_callback' => function ( $value ) {
if ( empty( $value ) ) {
return true;
}
if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2})?$/', $value ) ) {
return new WP_Error(
'press_this_invalid_date_format',
__( 'Date must be in ISO 8601 format.', 'press-this' ),
array( 'status' => 400 )
);
}
return true;
},
'default' => '',
),
'format' => array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => '',
),
'categories' => array(
'type' => 'array',
'items' => array( 'type' => 'integer' ),
'default' => array(),
),
'tags' => array(
'type' => 'array',
'items' => array( 'type' => 'string' ),
'default' => array(),
),
'featured_image' => array(
'type' => 'integer',
'sanitize_callback' => 'absint',
'default' => 0,
),
'force_redirect' => array(
'type' => 'boolean',
'default' => false,
),
),
)
);
// Sideload image endpoint (for featured image from scraped content).
register_rest_route(
'press-this/v1',
'/sideload',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'press_this_rest_sideload_image',
'permission_callback' => 'press_this_rest_sideload_permission',
'args' => array(
'url' => array(
'required' => true,
'type' => 'string',
'sanitize_callback' => 'esc_url_raw',
),
'post_id' => array(
'type' => 'integer',
'sanitize_callback' => 'absint',
'default' => 0,
),
),
)
);
// Validate embeds endpoint (filters URLs through WordPress oEmbed providers).
register_rest_route(
'press-this/v1',
'/validate-embeds',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'press_this_rest_validate_embeds',
'permission_callback' => 'press_this_rest_validate_embeds_permission',
'args' => array(
'urls' => array(
'required' => true,
'type' => 'array',
'items' => array( 'type' => 'string' ),
),
),
)
);
}
/**
* Permission callback for REST save endpoint.
*
* @since 2.0.1
*
* @param WP_REST_Request $request Request object.
* @return bool|WP_Error True if the user can edit the post, WP_Error otherwise.
*/
function press_this_rest_save_permission( $request ) {
$post_id = $request->get_param( 'post_id' );
if ( ! $post_id ) {
return new WP_Error(
'press_this_missing_post_id',
__( 'Missing post ID.', 'press-this' ),
array( 'status' => 400 )
);
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return new WP_Error(
'press_this_cannot_edit',
__( 'You do not have permission to edit this post.', 'press-this' ),
array( 'status' => 403 )
);
}
return true;
}
/**
* REST API handler for saving a post from Press This.
*
* @since 2.0.1
*
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response|WP_Error Response object on success, WP_Error on failure.
*/
function press_this_rest_save_post( $request ) {
include_once plugin_dir_path( __FILE__ ) . 'class-wp-press-this-plugin.php';
$post_id = $request->get_param( 'post_id' );
// 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' => $request->get_param( 'title' ),
'post_content' => wp_kses_post( $request->get_param( 'content' ) ),
'post_type' => $post_type,
'post_status' => 'draft',
'post_format' => $request->get_param( 'format' ),
);
// Handle categories if user can assign.
$category_tax = get_taxonomy( 'category' );
if ( current_user_can( $category_tax->cap->assign_terms ) ) {
$categories = $request->get_param( 'categories' );
if ( ! empty( $categories ) ) {
$post_data['post_category'] = array_map( 'absint', $categories );
}
}
// Handle tags if user can assign.
$tag_tax = get_taxonomy( 'post_tag' );
if ( current_user_can( $tag_tax->cap->assign_terms ) ) {
$tags = $request->get_param( 'tags' );
if ( ! empty( $tags ) ) {
$post_data['tax_input'] = array(
'post_tag' => array_map( 'sanitize_text_field', $tags ),
);
}
}
// Handle publish status.
$status = $request->get_param( 'status' );
if ( 'publish' === $status ) {
if ( current_user_can( 'publish_posts' ) ) {
$post_data['post_status'] = 'publish';
} else {
$post_data['post_status'] = 'pending';
}
}
// Handle future (scheduled) status.
// We intentionally don't reject past dates here. WordPress core's
// wp_insert_post() auto-converts future+past-date to 'publish', so
// a past date simply publishes immediately — matching core REST API behavior.
if ( 'future' === $status ) {
if ( current_user_can( 'publish_posts' ) ) {
$date = $request->get_param( 'date' );
if ( empty( $date ) || false === strtotime( $date ) ) {
return new WP_Error(
'press_this_invalid_date',
__( 'A valid date is required to schedule a post.', 'press-this' ),
array( 'status' => 400 )
);
}
// The frontend sends a naive datetime in the site's local timezone (no TZ qualifier).
// WordPress sets PHP's timezone to UTC, so strtotime() interprets the string as UTC
// and gmdate() formats it back as UTC -- the round-trip preserves the original value.
// The result is the site-local time string we need for post_date.
$post_data['post_date'] = gmdate( 'Y-m-d H:i:s', strtotime( $date ) );
$post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] );
$post_data['post_status'] = 'future';
// Required: wp_update_post ignores post_date changes unless edit_date is true.
$post_data['edit_date'] = true;
} else {
$post_data['post_status'] = 'pending';
}
}
// Side-load images from content.
// Require admin includes needed by media_sideload_image() (not loaded in REST context).
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
$wp_press_this = new WP_Press_This_Plugin();
press_this_http_request_context( true );
$post_data['post_content'] = $wp_press_this->side_load_images( $post_id, wp_slash( $post_data['post_content'] ) );
press_this_http_request_context( false );
$post_data['post_content'] = wp_unslash( $post_data['post_content'] );
/**
* Filters the post data of a Press This post before saving/updating.
*
* @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 ) ) {
// Log detailed error when WP_DEBUG is enabled, return generic message to user.
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG enabled.
error_log( 'Press This save_post error: ' . $updated->get_error_message() );
}
return new WP_Error(
'press_this_save_failed',
__( 'Unable to save the post. Please try again.', 'press-this' ),
array( 'status' => 500 )
);
}
// Set post format.
if ( ! empty( $post_data['post_format'] ) ) {
if ( current_theme_supports( 'post-formats', $post_data['post_format'] ) ) {
set_post_format( $post_id, $post_data['post_format'] );
} else {
set_post_format( $post_id, false );
}
}
// Set featured image.
$featured_image = $request->get_param( 'featured_image' );
if ( $featured_image && current_user_can( 'upload_files' ) ) {
// Validate that the attachment ID exists and is a valid image.
$attachment = get_post( $featured_image );
if ( $attachment && 'attachment' === $attachment->post_type && wp_attachment_is_image( $featured_image ) ) {
set_post_thumbnail( $post_id, $featured_image );
} elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
// Log invalid attachment IDs for debugging.
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log( sprintf( 'Press This: Invalid featured image ID %d for post %d', $featured_image, $post_id ) );
}
} elseif ( 0 === $featured_image ) {
delete_post_thumbnail( $post_id );
}
// Determine redirect URL.
$force_redirect = $request->get_param( 'force_redirect' );
$redirect = false;
if ( 'publish' === get_post_status( $post_id ) ) {
$redirect = get_post_permalink( $post_id );
} elseif ( $force_redirect ) {
$redirect = get_edit_post_link( $post_id, 'js' );
}
/**
* Filters the URL to redirect to when Press This saves.
*
* @since 1.0.0
*
* @param string $url Redirect URL.
* @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'] );
// Validate redirect URL is on same host or relative.
if ( $redirect ) {
$redirect_host = wp_parse_url( $redirect, PHP_URL_HOST );
$site_host = wp_parse_url( home_url(), PHP_URL_HOST );
// Block external redirects.
if ( $redirect_host && $redirect_host !== $site_host ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG enabled.
error_log( sprintf( 'Press This: Blocked external redirect to %s', esc_url( $redirect ) ) );
}
$redirect = get_edit_post_link( $post_id, 'raw' );
}
}
return rest_ensure_response(
array(
'success' => true,
'post_id' => $post_id,
'redirect' => $redirect,
'force' => $force_redirect,
)
);
}
/**
* Permission callback for REST sideload endpoint.
*
* @since 2.0.1
*
* @return bool|WP_Error True if the user can upload files, WP_Error otherwise.
*/
function press_this_rest_sideload_permission() {
if ( ! current_user_can( 'upload_files' ) ) {
return new WP_Error(
'press_this_cannot_upload',
__( 'You do not have permission to upload files.', 'press-this' ),
array( 'status' => 403 )
);
}
return true;
}
/**
* Permission callback for REST validate-embeds endpoint.
*
* @since 2.0.1
*
* @return bool|WP_Error True if the user can edit posts, WP_Error otherwise.
*/
function press_this_rest_validate_embeds_permission() {
if ( ! current_user_can( 'edit_posts' ) ) {
return new WP_Error(
'press_this_cannot_validate',
__( 'You do not have permission to use this feature.', 'press-this' ),
array( 'status' => 403 )
);
}
return true;
}
/**
* REST API handler for validating embed URLs.
*
* Takes an array of URLs and returns only those that are valid oEmbed providers.
* Uses WordPress's built-in oEmbed provider list plus known video platforms.
*
* @since 2.0.1
*
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response Response with valid embed URLs.
*/
function press_this_rest_validate_embeds( $request ) {
include_once plugin_dir_path( __FILE__ ) . 'class-wp-press-this-plugin.php';
$urls = $request->get_param( 'urls' );
$valid = array();
if ( ! is_array( $urls ) ) {
return rest_ensure_response( array( 'embeds' => array() ) );
}
// Create an instance to access limit_embed method.
$press_this = new WP_Press_This_Plugin();
// Use reflection to access the private limit_embed method.
$reflection = new ReflectionClass( $press_this );
$method = $reflection->getMethod( 'limit_embed' );
$method->setAccessible( true );
foreach ( $urls as $url ) {
if ( ! is_string( $url ) ) {
continue;
}
// Sanitize and validate the URL.
$url = esc_url_raw( $url );
if ( empty( $url ) ) {
continue;
}
// Use limit_embed to validate against oEmbed providers.
$validated = $method->invoke( $press_this, $url );
if ( ! empty( $validated ) ) {
$valid[] = $validated;
}
}
// Remove duplicates.
$valid = array_unique( $valid );
return rest_ensure_response( array( 'embeds' => array_values( $valid ) ) );
}
/**
* Get the allowed content types for image sideloading.
*
* Validates content types for image sideloading.
*
* @since 2.0.1
*
* @return array Array of allowed MIME types for image sideloading.
*/
function press_this_get_sideload_allowed_types() {
$default_types = array(
'image/jpeg',
'image/jpg',
'image/png',
'image/gif',
'image/webp',
);
/**
* Filters the allowed content types for image sideloading.
*
* Allows customization of accepted image MIME types.
*
* @since 2.0.1
*
* @param array $allowed_types Array of allowed MIME types.
*/
return apply_filters( 'press_this_sideload_allowed_types', $default_types );
}
/**
* Get the maximum file size for image sideloading.
*
* Configurable max file size for sideloading.
*
* @since 2.0.1
*
* @return int Maximum file size in bytes (default 10MB).
*/
function press_this_get_sideload_max_size() {
$default_max = 10 * 1024 * 1024; // 10MB.
/**
* Filters the maximum file size for image sideloading.
*
* @since 2.0.1
*
* @param int $max_size Maximum file size in bytes.
*/
return apply_filters( 'press_this_sideload_max_size', $default_max );
}
/**
* REST API handler for sideloading an external image to the media library.
*
* Validates content-type via HEAD request before download.
*
* @since 2.0.1
*
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response|WP_Error Response object on success, WP_Error on failure.
*/
function press_this_rest_sideload_image( $request ) {
include_once plugin_dir_path( __FILE__ ) . 'class-wp-press-this-plugin.php';
$url = $request->get_param( 'url' );
$post_id = $request->get_param( 'post_id' );
// Validate URL format.
if ( empty( $url ) || ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
return new WP_Error(
'press_this_invalid_url',
__( 'Invalid image URL.', 'press-this' ),
array( 'status' => 400 )
);
}
// Validate URL is safe to fetch.
$valid = press_this_validate_url_for_proxy( $url );
if ( is_wp_error( $valid ) ) {
$valid->add_data( array( 'status' => 400 ) );
return $valid;
}
// Perform HEAD request to validate content-type before full download.
$allowed_types = press_this_get_sideload_allowed_types();
$max_size = press_this_get_sideload_max_size();
press_this_http_request_context( true );
$head_response = wp_remote_head(
$url,
array(
'timeout' => 10,
'redirection' => 3,
'reject_unsafe_urls' => true,
)
);
press_this_http_request_context( false );
// If HEAD succeeds, validate content-type and size.
if ( ! is_wp_error( $head_response ) ) {
$content_type = wp_remote_retrieve_header( $head_response, 'content-type' );
// Extract base content-type (remove charset, boundary, etc.).
if ( $content_type ) {
$content_type = strtolower( trim( explode( ';', $content_type )[0] ) );
}
// Check content-type is an allowed image type.
if ( $content_type && ! in_array( $content_type, $allowed_types, true ) ) {
// Log detailed error when WP_DEBUG is enabled.
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG enabled.
error_log( sprintf( 'Press This sideload rejected content-type: %s for URL: %s', $content_type, $url ) );
}
return new WP_Error(
'press_this_invalid_image_type',
__( 'The URL does not point to a valid image file.', 'press-this' ),
array( 'status' => 400 )
);
}
// Check file size if Content-Length header is present.
$content_length = wp_remote_retrieve_header( $head_response, 'content-length' );
if ( $content_length && (int) $content_length > $max_size ) {
// Log detailed error when WP_DEBUG is enabled.
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG enabled.
error_log( sprintf( 'Press This sideload rejected file size: %d bytes for URL: %s', (int) $content_length, $url ) );
}
return new WP_Error(
'press_this_file_too_large',
__( 'The image file is too large.', 'press-this' ),
array( 'status' => 400 )
);
}
}
// If HEAD fails, proceed anyway - let media_handle_sideload validate.
// This handles servers that don't support HEAD requests.
// Require necessary files for media sideload.
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
// Download the file.
$tmp_file = press_this_download_url( $url, 30 );
if ( is_wp_error( $tmp_file ) ) {
// Log detailed error when WP_DEBUG is enabled.
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG enabled.
error_log( 'Press This sideload download error: ' . $tmp_file->get_error_message() );
}
return new WP_Error(
'press_this_download_failed',
__( 'Unable to download the image. Please try again.', 'press-this' ),
array( 'status' => 500 )
);
}
// Get the filename from URL.
$filename = basename( wp_parse_url( $url, PHP_URL_PATH ) );
if ( empty( $filename ) ) {
$filename = 'image';
}
// Prepare file array for sideloading.
$file_array = array(
'name' => sanitize_file_name( $filename ),
'tmp_name' => $tmp_file,
);
// Sideload the file.
$attachment_id = media_handle_sideload( $file_array, $post_id );
// Clean up temp file if sideload failed.
if ( is_wp_error( $attachment_id ) ) {
wp_delete_file( $tmp_file );
// Log detailed error when WP_DEBUG is enabled.
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when WP_DEBUG enabled.
error_log( 'Press This sideload error: ' . $attachment_id->get_error_message() );
}
return new WP_Error(
'press_this_sideload_failed',
__( 'Unable to process the image. Please try again.', 'press-this' ),
array( 'status' => 500 )
);
}
// Get the attachment data.
$attachment_url = wp_get_attachment_url( $attachment_id );
$attachment = wp_get_attachment_metadata( $attachment_id );
return rest_ensure_response(
array(
'success' => true,
'id' => $attachment_id,
'url' => $attachment_url,
'width' => isset( $attachment['width'] ) ? $attachment['width'] : 0,
'height' => isset( $attachment['height'] ) ? $attachment['height'] : 0,
)
);
}
/**
* Adds metabox on wp-admin/tools.php
*
* @since 1.0.0
* @since 2.0.1 Updated description to mention block editor.
*/
function press_this_tool_box() {
if ( current_user_can( 'edit_posts' ) ) {
?>
<div class="card pressthis">
<h2><?php esc_html_e( 'Press This', 'press-this' ); ?></h2>
<p><?php esc_html_e( 'Press This is a little tool that lets you grab bits of the web and create new posts with ease.', 'press-this' ); ?>
<?php esc_html_e( 'It will even allow you to choose from images or videos included on the page and use them in your post.', 'press-this' ); ?>
<?php esc_html_e( 'Use Press This as a quick and lightweight way to highlight another page on the web.', 'press-this' ); ?>
</p>
<p class="description">
<?php esc_html_e( 'Now featuring the WordPress block editor for a modern editing experience.', 'press-this' ); ?>
</p>
<form>
<h3><?php esc_html_e( 'Install Press This', 'press-this' ); ?></h3>
<h4><?php esc_html_e( 'Direct link (best for mobile)', 'press-this' ); ?></h4>
<p><a href="<?php echo esc_url( admin_url( 'press-this.php' ) ); ?>"><?php esc_html_e( 'Open Press This', 'press-this' ); ?></a>
<?php esc_html_e( 'then add it to your device’s bookmarks or home screen.', 'press-this' ); ?>
</p>
<h4><?php esc_html_e( 'Bookmarklet', 'press-this' ); ?></h4>
<p><?php esc_html_e( 'Drag the bookmarklet below to your bookmarks bar. Then, when you’re on a page you want to share, simply “press” it.', 'press-this' ); ?></p>
<p class="pressthis-bookmarklet-wrapper">
<?php
// Use esc_attr() instead of esc_url() because esc_url() strips javascript: protocol.
// The bookmarklet link is trusted (we generate it) and needs the javascript: prefix.
?>
<a class="pressthis-bookmarklet" onclick="return false;" href="<?php echo esc_attr( press_this_get_shortcut_link() ); ?>"><span><?php esc_html_e( 'Press This', 'press-this' ); ?></span></a>
<button type="button" class="button pressthis-js-toggle js-show-pressthis-code-wrap" aria-expanded="false" aria-controls="pressthis-code-wrap">
<span class="dashicons dashicons-clipboard"></span>
<span class="screen-reader-text"><?php esc_html_e( 'Copy “Press This” bookmarklet code', 'press-this' ); ?></span>
</button>
</p>
<div class="hidden js-pressthis-code-wrap clear" id="pressthis-code-wrap">
<p id="pressthis-code-desc">
<?php esc_html_e( 'If you can’t drag the bookmarklet to your bookmarks, copy the following code and create a new bookmark. Paste the code into the new bookmark’s URL field.', 'press-this' ); ?>
</p>
<p>
<textarea class="js-pressthis-code" rows="5" cols="120" readonly="readonly" aria-labelledby="pressthis-code-desc"><?php echo esc_textarea( press_this_get_shortcut_link() ); ?></textarea>
</p>
</div>
<script>
jQuery( document ).ready( function( $ ) {
var $showPressThisWrap = $( '.js-show-pressthis-code-wrap' );
var $pressthisCode = $( '.js-pressthis-code' );
$showPressThisWrap.on( 'click', function( event ) {
var $this = $( this );
$this.parent().next( '.js-pressthis-code-wrap' ).slideToggle( 200 );
$this.attr( 'aria-expanded', $this.attr( 'aria-expanded' ) === 'false' ? 'true' : 'false' );
});
// Select Press This code when focusing (tabbing) or clicking the textarea.
$pressthisCode.on( 'click focus', function() {
var self = this;
setTimeout( function() { self.select(); }, 50 );
});
});
</script>
</form>
</div>
<?php
}
}
/**
* Retrieves the Press This bookmarklet link.
*
* @since Core/2.6.0
* @since 1.1.0 Added to Press This plugin.
* @since 2.0.1 Updated for modern bookmarklet with enhanced data extraction.
*
* @global bool $is_IE Whether the browser matches an Internet Explorer user agent.
*
* @return string The bookmarklet JavaScript code.
*/
function press_this_get_shortcut_link() {
global $is_IE;
include_once plugin_dir_path( __FILE__ ) . 'class-wp-press-this-plugin.php';
$link = '';
if ( $is_IE ) {
/*
* Return the old/shorter bookmarklet code for MSIE 8 and lower,
* since they only support a max length of ~2000 characters for
* bookmark[let] URLs, which is way too small for our smarter one.
* Do update the version number so users do not get the "upgrade your
* bookmarklet" notice when using PT in those browsers.
*/
$ua = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
if ( ! empty( $ua ) && preg_match( '/\bMSIE (\d)/', $ua, $matches ) && (int) $matches[1] <= 8 ) {
$url = wp_json_encode( admin_url( 'press-this.php' ) );
$link = 'javascript:var d=document,w=window,e=w.getSelection,k=d.getSelection,x=d.selection,' .
's=(e?e():(k)?k():(x?x.createRange().text:0)),f=' . $url . ',l=d.location,e=encodeURIComponent,' .
'u=f+"?u="+e(l.href)+"&t="+e(d.title)+"&s="+e(s)+"&v=' . WP_Press_This_Plugin::VERSION . '";' .
'a=function(){if(!w.open(u,"t","toolbar=0,resizable=1,scrollbars=1,status=1,width=600,height=700"))l.href=u;};' .
'if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else a();void(0)';
}
}
if ( empty( $link ) ) {
$src = @file_get_contents( plugin_dir_path( __FILE__ ) . 'assets/bookmarklet.min.js' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if ( $src ) {
$url = wp_json_encode( admin_url( 'press-this.php' ) . '?v=' . WP_Press_This_Plugin::VERSION );
$link = 'javascript:' . str_replace( 'window.pt_url', $url, $src );
}
}
$link = str_replace( array( "\r", "\n", "\t" ), '', $link );
/**
* Filters the Press This bookmarklet link.
*
* @since 2.6.0
*
* @param string $link The Press This bookmarklet link.
*/
return apply_filters( 'shortcut_link', $link );
}
/**
* Get the Press This editor page URL.
*
* @since 2.0.1
*
* @param string $url Optional. URL to press. Default empty.
* @return string Press This editor URL.
*/
function press_this_get_editor_url( $url = '' ) {
$editor_url = admin_url( 'press-this.php' );
if ( ! empty( $url ) ) {
$editor_url = add_query_arg( 'u', rawurlencode( $url ), $editor_url );
}
return $editor_url;
}
/**
* Check if the URL proxy feature is enabled.
*
* The proxy allows Direct Access Mode to fetch and scrape URLs server-side.
* Disabled by default to only fetch content from known external URLs.
* Site owners can enable it via the 'press_this_enable_url_proxy' filter.
*
* @since 2.0.1
*
* @return bool True if URL proxy is enabled, false otherwise.
*/
function press_this_is_proxy_enabled() {
/**
* Filters whether the URL proxy feature is enabled.
*
* When enabled, Press This can fetch URLs server-side for Direct Access Mode.
* Disabled by default to limit URL fetching to known sources.
*
* @since 2.0.1
*
* @param bool $enabled Whether the proxy is enabled. Default false.
*/
return apply_filters( 'press_this_enable_url_proxy', false );
}
/**
* REST callback for Web App Manifest.
*
* Returns a JSON manifest for Add to Home Screen / PWA support.
* Must be publicly accessible so the browser can fetch it without authentication.