-
Notifications
You must be signed in to change notification settings - Fork 42
/
wordlift_core_post_entity_relations.php
603 lines (533 loc) · 20.1 KB
/
wordlift_core_post_entity_relations.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
<?php
/**
* Core Post Entity Relations functions.
*
* @since 3.0.0
* @package Wordlift
* @subpackage Wordlift/modules/core
*/
/**
* Checks if a relation is supported
*
* @param string $predicate Name of the relation: 'what' | 'where' | 'when' | 'who'
*
* @return boolean Return true if supported, false otherwise
*/
function wl_core_check_relation_predicate_is_supported( $predicate ) {
return in_array( $predicate, array(
WL_WHAT_RELATION,
WL_WHEN_RELATION,
WL_WHERE_RELATION,
WL_WHO_RELATION,
) );
}
/**
* Return an array of validation rules used by wl_core_get_posts
*
* @return array in the format field => (array) accepeted_values
*/
function wl_core_get_validation_rules() {
return unserialize( WL_CORE_GET_POSTS_VALIDATION_RULES );
}
/**
* Return the wordlift relation instances table name
*
* @return string Return the wordlift relation instances table name
*/
function wl_core_get_relation_instances_table_name() {
global $wpdb;
$table_name = $wpdb->prefix . WL_DB_RELATION_INSTANCES_TABLE_NAME;
return $table_name;
}
/**
* Create a single relation instance if the given instance does not exist on the table
*
* @param int $subject_id The post ID | The entity post ID.
* @param string $predicate Name of the relation: 'what' | 'where' | 'when' | 'who'
* @param int $object_id The entity post ID.
*
* @uses $wpdb->replace() to perform the query
* @return integer|boolean Return then relation instance ID or false.
*/
function wl_core_add_relation_instance( $subject_id, $predicate, $object_id ) {
// Checks on subject and object
if ( ! is_numeric( $subject_id ) || ! is_numeric( $object_id ) ) {
return false;
}
// Checks on the given relation
if ( ! wl_core_check_relation_predicate_is_supported( $predicate ) ) {
return false;
}
// Prepare interaction with db
global $wpdb;
// Checks passed. Add relation if not exists:
// See https://codex.wordpress.org/Class_Reference/wpdb#REPLACE_row
$wpdb->replace(
wl_core_get_relation_instances_table_name(),
array(
'subject_id' => $subject_id,
'predicate' => $predicate,
'object_id' => $object_id,
),
array( '%d', '%s', '%d' )
);
// Return record id
return $wpdb->insert_id;
}
/**
* Remove all relation instances for a given $subject_id and $predicate
* If $predicate is omitted, $predicate filter is not applied
*
* @param int $subject_id The post ID | The entity post ID.
*
* @return boolean False for failure. True for success.
*/
function wl_core_delete_relation_instances( $subject_id ) {
// Checks on subject and object
if ( ! is_numeric( $subject_id ) ) {
return false;
}
// Prepare interaction with db
global $wpdb;
// wl_write_log( "Going to delete relation instances [ subject_id :: $subject_id ]");
// @see https://codex.wordpress.org/it:Riferimento_classi/wpdb#DELETE_di_righe
$wpdb->delete(
wl_core_get_relation_instances_table_name(),
array(
'subject_id' => $subject_id,
),
array( '%d' )
);
return true;
}
/**
* Validate filters given as parameters to any *wl_core_get_related_...*
*
* @param array $filters Associative array containing required predicate and post status
*
* @return array Corrected $filters, default is:
* array(
* 'predicate' => null,
* 'status' => null
* );
*/
function wl_core_validate_filters_for_related( $filters ) {
if ( ! is_array( $filters ) ) {
$filters = array();
}
if ( ! isset( $filters['predicate'] ) ) {
$filters['predicate'] = null;
}
if ( ! isset( $filters['status'] ) ) {
$filters['status'] = null;
}
return $filters;
}
///**
// * Find all entities related to a given $subject_id
// * If $predicate is omitted, $predicate filter is not applied
// * @uses wl_core_inner_get_related_entities() to perform the action
// *
// * @param int $subject_id The post ID | The entity post ID.
// * @param array $filters Associative array formed like this:
// * <code>
// * $filters = array(
// * 'predicate' => Name of the relation: [ null | 'what' | 'where' | 'when' | 'who' ], default is null (meaning *any* post status)
// * 'status' => [ null | 'publish' | 'draft' | 'pending' | 'trash' ], default is null (meaning *any* post status)
// * );
// * </code>
// *
// * @return array Array of post entity objects.
// */
//function wl_core_get_related_entities( $subject_id, $filters = array() ) {
//
// $filters = wl_core_validate_filters_for_related( $filters );
//
// return wl_core_inner_get_related_entities( "posts", $subject_id, $filters['predicate'], $filters['status'] );
//}
/**
* Find all entity ids related to a given $subject_id
* If $predicate is omitted, $predicate filter is not applied
*
* @deprecated use Wordlift_Relation_Service::get_instance()->get_objects( $subject_id, 'ids', $predicate, $status );
*
* @uses wl_core_inner_get_related_entities() to perform the action
*
* @param int $subject_id The post ID | The entity post ID.
* @param array $filters Associative array formed like this:
* <code>
* $filters = array(
* 'predicate' => Name of the relation: [ null | 'what' | 'where' | 'when' | 'who' ], default is null (meaning *any* post status)
* 'status' => [ null | 'publish' | 'draft' | 'pending' | 'trash' ], default is null (meaning *any* post status)
* );
* </code>
*
* @return array Array of post entity objects.
*/
function wl_core_get_related_entity_ids( $subject_id, $filters = array() ) {
$status = isset( $filters['status'] ) ? $filters['status'] : null;
$predicate = isset( $filters['predicate'] ) ? $filters['predicate'] : null;
return Wordlift_Relation_Service::get_instance()->get_objects( $subject_id, 'ids', $predicate, $status );
// $filters = wl_core_validate_filters_for_related( $filters );
//
// return wl_core_inner_get_related_entities( 'post_ids', $subject_id, $filters['predicate'], $filters['status'] );
}
/**
* Get the entities related to the specified {@link WP_Post}.
*
* This function is deprecated and left for compatibility with 3rd parties.
*
* @deprecated use Wordlift_Relation_Service::get_instance()->get_objects()
*
* @param int $subject_id The {@link WP_Post}'s id.
* @param array $filters An array of filters.
*
* @return array An array of {@link WP_Post}s.
*/
function wl_core_get_related_entities( $subject_id, $filters = array() ) {
$ids = wl_core_get_related_entity_ids( $subject_id, $filters );
return array_map( function ( $item ) {
return get_post( $item );
}, $ids );
}
//
///**
// * Find all entity ids related to a given $subject_id
// * If $predicate is omitted, $predicate filter is not applied
// * Do not use it directly. Use wl_core_get_related_entities or wl_core_get_related_entity_ids instead.
// *
// * @param $get
// * @param $item_id
// * @param string $predicate Name of the relation: null | 'what' | 'where' | 'when' | 'who'
// * @param string $post_status Filter by post status null | 'publish' | 'draft' | 'pending' | 'trash'. null means *any* post status
// *
// * @return array Array of ids.
// */
//function wl_core_inner_get_related_entities( $get, $item_id, $predicate = null, $post_status = null ) {
//
// if ( $results = wl_core_get_posts( array(
// 'get' => $get,
// 'post_type' => 'entity',
// 'post_status' => $post_status,
// 'related_to' => $item_id,
// 'as' => 'object',
// 'with_predicate' => $predicate,
// ) )
// ) {
// return $results;
// }
//
// // If wl_core_get_posts return false then an empty array is returned
// return array();
//}
///**
// * Find all posts related to a given $object_id
// * If $predicate is omitted, $predicate filter is not applied
// * @uses wl_core_get_related_posts() to perform the action
// *
// * @param int $object_id The entity ID or the post ID.
// * @param array $filters Associative array formed like this:
// * <code>
// * $filters = array(
// * 'predicate' => Name of the relation: [ null | 'what' | 'where' | 'when' | 'who' ], default is null (meaning *any* post status)
// * 'status' => [ null | 'publish' | 'draft' | 'pending' | 'trash' ], default is null (meaning *any* post status)
// * );
// * </code>
// *
// * @return array Array of objects.
// */
//function wl_core_get_related_posts( $object_id, $filters = array() ) {
//
// $filters = wl_core_validate_filters_for_related( $filters );
//
// return wl_core_inner_get_related_posts( "posts", $object_id, $filters['predicate'], $filters['status'] );
//}
/**
* Find all post ids related to a given $object_id
* If $predicate is omitted, $predicate filter is not applied
*
* @deprecated use Wordlift_Relation_Service::get_instance()->get_article_subjects( $object_id, 'ids', $status );
*
* @uses wl_core_get_related_posts() to perform the action
*
* @param int $object_id The entity ID or the post ID.
* @param array $filters Associative array formed like this:
* <code>
* $filters = array(
* 'predicate' => Name of the relation: [ null | 'what' | 'where' | 'when' | 'who' ], default is null (meaning *any* post status)
* 'status' => [ null | 'publish' | 'draft' | 'pending' | 'trash' ], default is null (meaning *any* post status)
* );
* </code>
*
* @return array Array of objects.
*/
function wl_core_get_related_post_ids( $object_id, $filters = array() ) {
$relation_service = Wordlift_Relation_Service::get_instance();
$status = isset( $filters['status'] ) ? $filters['status'] : null;
$predicate = isset( $filters['predicate'] ) ? $filters['predicate'] : null;
return $relation_service->get_article_subjects( $object_id, 'ids', $predicate, $status );
//
// $filters = wl_core_validate_filters_for_related( $filters );
//
// return wl_core_inner_get_related_posts( 'post_ids', $object_id, $filters['predicate'], $filters['status'] );
}
/**
* Get the posts related to the specified entity {@link WP_Post}.
*
* This function is deprecated and left for compatibility with 3rd parties.
*
* @deprecated use Wordlift_Relation_Service::get_instance()->get_article_subjects()
*
* @param int $subject_id The entity's {@link WP_Post}'s id. If a post/page id
* is provided, then the entities bound to that post/page
* are first loaded.
* @param array $filters An array of filters.
*
* @return array An array of {@link WP_Post}s.
*/
function wl_core_get_related_posts( $subject_id, $filters = array() ) {
$ids = wl_core_get_related_post_ids( $subject_id, $filters );
return array_map( function ( $item ) {
return get_post( $item );
}, $ids );
}
///**
// * Find all posts related to a given $object_id
// * If $predicate is omitted, $predicate filter is not applied
// * Not use it directly. Use wl_core_get_related_posts or wl_core_get_related_posts_ids instead.
// *
// * @param string $get
// * @param int $item_id
// * @param string $predicate Name of the relation: null | 'what' | 'where' | 'when' | 'who'
// * @param string $post_status Filter by post status null | 'publish' | 'draft' | 'pending' | 'trash'. null means *any* post status
// *
// * @return array Array of objects.
// */
//function wl_core_inner_get_related_posts( $get, $item_id, $predicate = null, $post_status = null ) {
//
// // Retrieve the post object
// $post = get_post( $item_id );
// if ( null === $post ) {
// return array();
// }
//
// if ( 'entity' === $post->post_type ) {
// if ( $results = wl_core_get_posts( array(
// 'get' => $get,
// 'post_type' => 'post',
// 'post_status' => $post_status,
// 'related_to' => $item_id,
// 'as' => 'subject',
// 'with_predicate' => $predicate,
// ) )
// ) {
// return $results;
// }
// } else {
// if ( $results = wl_core_get_posts( array(
// 'get' => $get,
// 'post_type' => 'post',
// 'post_status' => $post_status,
// 'post__not_in' => array( $item_id ),
// 'related_to__in' => wl_core_get_related_entity_ids( $post->ID ),
// 'as' => 'subject',
// 'with_predicate' => $predicate,
// ) )
// ) {
// return $results;
// }
// }
//
// // If wl_core_get_posts return false then an empty array is returned
// return array();
//}
/**
* Define a sql statement between wp_posts and wp_wl_relation_instances tables
* It's used by wl_core_get_posts. Implements a subset of WpQuery object
* @see https://codex.wordpress.org/Class_Reference/WP_Query
* Arguments validation is delegated to wl_core_get_posts method.
* Form the array like this:
* <code>
* $args = array(
* 'get' => 'posts', // posts, post_ids, relations, relation_ids
* 'first' => n,
* 'related_to' => 10, // the post/s / entity/ies id / ids
* 'related_to__in' => array(10,20,30)
* 'post__in' => array(10,20,30), // the post/s / entity/ies id / ids
* 'post__not_in' => array(10,20,30), // the post/s / entity/ies id / ids
* 'as' => [ subject | object ],
* 'with_predicate' => [ what | where | when | who ], // null as default value
* 'post_type' => [ post | entity ],
* 'post_status' => [ publish | draft | pending | trash ], default is null (meaning *any* post status)
* );
* </code>
*
* Since 3.15 post_type of 'post' serves as an indication of whether articles
* while a post type of 'entity' means a non article, instead of being used as explicit
* post types for the query.
*
* @param array $args Arguments to be used in the query builder.
*
* @return string|false String representing a sql statement, or false in case of error
*/
function wl_core_sql_query_builder( $args ) {
// Prepare interaction with db
global $wpdb;
// Retrieve Wordlift relation instances table name
$table_name = wl_core_get_relation_instances_table_name();
// When type is set to `post` we're looking for `post`s that are not
// configured as entities.
// When the type is set to `entity` we're looking also for `post`s that are
// configured as entities.
// Since we want Find only articles, based on the entity type, we need
// to figure out the relevant sql statements to add to the join and where
// parts.
$tax_query = array(
array(
'taxonomy' => Wordlift_Entity_Types_Taxonomy_Service::TAXONOMY_NAME,
'field' => 'slug',
'terms' => 'article',
'operator' => 'entity' === $args['post_type'] ? 'NOT IN' : 'IN',
),
);
// Use "p" as the table to match the initial join.
$tax_sql = get_tax_sql( $tax_query, 'p', 'ID' );
// Sql Action
$sql = 'SELECT ';
// Determine what has to be returned depending on 'get' argument value
switch ( $args['get'] ) {
case 'posts':
$sql .= 'p.*';
break;
case 'post_ids':
$sql .= 'p.id';
break;
}
// If we look for posts related as objects the JOIN has to be done with the object_id column and viceversa
$join_column = $args['as'] . '_id';
$sql .= " FROM $wpdb->posts as p JOIN $table_name as r ON p.id = r.$join_column";
// Changing left join generate by the tax query into an inner since the term relationship has to exist.
$sql .= str_replace( 'LEFT JOIN', 'INNER JOIN', $tax_sql['join'] );
// Sql add post type filter
$post_types = Wordlift_Entity_Service::valid_entity_post_types();
$sql .= " AND p.post_type IN ('" . join( "', '", esc_sql( $post_types ) ) . "') AND";
// Sql add post status filter
if ( isset( $args['post_status'] ) && ! is_null( $args['post_status'] ) ) {
$sql .= $wpdb->prepare( ' p.post_status = %s AND', $args['post_status'] );
}
// Add filtering conditions
// If we look for posts related as objects this means that
// related_to is a reference for a subject: subject_id is the filtering column
// If we look for posts related as subject this means that
// related_to is reference for an object: object_id is the filtering column
$filtering_column = ( 'object' == $args['as'] ) ? 'subject_id' : 'object_id';
if ( isset( $args['related_to'] ) ) {
$sql .= $wpdb->prepare( " r.$filtering_column = %d", $args['related_to'] );
}
if ( isset( $args['related_to'] ) && isset( $args['related_to__in'] ) ) {
$sql .= ' AND';
}
if ( isset( $args['related_to__in'] ) ) {
$sql .= " r.$filtering_column IN (" . implode( ',', $args['related_to__in'] ) . ')';
// The IDs used for filtering shouldn't be in the results.
$sql .= " AND p.ID NOT IN (" . implode( ',', $args['related_to__in'] ) . ')';
}
if ( isset( $args['post__not_in'] ) ) {
$sql .= ' AND r.' . $args['as'] . '_id NOT IN (' . implode( ',', $args['post__not_in'] ) . ')';
}
if ( isset( $args['post__in'] ) ) {
$sql .= ' AND r.' . $args['as'] . '_id IN (' . implode( ',', $args['post__in'] ) . ')';
}
// Add predicate filter if required.
if ( isset( $args['with_predicate'] ) ) {
// Sql Inner Join clause.
$sql .= $wpdb->prepare( ' AND r.predicate = %s', $args['with_predicate'] );
}
// Add the taxonomy related sql.
$sql .= $tax_sql['where'];
// Add a group by clause to avoid duplicated rows
// @todo: isn't a distinct a better choice?
$sql .= ' GROUP BY p.id';
// @todo: how does `first` represent the limit?
if ( isset( $args['first'] ) && is_numeric( $args['first'] ) ) {
// Sql Inner Join clause.
$sql .= $wpdb->prepare( ' LIMIT %d', $args['first'] );
}
// Close sql statement
$sql .= ';';
return $sql;
}
/**
* Perform a query on db depending on args
* It's responsible for argument validations
* @uses wl_core_sql_query_builder() to compose the sql statement
* @uses wpdb() instance to perform the query
*
* @param array $args Arguments to be used in the query builder.
*
* @param string $returned_type
*
* @return array|false List of WP_Post objects or list of WP_Post ids. False in case of error or invalid params
*/
function wl_core_get_posts( $args, $returned_type = OBJECT ) {
// Merge given args with defaults args value
$args = array_merge( array(
'with_predicate' => null,
'as' => 'subject',
'post_type' => 'post',
'get' => 'posts',
'post_status' => null,
), $args );
// Arguments validation rules
// At least one between related_to and related_to__in has to be set
if ( ! isset( $args['related_to'] ) && ! isset( $args['related_to__in'] ) ) {
return false;
}
if ( isset( $args['related_to'] ) && ! is_numeric( $args['related_to'] ) ) {
return false;
}
// The same check is applied to post_in, post__not_in and related_to__in options
// Only arrays with at least one numeric value are considerad valid
// The argument value is further sanitized in order to clean up not numeric values
foreach (
array(
'post__in',
'post__not_in',
'related_to__in',
) as $option_name
) {
if ( isset( $args[ $option_name ] ) ) {
if ( ! is_array( $args[ $option_name ] ) || 0 == count( array_filter( $args[ $option_name ], "is_numeric" ) ) ) {
return false;
}
// Sanitize value removing non numeric values from the array
$args[ $option_name ] = array_filter( $args[ $option_name ], "is_numeric" );
}
}
// Performing validation rules
foreach ( wl_core_get_validation_rules() as $option_name => $accepeted_values ) {
if ( isset( $args[ $option_name ] ) && ! is_null( $args[ $option_name ] ) ) {
if ( ! in_array( $args[ $option_name ], $accepeted_values ) ) {
return false;
}
}
}
// Prepare interaction with db
global $wpdb;
// Build sql statement with given arguments
$sql_statement = wl_core_sql_query_builder( $args );
// If ids are required, returns a one-dimensional array containing ids.
// Otherwise an array of associative arrays representing the post | relation object
if ( 'post_ids' == $args['get'] ) {
# See https://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Column
$results = $wpdb->get_col( $sql_statement );
} else {
$results = $wpdb->get_results( $sql_statement, $returned_type );
}
// If there were an error performing the query then false is returned
if ( ! empty( $wpdb->last_error ) ) {
return false;
}
// Finally
return $results;
}