-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai-seo-wp.php
2221 lines (1919 loc) · 61.8 KB
/
ai-seo-wp.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* WPSEO.AI - https://github.com/AlexanderGW/wpseoai
*
* @package WPSEOAI
* @author WPSEO.AI Ltd
*
* @wordpress-plugin
* Plugin Name: WPSEO.AI
* Plugin URI: https://wpseo.ai/
* Description: Pay-as-you-go artificial intelligence (AI); Search engine optimisations (SEO), proofreading, content translation, auditing, and more in development. Our service is currently in beta.
* Version: 0.0.7
* Author: WPSEO.AI Ltd
* Text Domain: ai-seo-wp
* Requires at least: 5.2
* Requires PHP: 7.1
* Domain Path: /language
* License: MIT
*/
/**
* Full source code for this plugin can be found at https://github.com/AlexanderGW/wpseoai
*/
/**
* NOTICE
* ---------------------------------------
* If you're having problems with this plugin, after configuring your Subscription ID,
* and Secret, please contact us, using one of the forms on our website. https://wpseo.ai/subscription-status.html
*
* Alternatively, please check our FAQ at: https://wpseo.ai/faq.html
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Require `WPSEOAI_List_Table` class, for displaying submissions on the WPSEO.AI dashboard
if ( ! class_exists( 'WPSEOAI_List_Table' ) ) {
require_once( __DIR__ . '/includes/class-wpseoai-wp-list-table.php' );
}
if ( ! class_exists( 'WPSEOAI' ) ) {
/**
* The `WPSEOAI` class, for plugin functionality and integration
*/
class WPSEOAI {
/**
* Constants for identifiers used within the WordPress ecosystem
*/
public const POST_TYPE_RESPONSE = 'wpseoai_response';
public const META_KEY_SUMMARY = '_wpseoai_summary';
public const META_KEY_SIGNATURE = '_wpseoai_signature';
public const META_KEY_STATE = '_wpseoai_state';
public const META_KEY_JSON = '_wpseoai_json';
/**
* Regular expression patterns, within the WPSEO.AI ecosystem
*/
public const PATTERN_SIGNATURE_ID = '/^[a-z0-9]{64}$/';
public const PATTERN_SUBSCRIPTION_ID = '/^[A-Z0-9]{20}$/';
public const PATTERN_SECRET = '/^[a-z0-9]{32}$/';
/**
* Holds instance of `WPSEOAI` class, fetched with `self::get_instance()`
*
* @var self
*/
private static $instance;
/**
* Holds instance of `WPSEOAI_List_Table` class
*
* @var WPSEOAI_List_Table
*/
public $responses_obj;
/**
* Prevent cloning
*
* @return void
*/
private function __clone() {
// Empty
}
/**
* Establish all actions and filters for the plugin
*/
private function __construct() {
// Setup WPSEO.AI post type
add_action( 'init', [ $this, 'register_custom_post_type' ] );
// Setup REST API endpoints
add_action( 'rest_api_init', [ $this, 'register_ingest_endpoint' ] );
add_action( 'admin_menu', [ $this, 'add_settings_page' ] );
add_action( 'admin_init', [ $this, 'register_settings' ] );
add_action( 'admin_head', [ $this, 'theme_admin_css' ] );
add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_block_editor_assets' ] );
add_action( 'plugins_loaded', function () {
WPSEOAI::get_instance();
} );
/**
* Filters
*/
add_filter( 'set-screen-option', [
__CLASS__,
'set_screen'
], 10, 3 );
add_filter( 'post_row_actions', [
__CLASS__,
'post_row_actions'
], 0, 2 );
add_filter( 'page_row_actions', [
__CLASS__,
'page_row_actions'
], 0, 2 );
}
/**
* Singleton instance
*
* @return WPSEOAI
*/
public static function get_instance(): WPSEOAI {
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* @param $status
* @param $option
* @param $value
*
* @return mixed
*/
public static function set_screen(
$status,
$option,
$value
) {
return $value;
}
/**
* post_row_actions filter
*
* @param array $actions
* @param object $post
*
* @return array
*/
public static function post_row_actions(
array $actions,
$post
): array {
if ( current_user_can( 'edit_posts' ) ) {
$actions = array_merge( $actions, array(
'wpseoai_optimize_post' => sprintf( '<a href="%s">' . esc_html__( 'Finesse', 'ai-seo-wp' ) . '</a>', wp_nonce_url( sprintf( 'admin.php?page=wpseoai_dashboard&action=optimize&post_id=%d', $post->ID ), 'optimize' ) )
) );
}
return $actions;
}
/**
* page_row_actions filter
*
* @param array $actions
* @param object $post
*
* @return array
*/
public static function page_row_actions(
array $actions,
$post
): array {
if ( current_user_can( 'edit_pages' ) ) {
$actions = array_merge( $actions, array(
'wpseoai_optimize_post' => sprintf( '<a href="%s">' . esc_html__( 'Finesse', 'ai-seo-wp' ) . '</a>', wp_nonce_url( sprintf( 'admin.php?page=wpseoai_dashboard&action=optimize&post_id=%d', $post->ID ), 'optimize' ) )
) );
}
return $actions;
}
/**
* @return void
*/
private function _enqueue_style(): void {
wp_enqueue_style(
'wpseoai-css',
esc_url( plugins_url( 'wpseoai.css', 'ai-seo-wp/dist/wpseoai.css' ) )
);
}
/**
* @return void
*/
public function enqueue_block_editor_assets(): void {
self::_enqueue_style();
wp_enqueue_script(
'wpseoai-gutenberg',
esc_url( plugins_url( 'dist/wpseoai_gutenberg.js', __FILE__ ) ),
array( 'wp-plugins', 'wp-edit-post' ),
filemtime( plugin_dir_path( __FILE__ ) . 'dist/wpseoai_gutenberg.js' ),
true
);
}
/**
* @param string $name
* @param $data
*
* @return bool|null
*/
private static function log(
string $name,
$data
): ?bool {
if ( get_option( 'wpseoai_log', get_option( 'wpseoai_debug', 'false' ) ) === 'false' ) {
return null;
}
$log_directory = getcwd() . '/log/' . gmdate( 'Y-m-d' );
if ( ! is_dir( $log_directory ) && ! mkdir( $log_directory ) ) {
return false;
}
$timestamp = time();
$data = wp_json_encode( $data, JSON_PRETTY_PRINT );
if ( ! file_put_contents(
"{$log_directory}/wpseoai-{$name}.json",
"{$timestamp}: {$data}\n",
FILE_APPEND
) ) {
return false;
}
return true;
}
/**
* Create custom post for responses, for auditing purposes
*
* @return void
*/
public function register_custom_post_type(): void {
register_post_type( self::POST_TYPE_RESPONSE, [
'label' => esc_html__( 'WPSEO.AI', 'ai-seo-wp' ),
'public' => true,
'exclude_from_search' => true,
'publicly_queryable' => false,
'show_ui' => false,
'show_in_nav_menus' => false,
'supports' => array( 'title' ),
'menu_icon' => 'dashicons-share-alt',
] );
}
/**
* @return void
*/
public function register_ingest_endpoint(): void {
register_rest_route( 'wpseoai/v1', '/ingest', [
'methods' => 'POST',
'callback' => [ $this, 'ingest_endpoint_callback' ],
'permission_callback' => [ $this, 'ingest_endpoint_permission_callback' ],
] );
register_rest_route( 'wpseoai/v1', '/optimize', [
'methods' => 'GET',
'callback' => [ $this, 'optimize_endpoint_callback' ],
'permission_callback' => [ $this, 'optimize_endpoint_permission_callback' ],
] );
register_rest_route( 'wpseoai/v1', '/retrieve', [
'methods' => 'GET',
'callback' => [ $this, 'retrieve_endpoint_callback' ],
'permission_callback' => [ $this, 'retrieve_endpoint_permission_callback' ],
] );
register_rest_route( 'wpseoai/v1', '/context', [
'methods' => 'GET',
'callback' => [ $this, 'context_endpoint_callback' ],
'permission_callback' => [ $this, 'context_endpoint_permission_callback' ],
] );
register_rest_route( 'wpseoai/v1', '/audit', [
'methods' => 'GET',
'callback' => [ $this, 'audit_endpoint_callback' ],
'permission_callback' => [ $this, 'audit_endpoint_permission_callback' ],
] );
}
/**
* @param WP_REST_Request $request
*
* @return WP_REST_Response
*/
public function ingest_endpoint_callback(
WP_REST_Request $request
): WP_REST_Response {
$subscription_id = esc_attr( self::_get_subscription_id() );
$secret = esc_attr( self::_get_subscription_secret() );
// Check we are configured with a subscription
if ( empty( $subscription_id ) || empty( $secret ) ) {
return new WP_REST_Response( [
'message' => 'Missing configuration',
'code' => 1
], 401 );
}
$request_subscription_id = $request->get_header( 'x_subscription_id' );
$request_signature = $request->get_header( 'x_signature' );
$request_timestamp = $request->get_header( 'x_timestamp' );
// Check that we have required headers
if ( ! $request_subscription_id || ! $request_signature || ! $request_timestamp ) {
return new WP_REST_Response( [
'message' => 'Missing authentication headers',
'code' => 2
], 401 );
}
// Check the provided subscription ID is matched
if ( $request_subscription_id !== $subscription_id ) {
return new WP_REST_Response( [
'message' => 'Invalid subscription ID',
'code' => 3
], 401 );
}
// Create HMAC, and verify signature
$method = $request->get_method();
$endpoint = '/wp-json';
$endpoint .= $request->get_route();
$payload = $request->get_body();
$content = $method . ' ' . $endpoint . $payload . $request_timestamp;
$hmac = hash_hmac( "sha256", $content, $secret );
if ( $hmac !== $request_signature ) {
return new WP_REST_Response( [
'message' => 'Invalid signature',
'code' => 4
], 401 );
}
// Check the received data structure
$json = $request->get_json_params();
if ( ! $json || ! array_key_exists( 'data', $json ) ) {
return new WP_REST_Response( [
'message' => 'No data provided',
'code' => 5
], 400 );
}
// Check payload version
if ( ! array_key_exists( 'version', $json ) || $json[ 'version' ] !== '1' ) {
return new WP_REST_Response( [
'message' => 'Invalid payload version',
'code' => 6
], 400 );
}
// Decode the received Base64 data
$data_string = base64_decode( $json[ 'data' ] );
if ( ! $data_string ) {
return new WP_REST_Response( [
'message' => 'Invalid data provided',
'code' => 7
], 400 );
}
// Parse the data string
$data = json_decode( $data_string, true );
if ( ! $data ) {
return new WP_REST_Response( [
'message' => 'Invalid data provided',
'code' => 8
], 400 );
}
self::log( "ingest-{$request_signature}", $data );
[ $post_id, $revision_id ] = self::_save_response( $data );
if ( ! $post_id ) {
return new WP_REST_Response( [
'message' => 'Failed to store response data',
'code' => 9
], 400 );
}
// Add post ID for audit record
$data[ 'post' ][ 'ID' ] = $post_id;
$data[ 'post' ][ 'revision_id' ] = $revision_id;
// TODO: Handling of failed audit record creation
$audit_post_id = self::_save_audit( $data );
if ( ! $audit_post_id ) {
self::log( "audit-${$post_id}", $audit_post_id );
}
return new WP_REST_Response( [
'code' => 0,
'auditId' => $audit_post_id,
'postId' => $post_id
], 200 );
}
/**
* See `WPSEOAI::ingest_endpoint_callback()`
*
* @param WP_REST_Request $request
*
* @return bool
*/
public function ingest_endpoint_permission_callback(
WP_REST_Request $request
): bool {
return true;
}
/**
* @param WP_REST_Request $request
*
* @return WP_REST_Response
*/
public function retrieve_endpoint_callback(
WP_REST_Request $request
): WP_REST_Response {
try {
$params = $request->get_query_params();
if ( ! array_key_exists( 'post', $params ) ) {
throw new \Exception( 'Invalid payload', 1 );
}
if ( ! current_user_can( 'edit_posts' ) ) {
throw new \Exception( 'Your user account is not allowed', 2 );
}
$post_id = intval( $params[ 'post' ] );
$post = get_post( $post_id );
if ( ! $post instanceof WP_Post ) {
throw new \Exception( 'Invalid post', 3 );
}
$signature = get_post_meta( $post_id, self::META_KEY_SIGNATURE, true );
if ( empty( $signature ) ) {
throw new \Exception( 'Invalid post type', 4 );
}
$result = self::retrieve( $signature );
if ( ! is_array( $result ) ) {
throw new \Exception( 'WPSEO.AI retrieval request failed to response, please try later.', 5 );
}
return new WP_REST_Response( [
'message' => $result[ 'code' ] === 204 ? 'Content not yet processed, please try later' : 'Success',
'code' => $result[ 'code' ],
'auditId' => $result[ 'audit_post_id' ] ?? 0
], 200 );
}
catch( \Exception $e ) {
return new WP_REST_Response( [
'message' => $e->getMessage(),
'code' => $e->getCode()
], 400 );
}
}
/**
* @param WP_REST_Request $request
*
* @return bool
*/
public function retrieve_endpoint_permission_callback(
WP_REST_Request $request
): bool {
return true;
}
/**
* @param WP_REST_Request $request
*
* @return WP_REST_Response
*/
public function optimize_endpoint_callback(
WP_REST_Request $request
): WP_REST_Response {
try {
$params = $request->get_query_params();
if ( ! array_key_exists( 'post', $params ) ) {
throw new \Exception( 'Invalid payload', 1 );
}
if ( ! current_user_can( 'edit_posts' ) ) {
throw new \Exception( 'Your user account is not allowed', 2 );
}
$post_id = intval( $params[ 'post' ] );
$post = get_post( $post_id );
if ( ! $post instanceof WP_Post ) {
throw new \Exception( 'Invalid post', 3 );
}
// WPML: Establish locale target
$target_locale = sanitize_text_field( wp_unslash( $params[ 'locale' ] ) );
if ( $target_locale && function_exists( 'wpml_get_setting' ) ) {
global $sitepress; // Implemented by WPML plugin, variable tested for `SitePress` instance below.
if ( class_exists( 'SitePress' ) && $sitepress instanceof SitePress ) {
$active_languages = $sitepress->get_active_languages();
if ( ! array_key_exists( $target_locale, $active_languages ) ) {
throw new \Exception( 'Invalid locale', 4 );
}
}
}
$result = self::submit_post( $post_id, $target_locale );
if ( ! is_array( $result ) ) {
if ( $result instanceof WP_Error ) {
throw new \Exception( $result->get_error_message(), 5 );
}
throw new \Exception( 'Invalid submission response, please try later.', 5 );
}
if ( $result[ 'code' ] <> 200 ) {
throw new \Exception( $result[ 'message' ], $result[ 'code' ] );
}
return new WP_REST_Response( [
'message' => 'Success',
'code' => $result[ 'code' ],
'auditId' => $result[ 'audit_post_id' ] ?? 0
], 200 );
}
catch( \Exception $e ) {
return new WP_REST_Response( [
'message' => $e->getMessage(),
'code' => $e->getCode()
], 400 );
}
}
/**
* @param WP_REST_Request $request
*
* @return bool
*/
public function optimize_endpoint_permission_callback(
WP_REST_Request $request
): bool {
return true;
}
/**
* @param WP_REST_Request $request
*
* @return WP_REST_Response
*/
public function context_endpoint_callback(
WP_REST_Request $request
): WP_REST_Response {
try {
$params = $request->get_query_params();
if ( ! array_key_exists( 'post', $params ) ) {
throw new \Exception( 'Invalid payload', 1 );
}
if ( ! current_user_can( 'edit_posts' ) ) {
throw new \Exception( 'Your user account is not allowed', 2 );
}
$post_id = absint( $params[ 'post' ] );
$post = get_post( $post_id );
if ( ! $post instanceof WP_Post ) {
throw new \Exception( 'Invalid post', 3 );
}
// Get submission summary
$summary = get_post_meta( $post_id, self::META_KEY_SUMMARY, true );
// WPML: Establish locales
$default_locale = get_locale();
$locales = null;
if ( function_exists( 'wpml_get_setting' ) ) {
global $sitepress; // Implemented by WPML plugin, variable tested for `SitePress` instance below.
if ( class_exists( 'SitePress' ) && $sitepress instanceof SitePress ) {
$language_details = $sitepress->get_element_language_details(
$post_id,
"post_{$post->post_type}"
);
$default_locale = $language_details->language_code;
$locales = $sitepress->get_active_languages();
}
}
return new WP_REST_Response( [
'defaultLocale' => $default_locale,
'locales' => $locales,
'summary' => $summary
], 200 );
}
catch( \Exception $e ) {
return new WP_REST_Response( [
'message' => $e->getMessage(),
'code' => $e->getCode()
], 400 );
}
}
/**
* @param WP_REST_Request $request
*
* @return bool
*/
public function context_endpoint_permission_callback(
WP_REST_Request $request
): bool {
return true;
}
/**
* @param WP_REST_Request $request
*
* @return WP_REST_Response
*/
public function audit_endpoint_callback(
WP_REST_Request $request
): WP_REST_Response {
try {
$params = $request->get_query_params();
if ( ! array_key_exists( 'post', $params ) ) {
throw new \Exception( 'Invalid payload', 1 );
}
if ( ! current_user_can( 'edit_posts' ) ) {
throw new \Exception( 'Your user account is not allowed', 2 );
}
$post_id = absint( $params[ 'post' ] );
$post = get_post( $post_id );
if ( ! $post instanceof WP_Post ) {
throw new \Exception( 'Invalid post', 3 );
}
$state = get_post_meta( $post_id, self::META_KEY_STATE, true );
return new WP_REST_Response( [
'state' => $state
], 200 );
}
catch( \Exception $e ) {
return new WP_REST_Response( [
'message' => $e->getMessage(),
'code' => $e->getCode()
], 400 );
}
}
/**
* @param WP_REST_Request $request
*
* @return bool
*/
public function audit_endpoint_permission_callback(
WP_REST_Request $request
): bool {
return true;
}
/**
* @return string|void
*/
public function theme_admin_css(): void {
$page = (string) filter_input( INPUT_GET, 'page', FILTER_SANITIZE_STRING );
$action = (string) filter_input( INPUT_GET, 'action', FILTER_SANITIZE_STRING );
if (
( $page !== 'wpseoai_dashboard' )
|| ! in_array( $action, [
'audit',
'optimize',
'retrieve',
'edit'
] )
) {
return;
}
self::_enqueue_style();
wp_enqueue_script(
'wpseoai-main',
esc_url( plugins_url( 'main.js', 'ai-seo-wp/dist/main.js' ) )
);
}
/**
* Screen options
*
* @return void
*/
public function screen_option() {
// TODO: Can we refactor this?
if ( ! isset( $_GET[ 'orderby' ] ) ) {
$_GET[ 'orderby' ] = 'post_date';
}
if ( ! isset( $_GET[ 'order' ] ) ) {
$_GET[ 'order' ] = 'desc';
}
$option = 'per_page';
$args = [
'label' => esc_html__( 'Number of items per page:', 'ai-seo-wp' ),
'default' => 20,
'option' => 'submissions_per_page'
];
add_screen_option( $option, $args );
$this->responses_obj = new WPSEOAI_List_Table();
}
/**
* @return void
*/
public function add_settings_page() {
add_menu_page(
'WPSEO.AI Responses',
'WPSEO.AI',
'manage_options',
'wpseoai_dashboard',
[ $this, 'manage_responses_callback' ],
'dashicons-share-alt',
null
);
$hook = add_submenu_page(
'wpseoai_dashboard',
esc_html__( 'WPSEO.AI', 'ai-seo-wp' ),
esc_html__( 'Dashboard', 'ai-seo-wp' ),
'manage_options',
'wpseoai_dashboard',
[ $this, 'manage_responses_callback' ]
);
add_action( "load-$hook", [ $this, 'screen_option' ] );
add_submenu_page(
'wpseoai_dashboard',
esc_html__( 'WPSEO.AI', 'ai-seo-wp' ),
esc_html__( 'Settings', 'ai-seo-wp' ),
'manage_options',
'wpseoai_settings',
[ $this, 'settings_page' ]
);
}
/**
* @param array $array
*
* @return string
*/
private static function _key_value_array_to_html(
array $array
): string {
$html = '';
foreach ( $array as $key => $value ) {
$html .= "<hr />";
$html .= "<h4>" . esc_html( $key ) . "</h4>";
$html .= '<p>';
if ( is_bool( $value ) ) {
$html .= esc_html( $value ? 'TRUE' : 'FALSE' );
} elseif ( is_array( $value ) ) {
foreach ( $value as $i => $field ) {
foreach ( $field as $j => $k ) {
$html .= "<hr />";
$html .= "<h4>[" . esc_html( $i ) . "]: " . esc_html( $j ) . "</h4>";
$html .= '<p>';
if ( is_string( $k ) || is_int( $value ) ) {
$html .= esc_html( $k );
} elseif ( is_bool( $k ) ) {
$html .= esc_html( $k ? 'TRUE' : 'FALSE' );
}
$html .= '</p>';
}
}
} else {
$html .= esc_html( $value );
}
$html .= '</p>';
}
return $html;
}
/**
* @return void
*/
public function manage_responses_callback() {
if ( array_key_exists( 'action', $_GET ) ) {
if ( ! array_key_exists( 'post_id', $_GET ) ) {
return;
}
$post_id = absint( $_GET[ 'post_id' ] );
$_wpnonce = sanitize_text_field( wp_unslash( filter_input( INPUT_GET, '_wpnonce', FILTER_SANITIZE_STRING ) ) );
$action = sanitize_text_field( wp_unslash( filter_input( INPUT_GET, 'action', FILTER_SANITIZE_STRING ) ) );
switch ( $action ) {
/**
* Action an optimization request to WPSEO.AI
*/
case 'optimize':
{
if ( ! isset( $_wpnonce ) || ! wp_verify_nonce( $_wpnonce, 'optimize' ) ) {
wp_die(
new WP_Error(
'nonce_failure',
esc_html__(
'Failed to verify nonce, please navigate back to the dashboard',
'ai-seo-wp'
)
)
);
}
$post = get_post( $post_id );
if ( ! $post instanceof WP_Post ) {
wp_die( esc_html__( 'Post not found.', 'ai-seo-wp' ) );
}
// WPML: Establish target locale
$locale = get_locale();
if ( function_exists( 'wpml_get_setting' ) ) {
global $sitepress; // Implemented by WPML plugin, variable tested for `SitePress` instance below.
if ( class_exists( 'SitePress' ) && $sitepress instanceof SitePress ) {
$active_languages = $sitepress->get_active_languages();
$locale = sanitize_text_field( wp_unslash( filter_input( INPUT_GET, 'locale', FILTER_SANITIZE_STRING ) ) );
if ( ! $locale ) {
$language_details = $sitepress->get_element_language_details(
$post_id,
"post_{$post->post_type}"
);
$locale = $language_details->language_code;
}
if ( ! array_key_exists( $locale, $active_languages ) ) {
return;
}
}
}
$nonce_retrieve = wp_create_nonce( 'wp_rest' );
$nonce_audit = wp_create_nonce( 'audit' );
?>
<div class="wrap"
id="wpseoai-request" data-type="optimize"
data-locale="<?php echo esc_attr( $locale ) ?>"
data-post="<?php echo esc_attr( $post_id ) ?>"
data-nonce-request="<?php echo esc_attr( $nonce_retrieve ) ?>"
data-nonce-audit="<?php echo esc_attr( $nonce_audit ) ?>"
>
<h2>Finesse content</h2>
</div>
<?php
break;
}
/**
* Retrieve an optimisation request, previously sent to WPSEO.AI
*/
case 'retrieve':
{
if ( ! isset( $_wpnonce ) || ! wp_verify_nonce( $_wpnonce, 'retrieve' ) ) {
wp_die(
new WP_Error(
'nonce_failure',
esc_html__(
'Failed to verify nonce, please navigate back to the dashboard',
'ai-seo-wp'
)
)
);
}
$nonce_retrieve = wp_create_nonce( 'wp_rest' );
$nonce_audit = wp_create_nonce( 'audit' );
?>
<div class="wrap"
id="wpseoai-request" data-type="retrieve"
data-post="<?php echo esc_attr( $post_id ) ?>"
data-nonce-request="<?php echo esc_attr( $nonce_retrieve ) ?>"
data-nonce-audit="<?php echo esc_attr( $nonce_audit ) ?>"
>
<h2>WPSEO.AI Retrieval</h2>
</div>
<?php
break;
}
/**
* View current audit state of an optimisation request, previously sent to WPSEO.AI
*/
case 'audit':
{
if ( ! isset( $_wpnonce ) || ! wp_verify_nonce( $_wpnonce, 'audit' ) ) {
wp_die(
new WP_Error(
'nonce_failure',
esc_html__(
'Failed to verify nonce, please navigate back to the dashboard',
'ai-seo-wp'
)
)
);
}
$post = get_post( $post_id );
if ( ! $post ) {
wp_die( esc_html__( 'Post not found.', 'ai-seo-wp' ) );
}
$date_before = get_the_date( 'jS F, h:i:s a', $post );
$state = get_post_meta( $post_id, self::META_KEY_JSON, true );
// Exit if we have invalid state information
if (
! is_array( $state )
|| ! array_key_exists( 'sent', $state )
|| ! array_key_exists( 'post', $state[ 'sent' ] )
) {
wp_die( esc_html__( 'Invalid state information for this WPSEO.AI submission.', 'ai-seo-wp' ) );
}
$response = addslashes( wp_json_encode( $state ) );
// Used with `wp_kses()` calls to `self::_key_value_array_to_html()`
$allowed_html = [
'hr' => [],
'h4' => [],
'p' => [],
]
?>
<div class="wrap">
<h1><?php esc_html_e( 'WPSEO.AI Submission', 'ai-seo-wp' ) ?></h1>
<h2><?php echo esc_html( $state[ 'sent' ][ 'post' ][ 'post_title' ] ) ?></h2>
<div class="card">
<h2 class="title">
<label for="submission-toggle">
<?php esc_html_e( 'Submission', 'ai-seo-wp' ) ?>
</label>
</h2>
<button
class="toggle"
id="submission-toggle"
aria-label="<?php esc_attr_e( 'Show card contents', 'ai-seo-wp' ) ?>"
aria-pressed="true"
>
</button>
<div class="show">
<h4><?php esc_html_e( 'Date', 'ai-seo-wp' ) ?></h4>
<p><?php echo esc_html( $date_before ) ?></p>
<h4><?php esc_html_e( 'Signature', 'ai-seo-wp' ) ?></h4>
<p><?php echo esc_html( $state[ 'sent' ][ 'signature' ] ) ?></p>