-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebhook-plugin.php
More file actions
1249 lines (1078 loc) · 48.6 KB
/
webhook-plugin.php
File metadata and controls
1249 lines (1078 loc) · 48.6 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
/**
* Plugin Name: Simple Webhook Handler
* Description: Custom API-Rest webhook endpoint for media upload, post creation and post retrivael.
* Author: Felipe Matos
* Version: 1.9.18
*/
class Webhook_Handler {
public function __construct() {
register_activation_hook(__FILE__, [$this, 'activate']);
register_deactivation_hook(__FILE__, [$this, 'deactivate']);
add_action('rest_api_init', [$this, 'register_routes']);
add_filter('rest_pre_dispatch', [$this, 'log_invalid_json_request'], 10, 3);
add_action('admin_menu', [$this, 'add_settings_page']);
add_action('admin_init', [$this, 'register_settings']);
add_action('wp_ajax_start_webhook_test', [$this, 'start_test_mode']);
add_action('wp_ajax_stop_webhook_test', [$this, 'stop_test_mode']);
add_action('wp_ajax_get_webhook_test', [$this, 'get_test_results']);
add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
add_action('wp_ajax_get_logs', [$this, 'ajax_get_logs']);
add_action('wp_ajax_clear_logs', [$this, 'clear_logs']);
add_action('wp_ajax_refresh_auth_key', [$this, 'refresh_auth_key']);
add_action('wp_ajax_toggle_trigger', [$this, 'ajax_toggle_trigger']);
add_action('wp_ajax_save_trigger_url', [$this, 'ajax_save_trigger_url']);
add_action('wp_ajax_save_trigger_headers', [$this, 'ajax_save_trigger_headers']);
// Add trigger hooks
add_action('save_post', [$this, 'handle_post_created'], 10, 3);
add_action('transition_post_status', [$this, 'handle_post_published'], 10, 3);
add_action('wp_insert_comment', [$this, 'handle_new_comment'], 10, 2);
// Add plugin action links
add_filter('plugin_action_links_' . plugin_basename(__FILE__), [$this, 'plugin_settings_link']);
// Update version on plugin load
if (!function_exists('get_plugin_data')) {
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
}
$plugin_data = get_plugin_data(__FILE__);
update_option('webhook_plugin_version', $plugin_data['Version']);
}
public function plugin_settings_link($links) {
$settings_link = '<a href="options-general.php?page=webhook-settings">' . __('Settings') . '</a>';
array_unshift($links, $settings_link);
return $links;
}
public function create_log_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'webhook_logs';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
time datetime NOT NULL,
endpoint varchar(100) NOT NULL,
method varchar(10) NOT NULL,
headers text NOT NULL,
params text NOT NULL,
files text NOT NULL,
response text NOT NULL,
status_code smallint(3) NOT NULL,
ip varchar(45) NOT NULL,
direction varchar(10) DEFAULT 'incoming',
PRIMARY KEY (id),
KEY endpoint (endpoint),
KEY status_code (status_code)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
public function register_routes() {
register_rest_route('webhook/v1', '/(?P<action>[a-zA-Z0-9-_]+)', [
'methods' => 'POST',
'callback' => [$this, 'handle_request'],
'permission_callback' => [$this, 'verify_request'],
'args' => [
'action' => [
'required' => true,
'validate_callback' => function($param) {
return in_array($param, ['upload', 'create-post']);
}
]
]
]);
}
public function add_settings_page() {
add_options_page(
'Webhook Settings',
'Webhook',
'manage_options',
'webhook-settings',
[$this, 'render_settings_page']
);
}
public function register_settings() {
// Auto-generate key if empty
if(empty(get_option('webhook_auth_key'))) {
update_option('webhook_auth_key', wp_generate_password(32, false));
}
register_setting('webhook_settings', 'webhook_auth_key');
register_setting('webhook_settings', 'webhook_endpoint');
// Register trigger settings
register_setting('webhook_settings', 'webhook_trigger_post_created');
register_setting('webhook_settings', 'webhook_trigger_post_created_url');
register_setting('webhook_settings', 'webhook_trigger_post_created_headers');
register_setting('webhook_settings', 'webhook_trigger_post_published');
register_setting('webhook_settings', 'webhook_trigger_post_published_url');
register_setting('webhook_settings', 'webhook_trigger_post_published_headers');
register_setting('webhook_settings', 'webhook_trigger_new_comment');
register_setting('webhook_settings', 'webhook_trigger_new_comment_url');
register_setting('webhook_settings', 'webhook_trigger_new_comment_headers');
add_settings_section(
'webhook_main',
'Webhook Settings',
null,
'webhook-settings'
);
add_settings_section(
'webhook_security',
'Security Settings',
null,
'webhook-settings'
);
add_settings_field(
'webhook_auth_key',
'API Auth Key',
[$this, 'auth_key_field'],
'webhook-settings',
'webhook_security'
);
add_settings_field(
'webhook_endpoints',
'Endpoint URLs',
[$this, 'endpoint_url_fields'],
'webhook-settings',
'webhook_main'
);
add_settings_field(
'webhook_rate_limit',
'Rate Limit',
[$this, 'rate_limit_field'],
'webhook-settings',
'webhook_security'
);
}
public function render_settings_page() {
?>
<div class="wrap">
<h2>Simple Webhook Handler Settings</h2>
<p>Plugin Version: <?php echo esc_html(get_option('webhook_plugin_version')); ?></p>
<!-- Test Mode Section -->
<div class="card">
<h3>Test Webhook</h3>
<button id="testToggle" class="button button-primary">
<span class="text">Start Listening</span>
<span class="spinner"></span>
</button>
<div id="testStatus" style="display:none;margin-top:15px;">
<div class="notice notice-info">
<p>Waiting for requests... <span class="dashicons dashicons-update spin"></span></p>
</div>
<div id="testResults"></div>
</div>
</div>
<!-- Docs Section -->
<div class="card" style="margin-top:20px;">
<h3>API Documentation</h3>
<?php
$site_url = site_url();
$auth_key = get_option('webhook_auth_key');
// Get docs content with real values
$docs = file_get_contents(__DIR__.'/readme.md');
$docs = str_replace(
['https://yoursite.com', 'YOUR_KEY'],
[$site_url, $auth_key],
$docs
);
echo "<div class='endpoint-doc'>
<pre><code>".esc_html($docs)."</code></pre>
</div>";
?>
</div>
<!-- Triggers Section -->
<div class="card">
<h3>Triggers</h3>
<p>Configure webhooks to be triggered on specific WordPress events.</p>
<div class="trigger-item">
<label>
<input type="checkbox" name="webhook_trigger_post_created"
<?php checked(get_option('webhook_trigger_post_created'), 'on'); ?> />
When a new blog post is created
</label>
<input type="url" name="webhook_trigger_post_created_url"
value="<?php echo esc_attr(get_option('webhook_trigger_post_created_url')); ?>"
placeholder="Enter webhook URL" class="regular-text" />
<button type="button" class="button toggle-headers" data-trigger="post_created">Custom Headers</button>
<div class="custom-headers" style="display:none;">
<textarea name="webhook_trigger_post_created_headers" rows="3" class="large-text"
placeholder='Enter headers in JSON format, e.g: {"X-Auth-Key": "your-key"}'><?php echo esc_textarea(get_option('webhook_trigger_post_created_headers')); ?></textarea>
</div>
</div>
<div class="trigger-item">
<label>
<input type="checkbox" name="webhook_trigger_post_published"
<?php checked(get_option('webhook_trigger_post_published'), 'on'); ?> />
When a blog post is published
</label>
<input type="url" name="webhook_trigger_post_published_url"
value="<?php echo esc_attr(get_option('webhook_trigger_post_published_url')); ?>"
placeholder="Enter webhook URL" class="regular-text" />
<button type="button" class="button toggle-headers" data-trigger="post_published">Custom Headers</button>
<div class="custom-headers" style="display:none;">
<textarea name="webhook_trigger_post_published_headers" rows="3" class="large-text"
placeholder='Enter headers in JSON format, e.g: {"X-Auth-Key": "your-key"}'><?php echo esc_textarea(get_option('webhook_trigger_post_published_headers')); ?></textarea>
</div>
</div>
<div class="trigger-item">
<label>
<input type="checkbox" name="webhook_trigger_new_comment"
<?php checked(get_option('webhook_trigger_new_comment'), 'on'); ?> />
When a new comment is received
</label>
<input type="url" name="webhook_trigger_new_comment_url"
value="<?php echo esc_attr(get_option('webhook_trigger_new_comment_url')); ?>"
placeholder="Enter webhook URL" class="regular-text" />
<button type="button" class="button toggle-headers" data-trigger="new_comment">Custom Headers</button>
<div class="custom-headers" style="display:none;">
<textarea name="webhook_trigger_new_comment_headers" rows="3" class="large-text"
placeholder='Enter headers in JSON format, e.g: {"X-Auth-Key": "your-key"}'><?php echo esc_textarea(get_option('webhook_trigger_new_comment_headers')); ?></textarea>
</div>
</div>
</div>
<!-- Log viewer section -->
<div class="card">
<h3>Recent Logs</h3>
<div class="log-controls">
<button class="button" id="refreshLogs">Refresh</button>
<button class="button button-danger" id="clearLogs">Clear All Logs</button>
</div>
<div id="webhookLogsContainer"></div>
</div>
<!-- Existing Settings Form -->
<form action="options.php" method="post">
<?php
settings_fields('webhook_settings');
do_settings_sections('webhook-settings');
?>
</form>
</div>
<script>
jQuery(document).ready(function($) {
const toggle = $('#testToggle');
const status = $('#testStatus');
let isTesting = false;
toggle.click(function(e) {
e.preventDefault();
isTesting = !isTesting;
$.post(ajaxurl, {
action: isTesting ? 'start_webhook_test' : 'stop_webhook_test',
security: '<?php echo wp_create_nonce('webhook_test'); ?>'
}, function(response) {
status.toggle(isTesting);
toggle.find('.text').text(isTesting ? 'Stop Testing' : 'Start Listening');
toggle.toggleClass('button-primary button-secondary');
});
if(isTesting) checkForResults();
});
function checkForResults() {
if(!isTesting) return;
$.get(ajaxurl + '?action=get_webhook_test', function(data) {
$('#testResults').html('<pre>' + JSON.stringify(data, null, 2) + '</pre>');
setTimeout(checkForResults, 2000);
});
}
// Log viewer
const logContainer = $('#webhookLogsContainer');
const refreshButton = $('#refreshLogs');
const clearButton = $('#clearLogs');
refreshButton.click(function(e) {
e.preventDefault();
$.post(ajaxurl, {
action: 'get_logs',
security: '<?php echo wp_create_nonce('webhook_logs'); ?>',
page: 1
}, function(response) {
if(response.success) {
logContainer.html(response.data.html);
} else {
console.error('Error loading logs:', response.data);
logContainer.html('<div class="notice notice-error">Error loading logs</div>');
}
}).fail(function(xhr) {
console.error('Log request failed:', xhr.responseText);
logContainer.html('<div class="notice notice-error">Request failed: ' + xhr.statusText + '</div>');
});
});
clearButton.click(function(e) {
e.preventDefault();
$.post(ajaxurl, {
action: 'clear_logs',
security: '<?php echo wp_create_nonce('webhook_logs'); ?>'
}, function(response) {
if(response.success) {
logContainer.html('');
} else {
console.error('Error clearing logs:', response.data);
}
});
});
// Refresh auth key
$('#refresh-auth-key').click(function(e) {
e.preventDefault();
$.post(ajaxurl, {
action: 'refresh_auth_key',
security: '<?php echo wp_create_nonce('webhook_auth_key'); ?>'
}, function(response) {
if(response.success) {
$('#webhook_auth_key').val(response.data);
} else {
console.error('Error refreshing auth key:', response.data);
}
});
});
// Copy auth key
$('#copy-auth-key').click(function(e) {
e.preventDefault();
const authKey = document.getElementById("webhook_auth_key");
authKey.select();
document.execCommand("copy");
alert("Auth Key copied to clipboard");
});
});
</script>
<?php
}
public function enqueue_assets($hook) {
if ('settings_page_webhook-settings' !== $hook) {
return;
}
// Enqueue clipboard.js
wp_enqueue_script(
'clipboard',
'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.11/clipboard.min.js',
[],
'2.0.11'
);
// Enqueue our plugin scripts and styles
wp_enqueue_script('webhook-logs', plugins_url('assets/logs.js', __FILE__), array('jquery'), '1.0', true);
wp_enqueue_script('webhook-triggers', plugins_url('assets/triggers.js', __FILE__), array('jquery'), '1.0', true);
wp_enqueue_style('webhook-style', plugins_url('assets/style.css', __FILE__));
wp_enqueue_style('webhook-triggers', plugins_url('assets/triggers.css', __FILE__));
// Localize script with nonce
wp_localize_script('webhook-logs', 'webhook_settings', array(
'nonce' => wp_create_nonce('webhook_nonce')
));
wp_localize_script('webhook-triggers', 'webhook_settings', array(
'nonce' => wp_create_nonce('webhook_nonce')
));
wp_add_inline_script('clipboard', "document.addEventListener('DOMContentLoaded', function() { new ClipboardJS('.copy-key, .copy-url', { text: function(trigger) { return trigger.dataset.clipboardTarget ? document.querySelector(trigger.dataset.clipboardTarget).value : trigger.dataset.clipboardText; }}); });");
wp_enqueue_style(
'webhook-test-mode',
plugins_url('assets/test-mode.css', __FILE__)
);
wp_enqueue_style(
'webhook-logs',
plugins_url('assets/logs.css', __FILE__)
);
wp_enqueue_script(
'webhook-settings',
plugins_url('assets/logs.js', __FILE__),
['jquery', 'clipboard'],
'1.0',
true
);
wp_localize_script('webhook-settings', 'webhookLogs', [
'nonce' => wp_create_nonce('webhook_logs')
]);
}
public function start_test_mode() {
set_transient('webhook_test_mode', true, 3600);
delete_transient('webhook_test_data'); // Clear previous test data
wp_send_json_success([
'message' => 'Test mode activated',
'test_active' => true
]);
}
public function stop_test_mode() {
delete_transient('webhook_test_mode');
delete_transient('webhook_test_data');
wp_send_json_success([
'message' => 'Test mode deactivated',
'test_active' => false
]);
}
public function get_test_results() {
if (!get_transient('webhook_test_mode')) {
wp_send_json_success(['test_active' => false]);
return;
}
$data = get_transient('webhook_test_data');
if(!$data) {
wp_send_json_success([
'test_active' => true,
'message' => 'Waiting for requests...'
]);
return;
}
wp_send_json_success([
'test_active' => true,
'results' => $data
]);
}
public function clear_logs() {
check_ajax_referer('webhook_logs', 'security');
global $wpdb;
$table_name = $wpdb->prefix . 'webhook_logs';
$wpdb->query("TRUNCATE TABLE {$table_name}");
wp_send_json_success();
}
public function refresh_auth_key() {
check_ajax_referer('webhook_auth_key', 'security');
$new_key = wp_generate_password(32, false);
update_option('webhook_auth_key', $new_key);
wp_send_json_success(['data' => $new_key]);
}
public function auth_key_field() {
$key = esc_attr(get_option('webhook_auth_key'));
echo "<div class='auth-key-wrapper' style='display:flex;gap:10px;align-items:center;'>
<input type='text' id='webhook_auth_key' value='{$key}' class='regular-text' readonly>
<button type='button' id='refresh-auth-key' class='button'><span class='dashicons dashicons-update'></span></button>
<button type='button' id='copy-auth-key' class='button'><span class='dashicons dashicons-admin-page'></span></button>
</div>";
echo "<p class='description'>Authentication key required in X-Auth-Key header</p>";
}
public function endpoint_url_fields() {
$base_url = rest_url('webhook/v1/');
$endpoints = [
'upload' => 'Media Upload',
'create-post' => 'Create Post',
'get-post' => 'Get Post'
];
echo "<table class='form-table'><tbody>";
foreach($endpoints as $path => $label) {
$full_url = $base_url . $path;
echo "<tr>
<th scope='row'>{$label}</th>
<td>
<div style='display:flex;gap:10px;align-items:center;'>
<input type='text' value='{$full_url}' class='regular-text' readonly>
<button type='button' class='button button-secondary copy-url' data-clipboard-text='{$full_url}'>
<span class='dashicons dashicons-clipboard'></span>
</button>
</div>
</td>
</tr>";
}
echo "</tbody></table>";
}
public function rate_limit_field() {
echo "<p class='description'>Rate limiting is enabled by default. Maximum 5 requests per minute.</p>";
}
public function get_post($request) {
// Validate that postId is provided
if ( empty( $request['postId'] ) ) {
return new WP_Error('missing_postId', 'Post ID is required', ['status' => 400]); }
$postId = absint( $request['postId'] );
$post = get_post( $postId );
if ( !$post ) {
return new WP_Error('not_found', 'Post not found', ['status' => 404]); }
return (array) $post; }
private function get_auth_key() {
return get_option('webhook_auth_key');
}
public function handle_request($request) {
global $wpdb;
try {
// Verificação de autorização já realizada pelo 'permission_callback'
// Verificar Limitação de Taxa
if ($this->is_rate_limited()) {
return $this->format_error_response(new WP_Error('rate_limited', 'Too many requests', ['status' => 429]));
}
$response_data = $this->process_request($request);
$status_code = is_wp_error($response_data) ? ($response_data->get_error_data()['status'] ?? 500) : 200;
if (!is_wp_error($response_data) && is_array($response_data) && isset($response_data['mediaId'])) {
$data = array_merge(['success' => true], $response_data);
} else {
$response_json = is_wp_error($response_data) ? $response_data->get_error_message() : $response_data;
$data = [
'success' => !is_wp_error($response_data),
'data' => $response_json
];
}
// Log the response data before sending
$log_data = [
'time' => current_time('mysql'),
'endpoint' => $request->get_route(),
'method' => $request->get_method(),
'headers' => wp_json_encode($request->get_headers(), JSON_UNESCAPED_SLASHES),
'params' => wp_json_encode($request->get_params(), JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES),
'files' => wp_json_encode($request->get_file_params(), JSON_UNESCAPED_SLASHES),
'ip' => $_SERVER['REMOTE_ADDR'],
'status_code' => $status_code,
'response' => wp_json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
];
// Insert log into the database
$log_result = $wpdb->insert(
$wpdb->prefix . 'webhook_logs',
$log_data,
['%s','%s','%s','%s','%s','%s','%d','%s']
);
if (false === $log_result) {
error_log('Webhook Logging Failed: ' . $wpdb->last_error);
}
// Set response headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
// Send JSON response
wp_send_json($data);
} catch (Exception $e) {
error_log('Webhook Critical Error: ' . $e->getMessage());
return new WP_REST_Response([
'error' => [
'code' => 'internal_error',
'message' => 'Internal Server Error',
'details' => WP_DEBUG ? $e->getMessage() : null
]
], 500);
}
}
/**
* Unescapes a string by converting HTML entities and special characters back to their original form
*
* @param string $string The string to unescape
* @return string The unescaped string
*/
private function unescape_string($string) {
return html_entity_decode(stripslashes($string), ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
/**
* Decodes a JSON field that might be a string or already an array
*
* @param mixed $field The field to decode
* @return array The decoded array or empty array if invalid
*/
private function decode_json_field($field) {
if (empty($field)) {
return [];
}
if (is_array($field)) {
return $field;
}
if (is_string($field)) {
$decoded = json_decode($field, true);
if (json_last_error() === JSON_ERROR_NONE) {
return $decoded;
}
}
return [];
}
private function format_error_response(WP_Error $error) {
$error_body = [
'success' => false,
'error' => [
'code' => $error->get_error_code(),
'message' => $error->get_error_message(),
'details' => $error->get_error_data()
]
];
$status_code = $error->get_error_data()['status'] ?? 500;
$rest_response = new WP_REST_Response($error_body, $status_code);
$rest_response->set_headers(['Content-Type' => 'application/json']);
return $rest_response;
}
private function format_response($response) {
if (is_wp_error($response)) {
return $this->format_error_response($response);
}
// Ensure all responses go through this formatter
return new WP_REST_Response([
'success' => true,
'data' => $response
], 200);
}
private function process_request($request) {
if(get_transient('webhook_test_mode')) {
return [
'test_mode' => true,
'captured_data' => [
'action' => $request['action'],
'params' => $request->get_params(),
'files' => $request->get_file_params(),
'headers' => $request->get_headers()
]
];
}
$action = $request['action'];
switch ( $request['action'] ) {
case 'upload': return $this->handle_upload($request);
case 'create-post': return $this->create_post($request);
case 'get-post': return $this->get_post($request);
default: return new WP_Error('invalid_action', 'Invalid action specified', ['status' => 400]);
}
}
private function handle_upload($request) {
$files = $request->get_file_params();
$params = $request->get_params();
if(empty($files['file']) && empty($params['file_url'])) {
return new WP_Error('no_file', 'No file uploaded or URL provided', ['status' => 400]);
}
if (!empty($params['file_url'])) {
return $this->handle_upload_from_url($params['file_url']);
}
$allowed_types = ['image/jpeg', 'image/png', 'application/pdf'];
if (!in_array($files['file']['type'], $allowed_types)) {
return new WP_Error('invalid_type', 'Unsupported file type', ['status' => 400]);
}
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$upload = wp_handle_upload($files['file'], ['test_form' => false]);
if (isset($upload['error'])) {
error_log('Upload Error: ' . $upload['error']);
error_log('File Path: ' . $files['file']['tmp_name']);
return new WP_Error('upload_error', [
'error' => $upload['error'],
'file_path' => $files['file']['tmp_name'],
'file_type' => $files['file']['type'],
'file_size' => $files['file']['size'],
], ['status' => 500]);
}
$attachment = [
'post_title' => basename($upload['file']),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $upload['url'],
'post_mime_type' => $files['file']['type']
];
$attachment_id = wp_insert_attachment($attachment, $upload['file']);
$metadata = wp_generate_attachment_metadata($attachment_id, $upload['file']);
wp_update_attachment_metadata($attachment_id, $metadata);
if (is_wp_error($attachment_id)) {
@unlink($upload['file']);
return $attachment_id;
}
return [
'mediaID' => $attachment_id,
'mediaUrl' => wp_get_attachment_url($attachment_id),
'editUrl' => admin_url("post.php?post=$attachment_id&action=edit")
];
}
private function create_post($request) {
$required = ['title', 'content', 'author'];
foreach ($required as $field) {
if (empty($request[$field])) {
return new WP_Error('missing_field', "Missing required field: $field", ['status' => 400]);
}
}
$post_data = [
'post_title' => sanitize_text_field($request['title']),
'post_content' => wp_kses_post($request['content']),
'post_status' => $request['status'] ?? 'draft',
'post_author' => intval($request['author']),
'post_type' => 'post'
];
$post_id = wp_insert_post($post_data, true);
if (is_wp_error($post_id)) {
return new WP_Error('post_creation_failed', $post_id->get_error_message(), ['status' => 500]);
}
// Handle categories
$categories = $this->decode_json_field($request['categories']);
if (!empty($categories)) {
$category_ids = [];
foreach ($categories as $category_data) {
if (is_numeric($category_data)) {
$category_ids[] = intval($category_data);
} else {
// Unescape category name
$category_data = $this->unescape_string($category_data);
$category = get_term_by('name', $category_data, 'category');
if ($category) {
$category_ids[] = intval($category->term_id);
} else {
$new_category = wp_insert_term($category_data, 'category');
if (!is_wp_error($new_category)) {
$category_ids[] = intval($new_category['term_id']);
}
}
}
}
wp_set_post_categories($post_id, $category_ids);
}
// Handle tags
$tags = $this->decode_json_field($request['tags']);
if (!empty($tags)) {
$tag_ids = [];
foreach ($tags as $tag_data) {
if (is_numeric($tag_data)) {
$tag_ids[] = intval($tag_data);
} else {
$tag = get_term_by('name', $tag_data, 'post_tag');
if ($tag) {
$tag_ids[] = intval($tag->term_id);
} else {
$new_tag = wp_insert_term($tag_data, 'post_tag');
if (!is_wp_error($new_tag)) {
$tag_ids[] = intval($new_tag['term_id']);
}
}
}
}
wp_set_post_tags($post_id, $tag_ids);
}
// Handle featured image from URL
if (!empty($request['featured_image'])) {
$attachment_id = $this->handle_upload_from_url($request['featured_image']);
if (!is_wp_error($attachment_id)) {
set_post_thumbnail($post_id, $attachment_id);
}
}
// Handle featured media by ID
if (!empty($request['featuredMediaId'])) {
$media_id = intval($request['featuredMediaId']);
if (get_post_type($media_id) === 'attachment') {
set_post_thumbnail($post_id, $media_id);
} else {
return new WP_Error('invalid_media', 'Invalid media ID provided', ['status' => 400]);
}
}
return [
'postID' => $post_id,
'postUrl' => get_permalink($post_id),
'postEditUrl' => admin_url("post.php?post=$post_id&action=edit"),
'published' => ('publish' === ($post_data['post_status'] ?? 'draft'))
];
}
private function handle_upload_from_url($url) {
$upload = wp_upload_bits(basename($url), null, file_get_contents($url));
if (!$upload['error']) {
$wp_filetype = wp_check_filetype($upload['file'], null);
$attachment = [
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($url)),
'post_content' => '',
'post_status' => 'inherit'
];
$attach_id = wp_insert_attachment($attachment, $upload['file']);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $upload['file']);
wp_update_attachment_metadata($attach_id, $attach_data);
return [
'success' => true,
'mediaId' => $attach_id,
'public_url' => wp_get_attachment_url($attach_id),
'edit_url' => admin_url("upload.php?item=$attach_id")
];
} else {
return new WP_Error('upload_error', $upload['error'], ['status' => 500]);
}
}
private function sanitize_post_status($status) {
$allowed = ['draft', 'publish', 'pending', 'private'];
return in_array($status, $allowed) ? $status : 'draft';
}
private function validate_author($user_id) {
$user = get_userdata(absint($user_id));
return $user ? $user->ID : 1;
}
public function verify_request($request) {
$auth_header = $request->get_header('X-Auth-Key');
if(empty($auth_header)) {
return new WP_Error('missing_auth', 'Authentication required', ['status' => 401]);
}
if (!hash_equals($this->get_auth_key(), $auth_header)) {
return new WP_Error('invalid_auth', 'Invalid authentication key', ['status' => 403]);
}
return true;
}
private function is_rate_limited() {
$transient_name = 'webhook_limit_' . $_SERVER['REMOTE_ADDR'];
$attempts = get_transient($transient_name) ?: 0;
if($attempts >= 5) { // Permit exatamente 5 tentativas
return true;
}
set_transient($transient_name, $attempts + 1, MINUTE_IN_SECONDS);
return false;
}
public function ajax_get_logs() {
check_ajax_referer('webhook_logs', 'security');
global $wpdb;
$table_name = $wpdb->prefix . 'webhook_logs';
// Temporary debug
error_log('[Webhook] Log table exists: '.$wpdb->get_var("SHOW TABLES LIKE '$table_name'"));
error_log('[Webhook] Last SQL error: '.$wpdb->last_error);
$logs = $wpdb->get_results("SELECT * FROM $table_name ORDER BY time DESC LIMIT 20");
error_log('[Webhook] Logs found: '.print_r($logs, true));
wp_send_json_success([
'html' => $this->render_logs_html($logs),
'page' => 1
]);
}
private function render_logs_html($logs) {
$html = '';
foreach ($logs as $log) {
$html .= $this->render_log_card($log);
}
return $html;
}
private function render_log_card($log) {
$params = json_decode($log->params, true) ?: [];
$headers = json_decode($log->headers, true) ?: [];
$status_class = 'status-' . substr($log->status_code, 0, 1);
$direction_arrow = isset($log->direction) && $log->direction === 'outgoing' ? '↑' : '↓';
$html = '<div class="log-card ' . $status_class . '">'
. '<div class="log-summary">'
. '<div class="log-info">'
. '<span class="log-direction">' . $direction_arrow . '</span>'
. '<span class="log-time">' . mysql2date('M j, Y H:i:s', $log->time) . '</span>'
. '<span class="log-status">HTTP ' . $log->status_code . '</span>'
. '<span class="log-method">' . $log->method . '</span>'
. '<span class="log-endpoint"><a href="' . $log->endpoint . '" target="_blank">' . $log->endpoint . '</a></span>'
. '</div>'
. '<button class="log-toggle button button-small">Show Details</button>'
. '</div>'
. '<div class="log-details" style="display:none;">'
. '<div class="collapsible-panel">'
. '<h3 class="collapsible-title">'
. '<span class="toggle-btn">[+]</span>'
. '<span>Headers</span>'
. '</h3>'
. '<div class="collapsible-content" style="display:none;">'
. '<pre>' . wp_kses_post(json_encode($headers, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) . '</pre>'
. '</div>'
. '</div>'
. '<div class="collapsible-panel">'
. '<h3 class="collapsible-title">'
. '<span class="toggle-btn">[+]</span>'
. '<span>Parameters</span>'
. '</h3>'
. '<div class="collapsible-content" style="display:none;">'
. '<pre>' . wp_kses_post(json_encode($params, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) . '</pre>'
. '</div>'
. '</div>'
. '<div class="collapsible-panel">'
. '<h3 class="collapsible-title">'
. '<span class="toggle-btn">[+]</span>'
. '<span>Response</span>'
. '</h3>'
. '<div class="collapsible-content" style="display:none;">'
. '<pre>' . $this->syntax_highlight($log->response) . '</pre>'
. '</div>'
. '</div>'
. '</div>'
. '</div>';
return $html;
}
private function syntax_highlight($json) {
// Decode the JSON string
$json = json_decode($json, true);
// Encode the HTML code inside the JSON string
if (is_array($json)) {
array_walk_recursive($json, function (&$item, &$key) {
if (is_string($item)) {
// Decode HTML entities
$item = html_entity_decode($item, ENT_QUOTES, 'UTF-8');
// Encode HTML special characters
$item = htmlspecialchars($item, ENT_QUOTES, 'UTF-8');
}
});
}
// Encode the JSON string
$json = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
// Make URLs clickable
$json = preg_replace('!(https?://[^\s\"]+)!i', '<a href=\"$1\" target=\"_blank\">$1</a>', $json);
// Apply syntax highlighting to JSON data
$json = preg_replace('/(\"(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\\"])*\"(\\s*:)?|\\b(true|false|null)\\b|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)/', '<span style=\"color: #007bff;\">$1</span>', $json);