-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathWP_Export_Query.php
More file actions
450 lines (386 loc) · 14.3 KB
/
WP_Export_Query.php
File metadata and controls
450 lines (386 loc) · 14.3 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
<?php
/**
* Represents a set of posts and other site data to be exported.
*
* An immutable object, which gathers all data needed for the export.
*/
class WP_Export_Query {
const QUERY_CHUNK = 100;
private static $defaults = [
'post_ids' => null,
'post_type' => null,
'status' => null,
'author' => null,
'start_date' => null,
'end_date' => null,
'start_id' => null,
'max_num_posts' => null,
'category' => null,
'allow_orphan_terms' => null,
];
private $post_ids;
private $filters;
private $where_clauses = [];
private $joins = [];
private $author;
private $category;
public $missing_parents = false;
public function __construct( $filters = [] ) {
$this->filters = wp_parse_args( $filters, self::$defaults );
$user = $this->find_user_from_any_object( $this->filters['author'] );
if ( $user && ! is_wp_error( $user ) ) {
$this->author = $user;
}
$this->post_ids = $this->calculate_post_ids();
}
public function post_ids() {
return $this->post_ids;
}
public function charset() {
return get_bloginfo( 'charset' );
}
public function site_metadata() {
$metadata = [
'name' => $this->bloginfo_rss( 'name' ),
'url' => $this->bloginfo_rss( 'url' ),
'language' => $this->bloginfo_rss( 'language' ),
'description' => $this->bloginfo_rss( 'description' ),
'pubDate' => date( 'D, d M Y H:i:s +0000' ), // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
'site_url' => is_multisite() ? network_home_url() : $this->bloginfo_rss( 'url' ),
'blog_url' => $this->bloginfo_rss( 'url' ),
];
return $metadata;
}
public function wp_generator_tag() {
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
return apply_filters( 'the_generator', get_the_generator( 'export' ), 'export' );
}
public function authors() {
global $wpdb;
// If we're filtering by a specific author, we only need to include that
// author's user object, and no other users.
if ( is_object( $this->author ) && property_exists( $this->author, 'ID' ) ) {
return [ $this->author ];
}
$authors = [];
$author_ids = (array) $wpdb->get_col( "SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_status != 'auto-draft' AND post_type != 'oembed_cache'" );
foreach ( $author_ids as $author_id ) {
$authors[] = get_userdata( $author_id );
}
$authors = array_filter( $authors );
return $authors;
}
public function categories() {
if ( $this->category ) {
return [ $this->category ];
}
if ( $this->filters['post_type'] ) {
return [];
}
$categories = (array) get_categories( [ 'get' => 'all' ] );
$categories = $this->process_orphaned_terms( $categories );
$categories = self::topologically_sort_terms( $categories );
return $categories;
}
public function tags() {
if ( $this->filters['post_type'] ) {
return [];
}
$tags = (array) get_tags( [ 'get' => 'all' ] );
$tags = $this->process_orphaned_terms( $tags );
return $tags;
}
public function custom_taxonomies_terms() {
if ( $this->filters['post_type'] ) {
return [];
}
$custom_taxonomies = get_taxonomies( [ '_builtin' => false ] );
// phpcs:ignore WordPress.WP.DeprecatedParameters.Get_termsParam2Found -- Deprecated, but we need to support older versions of WordPress.
$custom_terms = (array) get_terms( $custom_taxonomies, [ 'get' => 'all' ] );
$custom_terms = $this->process_orphaned_terms( $custom_terms );
$custom_terms = self::topologically_sort_terms( $custom_terms );
return $custom_terms;
}
public function nav_menu_terms() {
$nav_menus = wp_get_nav_menus();
foreach ( $nav_menus as $term ) {
$term->description = '';
}
return $nav_menus;
}
public function exportify_post( $post ) {
/**
* @var \WP_Query $wp_query
*/
global $wp_query;
$wp_query->in_the_loop = true;
$previous_global_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Temporary override.
$GLOBALS['post'] = $post;
setup_postdata( $post );
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
$post->post_content = apply_filters( 'the_content_export', $post->post_content );
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
$post->post_excerpt = apply_filters( 'the_excerpt_export', $post->post_excerpt );
$post->is_sticky = is_sticky( $post->ID ) ? 1 : 0;
$post->terms = self::get_terms_for_post( $post );
$post->meta = self::get_meta_for_post( $post );
$post->comments = $this->get_comments_for_post( $post );
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Revert back to original.
$GLOBALS['post'] = $previous_global_post;
return $post;
}
public function posts() {
$posts_iterator = new WP_Post_IDs_Iterator( $this->post_ids, self::QUERY_CHUNK );
return new WP_Map_Iterator( $posts_iterator, [ $this, 'exportify_post' ] );
}
private function calculate_post_ids() {
global $wpdb;
if ( is_array( $this->filters['post_ids'] ) ) {
if ( $this->filters['with_attachments'] ) {
$attachment_post_ids = $this->include_attachment_ids( $this->filters['post_ids'] );
$this->filters['post_ids'] = array_merge( $this->filters['post_ids'], $attachment_post_ids );
}
return $this->filters['post_ids'];
}
$this->post_type_where();
$this->status_where();
$this->author_where();
$this->start_date_where();
$this->end_date_where();
$this->start_id_where();
$this->category_where();
$where = implode( ' AND ', array_filter( $this->where_clauses ) );
if ( $where ) {
$where = "WHERE $where";
}
$join = implode( ' ', array_filter( $this->joins ) );
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Individual where clauses run through $wpdb->prepare().
$post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} AS p {$join} {$where} {$this->max_num_posts()}" );
if ( $this->filters['post_type'] ) {
$post_ids = array_merge( $post_ids, $this->include_attachment_ids( $post_ids ) );
}
return $post_ids;
}
private function post_type_where() {
$post_types_filters = [ 'can_export' => true ];
if ( $this->filters['post_type'] ) {
$post_types = $this->filters['post_type'];
// Flatten single post types
if ( is_array( $post_types ) && 1 === count( $post_types ) ) {
$post_types = array_shift( $post_types );
}
$post_types_filters = array_merge( $post_types_filters, [ 'name' => $post_types ] );
}
// Multiple post types
if ( isset( $post_types_filters['name'] ) && is_array( $post_types_filters['name'] ) ) {
$post_types = [];
foreach ( $post_types_filters['name'] as $post_type ) {
/**
* @var string $post_type
*/
if ( post_type_exists( $post_type ) ) {
$post_types[] = $post_type;
}
}
} else {
$post_types = get_post_types( $post_types_filters );
}
if ( ! $post_types ) {
$this->where_clauses[] = 'p.post_type IS NULL';
return;
}
if ( false === $this->filters['with_attachments'] && ( ! $this->filters['post_type'] || ! in_array( 'attachment', $this->filters['post_type'], true ) ) ) {
unset( $post_types['attachment'] );
}
$this->where_clauses[] = _wp_export_build_IN_condition( 'p.post_type', $post_types );
}
private function status_where() {
global $wpdb;
if ( ! $this->filters['status'] ) {
$this->where_clauses[] = "p.post_status != 'auto-draft'";
return;
}
$this->where_clauses[] = $wpdb->prepare( 'p.post_status = %s', $this->filters['status'] );
}
private function author_where() {
global $wpdb;
if ( is_object( $this->author ) && property_exists( $this->author, 'ID' ) ) {
$this->where_clauses[] = $wpdb->prepare( 'p.post_author = %d', $this->author->ID );
}
}
private function start_date_where() {
global $wpdb;
$timestamp = $this->filters['start_date'] ? strtotime( $this->filters['start_date'] ) : null;
if ( ! $timestamp ) {
return;
}
$this->where_clauses[] = $wpdb->prepare( 'p.post_date >= %s', date( 'Y-m-d 00:00:00', $timestamp ) ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
}
private function end_date_where() {
global $wpdb;
if ( ! $this->filters['end_date'] ) {
return;
}
if ( preg_match( '/^\d{4}-\d{2}$/', $this->filters['end_date'] ) ) {
$timestamp = $this->get_timestamp_for_the_last_day_of_a_month( $this->filters['end_date'] );
} else {
$timestamp = strtotime( $this->filters['end_date'] );
}
if ( ! $timestamp ) {
return;
}
$this->where_clauses[] = $wpdb->prepare( 'p.post_date <= %s', date( 'Y-m-d 23:59:59', $timestamp ) ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
}
private function start_id_where() {
global $wpdb;
$start_id = absint( $this->filters['start_id'] );
if ( 0 === $start_id ) {
return;
}
$this->where_clauses[] = $wpdb->prepare( 'p.ID >= %d', $start_id );
}
private function get_timestamp_for_the_last_day_of_a_month( $yyyy_mm ) {
return strtotime( "$yyyy_mm +1month -1day" );
}
private function category_where() {
global $wpdb;
if ( 'post' !== $this->filters['post_type'] && ! in_array( 'post', (array) $this->filters['post_type'], true ) ) {
return;
}
$category = $this->find_category_from_any_object( $this->filters['category'] );
if ( ! $category ) {
return;
}
$this->category = $category;
$this->joins[] = "INNER JOIN {$wpdb->term_relationships} AS tr ON (p.ID = tr.object_id)";
$this->where_clauses[] = $wpdb->prepare( 'tr.term_taxonomy_id = %d', $category->term_taxonomy_id );
}
private function max_num_posts() {
if ( $this->filters['max_num_posts'] > 0 ) {
return "LIMIT {$this->filters['max_num_posts']}";
} else {
return '';
}
}
private function include_attachment_ids( $post_ids ) {
global $wpdb;
if ( ! $post_ids ) {
return [];
}
$attachment_ids = [];
// phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition -- Assignment is part of the break condition.
while ( $batch_of_post_ids = array_splice( $post_ids, 0, self::QUERY_CHUNK ) ) {
$post_parent_condition = _wp_export_build_IN_condition( 'post_parent', $batch_of_post_ids );
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Escaped in wpcli_export_build_in_condition() function.
$attachment_ids = array_merge( $attachment_ids, (array) $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND {$post_parent_condition}" ) );
}
return array_map( 'intval', $attachment_ids );
}
private function bloginfo_rss( $section ) {
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
return apply_filters( 'bloginfo_rss', get_bloginfo_rss( $section ), $section );
}
private function find_user_from_any_object( $user ) {
if ( is_numeric( $user ) ) {
return get_user_by( 'id', (int) $user );
} elseif ( is_string( $user ) ) {
return get_user_by( 'login', $user );
} elseif ( isset( $user->ID ) ) {
return get_user_by( 'id', $user->ID );
}
return false;
}
private function find_category_from_any_object( $category ) {
if ( is_numeric( $category ) ) {
return get_term( (int) $category, 'category' );
} elseif ( is_string( $category ) ) {
$term = term_exists( $category, 'category' );
return isset( $term['term_id'] ) ? get_term( (int) $term['term_id'], 'category' ) : false;
} elseif ( isset( $category->term_id ) ) {
return get_term( $category->term_id, 'category' );
}
return false;
}
private static function topologically_sort_terms( $terms ) {
$sorted = [];
// phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition -- assignment is used as break condition.
while ( $term = array_shift( $terms ) ) {
if ( 0 === (int) $term->parent || isset( $sorted[ $term->parent ] ) ) {
$sorted[ $term->term_id ] = $term;
} else {
$terms[] = $term;
}
}
return $sorted;
}
private function process_orphaned_terms( $terms ) {
$term_ids = [];
$have_parent = [];
$orphans = [];
foreach ( $terms as $term ) {
$term_ids[ $term->term_id ] = true;
if ( 0 !== (int) $term->parent ) {
$have_parent[] = $term;
}
}
foreach ( $have_parent as $has_parent ) {
if ( ! isset( $term_ids[ $has_parent->parent ] ) ) {
if ( $this->filters['allow_orphan_terms'] ) {
$orphans[ $has_parent->term_id ] = true;
} else {
$this->missing_parents = $has_parent;
throw new WP_Export_Term_Exception( "Term is missing a parent: {$has_parent->slug} ({$has_parent->term_taxonomy_id})" );
}
}
}
if ( ! $this->filters['allow_orphan_terms'] ) {
return $terms;
}
if ( count( $orphans ) > 0 ) {
$terms_return = [];
foreach ( $terms as $term ) {
if ( isset( $orphans[ $term->term_id ] ) ) {
$term->parent = 0;
}
$terms_return[] = $term;
}
$terms = $terms_return;
}
return $terms;
}
private static function get_terms_for_post( $post ) {
$taxonomies = get_object_taxonomies( $post->post_type );
if ( empty( $taxonomies ) ) {
return [];
}
return wp_get_object_terms( $post->ID, $taxonomies ) ?: [];
}
private static function get_meta_for_post( $post ) {
global $wpdb;
$meta_for_export = [];
$meta_from_db = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) );
foreach ( $meta_from_db as $meta ) {
if ( '_edit_lock' === $meta->meta_key ) {
continue;
}
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) ) {
continue;
}
$meta_for_export[] = $meta;
}
return $meta_for_export;
}
private function get_comments_for_post( $post ) {
global $wpdb;
if ( isset( $this->filters['skip_comments'] ) ) {
return [];
}
$comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) );
foreach ( $comments as $comment ) {
$comment->meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $comment->comment_ID ) ) ?: [];
}
return $comments;
}
}