-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathterm-activity.php
283 lines (247 loc) · 7.42 KB
/
term-activity.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
<?php
/**
* Plugin Name: Term Activity
* Plugin Description: Adds a summary of post counts by period to term meta.
* Author: Edward Ficklin
* Author URI: https://github.com/eficklin
* Text Domain: term-activity
* License: GPLv2
* License URI: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/
namespace Term_Activity;
require_once 'class-term-activity-maps.php';
class TermActivity {
/**
* @var array
*/
protected $updates = [];
/**
* @var string
*/
protected $action_name = 'term_activity_update';
/**
* Meta key prefix for storing activity snapshots.
*
* @var string
*/
protected $meta_key_prefix = 'term_activity_';
/**
* Some lightweight security in the form of a token to verify a request
* was generated by an instance of this class.
*
* @var string
*/
protected $request_token = 'safetyfirst';
/**
* Supported taxonomies.
*
* @var array
*/
protected $supported_taxonomies = [ 'category' ];
/**
* Time periods for the activity snapshot.
*
* @var int[]
*/
protected const PERIODS = [ 3, 30, 90 ];
/**
* Initialization logic.
*/
public function init() {
// Post published/unpublished.
add_action( 'wp_after_insert_post', [ $this, 'maybe_recalculate_publish' ], 10, 4 );
// Term updates.
add_action( 'added_term_relationship', [ $this, 'maybe_recalculate_terms' ], 10, 3 );
add_action( 'deleted_term_relationships', [ $this, 'maybe_recalculate_terms' ], 10, 3 );
// Run calculations asynchronously.
add_action( "admin_post_nopriv_{$this->action_name}", [ $this, 'do_update' ] );
add_action( 'shutdown', [ $this, 'do_shutdown' ] );
}
/**
* Add term ID/post type pair to the update queue, if not already there.
*
* @param int $term_id The term ID.
* @param string $post_type The post type.
*/
protected function add_to_updates( $term_id, $post_type ) {
foreach ( $this->updates as $pair ) {
if ( $term_id === $pair['term_id'] && $post_type === $pair['post_type'] ) {
return;
}
}
$this->updates[] = [
'term_id' => $term_id,
'post_type' => $post_type,
];
}
/**
* Update activity snapshots on supported terms when post published.
*
* @param string $post_id The post ID.
* @param \WP_Post $post The post object.
* @param bool $update Is this an update.
* @param null|\WP_Post $post_before The post before.
*/
public function maybe_recalculate_publish( $post_id, $post, $update, $post_before ) {
if ( $post_before && $post_before->post_status === $post->post_status ) {
return;
}
if ( ( $post_before && 'publish' !== $post_before->post_status ) && 'publish' !== $post->post_status ) {
return;
}
$terms = wp_get_object_terms( $post_id, $this->supported_taxonomies );
if ( ! is_array( $terms ) ) {
return;
}
foreach ( $terms as $term ) {
$this->add_to_updates( $term->term_id, $post->post_type );
}
}
/**
* Update activity snapshots on supported terms when term (un)set.
*
* @param int $object_id The object ID.
* @param int|array $tt_ids A single term taxonomy ID or an array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
*/
public function maybe_recalculate_terms( $object_id, $tt_ids, $taxonomy ) {
if ( ! in_array( $taxonomy, $this->supported_taxonomies, true ) ) {
return;
}
$post = get_post( $object_id );
if ( ! $post || 'WP_Post' !== get_class( $post ) ) {
return;
}
// Could be array or int depending on which hook called the function.
if ( ! is_array( $tt_ids ) ) {
$tt_ids = [ $tt_ids ];
}
// Convert term-taxonomy IDs to term IDs.
$term_ids = array_filter(
array_map(
function ( $tt_id ) use ( $taxonomy ) {
$term = get_term_by( 'term_taxonomy_id', $tt_id, $taxonomy );
if ( $term ) {
return $term->term_id;
}
},
$tt_ids
)
);
foreach ( $term_ids as $term_id ) {
$this->add_to_updates( $term_id, $post->post_type );
}
}
/**
* Generates the activity snapshot.
*
* @param \WP_Term $term The term for which to calculate activity.
* @param string $post_type Post type for the calculation.
* @return array The activity snapshot.
*/
protected function calculate_snapshot( \WP_Term $term, string $post_type ) : array {
$snapshot = [
'generated_at' => time(),
'periods' => [],
];
// Reverse sort and get the longest period. Grab the full set of results.
$snapshot_periods = [];
$periods = self::PERIODS;
rsort( $periods );
$period = array_shift( $periods );
$args = [
'post_type' => $post_type,
'post_status' => 'publish',
'tax_query' => [
[
'taxonomy' => $term->taxonomy,
'field' => 'term_id',
'terms' => $term->term_id,
'include_children' => false,
],
],
'posts_per_page' => -1,
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'no_found_rows' => true,
'date_query' => [
[ 'after' => "-{$period} day" ],
],
];
$query = new \WP_Query( $args );
$snapshot_periods[] = [
'days_prior' => $period,
'count' => count( $query->posts ),
];
// Find the subsets, if any, for remaining periods.
$tz = wp_timezone();
foreach ( $periods as $period ) {
if ( ! $query->post_count ) {
$snapshot_periods[] = [
'days_prior' => $period,
'count' => 0,
];
continue;
}
$cutoff = new \DateTimeImmutable( "-{$period} day", $tz );
$posts = array_filter(
$query->posts,
function( $post ) use ( $cutoff, $tz ) {
$post_date = new \DateTimeImmutable( $post->post_date, $tz );
return $post_date > $cutoff;
}
);
$snapshot_periods[] = [
'days_prior' => $period,
'count' => count( $posts ),
];
}
// Put periods back into ascending order.
usort(
$snapshot_periods,
function( $a, $b ) {
return ( $a['days_prior'] < $b['days_prior'] ) ? -1 : 1;
}
);
$snapshot['periods'] = $snapshot_periods;
return $snapshot;
}
public function do_update() {
$verify = $_REQUEST['request_token'] === $this->request_token;
if ( ! $verify ) {
return;
}
if ( ! isset( $_REQUEST['updates'] ) || ! is_array( $_REQUEST['updates'] ) ) {
return;
}
foreach( $_REQUEST['updates'] as $pair ) {
$term = get_term( (int) $pair['term_id'] );
if ( $term && ! is_wp_error( $term ) ) {
$snapshot = $this->calculate_snapshot( $term, 'post' );
update_term_meta(
$pair['term_id'],
$this->meta_key_prefix . $pair['post_type'],
$snapshot
);
}
}
}
public function do_shutdown() {
if ( ! empty( $this->updates ) ) {
$resp = wp_remote_post(
admin_url( '/admin-post.php' ),
[
'body' => [
'action' => $this->action_name,
'updates' => $this->updates,
'request_token' => $this->request_token,
],
/* For convenience in demonstrating the code. Please don't do this for real. */
'sslverify' => false,
]
);
}
}
}
$ta = new TermActivity();
$ta->init();