-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathclass-subjects-controller.php
More file actions
459 lines (390 loc) · 13.7 KB
/
class-subjects-controller.php
File metadata and controls
459 lines (390 loc) · 13.7 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
<?php
namespace DotOrg\TryWordPress;
use DateTime;
use DateTimeZone;
use WP_Error;
use WP_REST_Controller;
use WP_REST_Response;
use WP_REST_Server;
class Subjects_Controller extends WP_REST_Controller {
private string $storage_post_type;
private array $subject_types;
protected $schema;
public function __construct( $storage_post_type ) {
$this->storage_post_type = $storage_post_type;
$this->init_schema();
$this->subject_types = array_keys( $this->schema );
add_action( 'rest_api_init', array( $this, 'register_routes' ) );
$this->attach_filters();
}
public function init_schema(): void {
$this->schema = array();
$new_schema = Schema::get();
foreach ( $new_schema as $subject_type => $definition ) {
$this->schema[ $subject_type ] = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => $definition['title'],
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Unique identifier for liberated page', 'try_wordpress' ),
'type' => 'integer',
'readonly' => true,
),
'authorId' => array(
'description' => __( 'Author ID of the page', 'try_wordpress' ),
'type' => 'integer',
'required' => false,
),
'sourceUrl' => array(
'description' => __( 'Source URL from where the page was liberated', 'try_wordpress' ),
'type' => 'string',
'required' => true,
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
),
'sourceHtml' => array(
'description' => __( 'Source HTML from where the page was liberated', 'try_wordpress' ),
'type' => 'string',
'required' => false,
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
),
'transformedId' => array(
'description' => __( 'Post ID of transformed result of this liberated page', 'try_wordpress' ),
'type' => 'integer',
'required' => false,
'readonly' => true,
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
),
),
);
foreach ( $definition['fields'] as $field => $field_definition ) {
$this->schema[ $subject_type ]['properties'][ 'raw' . ucfirst( $field ) ] = array(
'description' => '[raw]' . $field_definition['description'] ?? '',
'type' => convert_schema_type_to_rest_api_type( $field_definition['type'] ),
'required' => false,
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
);
$this->schema[ $subject_type ]['properties'][ 'parsed' . ucfirst( $field ) ] = array(
'description' => '[parsed]' . $field_definition['description'] ?? '',
'type' => convert_schema_type_to_rest_api_type( $field_definition['type'] ),
'required' => false,
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
);
}
}
}
public function register_routes(): void {
$version = '1';
$namespace = 'try-wp/v' . $version;
foreach ( $this->subject_types as $subject_type ) {
register_rest_route(
$namespace,
'/subjects/' . $subject_type,
array(
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'create_item' ),
'permission_callback' => '__return_true',
'args' => $this->get_endpoint_args_for_subject_schema( $subject_type, WP_REST_Server::CREATABLE ),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'search_item' ),
'permission_callback' => '__return_true',
'args' => $this->get_endpoint_args_for_subject_schema( $subject_type, WP_REST_Server::READABLE ),
),
)
);
register_rest_route(
$namespace,
'/subjects/' . $subject_type . '/(?P<id>\d+)',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => '__return_true',
'args' => array(
'context' => array(
'default' => 'view',
),
),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => '__return_true',
'args' => $this->get_endpoint_args_for_subject_schema( $subject_type, WP_REST_Server::EDITABLE ),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => array( $this, 'delete_item' ),
'permission_callback' => '__return_true',
'args' => array(
'force' => array(
'default' => false,
),
),
),
)
);
register_rest_route(
$namespace,
'/subjects/' . $subject_type . '/schema',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => function () use ( $subject_type ) {
return $this->get_public_subject_schema( $subject_type );
},
'permission_callback' => '__return_true',
)
);
}
}
public function get_public_subject_schema( $subject_type ) {
$schema = $this->schema[ $subject_type ];
return $this->remove_arg_options_from_schema( $schema );
}
private function remove_arg_options_from_schema( &$schema ) {
foreach ( $schema['properties'] as &$property ) {
unset( $property['arg_options'] );
}
return $schema;
}
public function get_storage_post_type(): string {
return $this->storage_post_type;
}
public function valid_request_for_insert( $request ): bool|WP_Error {
$request_data = json_decode( $request->get_body(), true );
$guid = $request_data['sourceUrl']; // required arg, will always be present at this point
// Rule1: guid must be unique
$post_id = $this->get_post_id_by_guid( $guid );
if ( $post_id ) {
return new WP_Error(
'rest_source_url_not_unique',
__( 'Source URL specified already exists', 'try_wordpress' ),
array( 'status' => 409 )
);
}
return true;
}
public function valid_request_for_update( $request ): bool|WP_Error {
// Rule1: post id must be a valid id
$post_id = $request['id'];
$item = get_post( $post_id );
if ( is_null( $item ) ) {
return new WP_Error(
'rest_post_invalid_id',
__( 'Invalid post ID.', 'try_wordpress' ),
array( 'status' => 404 )
);
}
// Rule2: if sourceUrl is supplied, it must be the same as already saved
$request_data = json_decode( $request->get_body(), true );
if ( isset( $request_data['sourceUrl'] ) && $request_data['sourceUrl'] !== $item->guid ) {
return new WP_Error(
'rest_source_url_immutable',
__( 'Source URL is immutable', 'try_wordpress' ),
array( 'status' => 400 )
);
}
return true;
}
public function attach_filters(): void {
add_filter(
'wp_insert_post_empty_content',
function ( $maybe_empty, $postarr ) {
if ( $postarr['post_type'] === $this->storage_post_type ) {
return false;
}
return $maybe_empty;
},
10,
2
);
// Bust guid -> postId cache when a post is deleted
add_action(
'delete_post_' . $this->storage_post_type,
function ( $post_id, $post ) {
$cache_group = 'try_wp';
$cache_key = 'try_wp_cache_guid_' . md5( $post->guid );
wp_cache_delete( $cache_key, $cache_group );
},
10,
2
);
}
public function get_endpoint_args_for_subject_schema( $subject_type, $method ): array {
return rest_get_endpoint_args_for_schema( $this->schema[ $subject_type ], $method );
}
public function get_item( $request ): WP_REST_Response|WP_Error {
$post_id = $request['id'];
$item = get_post( $post_id, ARRAY_A );
if ( is_null( $item ) ) {
return new WP_Error(
'rest_post_invalid_id',
__( 'Invalid post ID.', 'try_wordpress' ),
array( 'status' => 404 )
);
}
return $this->prepare_item_for_response( $item, $request );
}
public function create_item( $request ): WP_REST_Response|WP_Error {
$valid_request_for_insert = $this->valid_request_for_insert( $request );
if ( is_wp_error( $valid_request_for_insert ) ) {
return $valid_request_for_insert;
}
$item = $this->prepare_item_for_database( $request );
$item_meta = $item['meta'];
unset( $item['meta'] );
$result = wp_insert_post( $item, true );
if ( is_wp_error( $result ) ) {
return $result;
}
$item['ID'] = $result;
foreach ( $item_meta as $key => $value ) {
update_post_meta( $item['ID'], $key, $value );
}
$subject_type = $this->get_subject_type( $request );
update_post_meta( $item['ID'], 'subject_type', $subject_type );
do_action( 'dl_data_saved', Subject::from_post( $item['ID'] ), 'create' );
return $this->prepare_item_for_response( $item, $request, $subject_type );
}
public function update_item( $request ): WP_REST_Response|WP_Error {
$valid_request_for_update = $this->valid_request_for_update( $request );
if ( is_wp_error( $valid_request_for_update ) ) {
return $valid_request_for_update;
}
$item = $this->prepare_item_for_database( $request );
$item_meta = $item['meta'];
unset( $item['meta'] );
$result = wp_insert_post( $item, true );
if ( is_wp_error( $result ) ) {
return $result;
}
foreach ( $item_meta as $key => $value ) {
update_post_meta( $item['ID'], $key, $value );
}
do_action( 'dl_data_saved', Subject::from_post( $item['ID'] ), 'update' );
return $this->prepare_item_for_response( $item, $request );
}
public function delete_item( $request ): WP_Error|WP_REST_Response {
$post_id = $request['id'];
$item = get_post( $post_id );
if ( is_null( $item ) ) {
return new WP_Error(
'rest_post_invalid_id',
__( 'Invalid post ID.', 'try_wordpress' ),
array( 'status' => 404 )
);
}
if ( wp_delete_post( $request['id'], true ) ) {
return new WP_REST_Response( true, 204 );
}
return new WP_Error( 'rest_could_not_delete', __( 'Could not delete', 'try_wordpress' ), array( 'status' => 500 ) );
}
public function search_item( $request ): WP_Error|WP_REST_Response {
$guid = $request['sourceurl'] ?? '';
$guid = urldecode( $guid );
if ( empty( $guid ) ) {
return new WP_Error(
'rest_search_invalid_sourceurl',
__( 'Invalid source URL.', 'try_wordpress' ),
array( 'status' => 400 )
);
}
$post_id = $this->get_post_id_by_guid( $guid );
if ( $post_id ) {
$post = get_post( $post_id, ARRAY_A );
return $this->prepare_item_for_response( $post, $request );
}
return new WP_Error(
'rest_not_found',
__( 'Not found', 'try_wordpress' ),
array( 'status' => 404 )
);
}
public function prepare_item_for_response( $item, $request ): WP_REST_Response|WP_Error {
if ( empty( $item['ID'] ) ) {
return new WP_Error(
'rest_post_missing_id',
__( 'Missing post ID when preparing item for response.', 'try_wordpress' ),
array( 'status' => 500 )
);
}
$subject_type = $this->get_subject_type( $request );
$response = array(
'id' => $item['ID'],
'authorId' => $item['post_author'] ?? '',
'sourceUrl' => $item['guid'] ?? '',
'sourceHtml' => $item['post_content_filtered'] ?? '',
'transformedId' => absint( get_post_meta( $item['ID'], Transformer::META_KEY_LIBERATED_OUTPUT, true ) ),
);
foreach ( array_keys( Schema::get()[ $subject_type ]['fields'] ) as $field_name ) {
$response[ 'raw' . ucfirst( $field_name ) ] = get_post_meta( $item['ID'], 'raw_' . $field_name, true );
$response[ 'parsed' . ucfirst( $field_name ) ] = get_post_meta( $item['ID'], 'parsed_' . $field_name, true );
}
$response['previewUrl'] = get_permalink( $response['transformedId'] );
return new WP_REST_Response( $response );
}
public function prepare_item_for_database( $request ): array {
$prepared_post = array();
$request_data = json_decode( $request->get_body(), true );
$subject_type = $this->get_subject_type( $request );
// Prepare $postarr that can be passed to wp_insert_post()
$prepared_post['ID'] = $request['id'];
$prepared_post['post_type'] = $this->storage_post_type;
$prepared_post['post_content_filtered'] = $request_data['sourceHtml'] ?? '';
$prepared_post['guid'] = $request_data['sourceUrl'] ?? '';
$prepared_post['post_author'] = $request_data['authorId'] ?? '';
$prepared_post['meta'] = array();
foreach ( array_keys( Schema::get()[ $subject_type ]['fields'] ) as $field_name ) {
$prepared_post['meta'][ 'raw_' . $field_name ] = $request_data[ 'raw' . ucfirst( $field_name ) ] ?? '';
$prepared_post['meta'][ 'parsed_' . $field_name ] = $request_data[ 'parsed' . ucfirst( $field_name ) ] ?? '';
}
return $prepared_post;
}
public function get_post_id_by_guid( string $guid ): ?int {
// Use wp_cache_* for guid -> postId
$cache_group = 'try_wp';
$cache_key = 'try_wp_cache_guid_' . md5( $guid );
$post_id = wp_cache_get( $cache_key, $cache_group );
if ( false !== $post_id ) {
// Cache hit - get post using WordPress API
$post = get_post( $post_id );
if ( $post ) {
return (int) $post_id;
}
// If post not found despite cache hit, delete the cache
wp_cache_delete( $cache_key, $cache_group );
}
// Cache miss - query database
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$post_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT ID FROM $wpdb->posts WHERE guid = %s",
$guid
)
);
if ( $post_id ) {
// Cache the post ID for future lookups
wp_cache_set( $cache_key, $post_id, $cache_group, YEAR_IN_SECONDS );
return (int) $post_id;
}
return null;
}
private function get_subject_type( $request ): string {
preg_match( '/\/subjects\/([^\/]+)/', $request->get_route(), $matches );
return $matches[1];
}
}