PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 2.14.1
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v2.14.1
2.14.1 2.14.0 2.13.0 2.12.0 2.11.0 2.10.0 2.9.0 2.8.0 2.7.0 2.6.0 2.5.0 2.4.0 2.3.0 2.2.0 2.1.1 2.1.0 2.0.2 2.0.1 2.0.0 1.32.0 1.31.0 1.30.0 1.29.0 1.28.0 1.27.0 All 56 releases
← All changes | includes/seo/class-sitemap-generator.php +591 -106 2.10.0 → 2.14.1 View file →
@@ -251,8 +251,33 @@
251 251 * @var int
252 252 */
253 253 private const TERM_WALK_CHUNK = 1000;
254 254
255 + /**
256 + * Exception code for an automatic rebuild stopped short of the memory limit.
257 + *
258 + * @since 2.10.1
259 + * @var int
260 + */
261 + private const MEMORY_ABORT_CODE = 4290;
262 +
263 + /**
264 + * Whether the chunked walks should stop before the memory limit. Only on
265 + * for automatic rebuilds, whose failure is recorded and retried.
266 + *
267 + * @since 2.10.1
268 + * @var bool
269 + */
270 + private bool $memory_guard = false;
271 +
272 + /**
273 + * Largest memory cost of one walked chunk in this rebuild, in bytes.
274 + *
275 + * @since 2.10.1
276 + * @var int
277 + */
278 + private int $walk_chunk_cost = 0;
279 +
255 280 private array $sitemap_types = [
256 281 'posts' => [
257 282 'name' => 'Posts',
258 283 'post_types' => ['post'],
@@ -279,25 +304,29 @@
279 304 ]
280 305 ];
281 306
282 307 /**
308 + * The generator the content-change listeners share, built on the first
309 + * change of a request.
310 + *
311 + * @since 2.10.1
312 + * @var self|null
313 + */
314 + private static ?self $listener = null;
315 +
316 + /**
283 317 * Constructor
284 318 *
285 319 * @since 1.0.0
320 + * @since 2.10.1 Registers no hooks, whatever `$register_hooks` says. The
321 + * content-change listeners are registered once, at bootstrap,
322 + * by register_content_listeners().
286 323 *
287 - * @param bool $register_hooks Optional. Whether to register the auto-generation
288 - * hooks. Pass false for a read-only instance built
289 - * solely to query settings — the hooks are bound to
290 - * `$this`, so a second hook-registering instance
291 - * would run `handle_content_change()` twice per save.
324 + * @param bool $register_hooks Unused since 2.10.1; kept so existing callers,
325 + * Pro's included, keep working.
292 326 */
293 327 public function __construct(bool $register_hooks = true) {
294 328 parent::__construct('sitemap');
295 -
296 - // Initialize auto-generation hooks
297 - if ($register_hooks) {
298 - $this->init_auto_generation_hooks();
299 - }
300 329 }
301 330
302 331 /**
303 332 * Filter the args of a sitemap post query.
@@ -341,34 +370,154 @@
341 370 return (array) apply_filters('thinkrank_sitemap_term_query_args', $args);
342 371 }
343 372
344 373 /**
345 - * Initialize WordPress hooks for auto-generation
374 + * Register the content-change listeners that queue an automatic rebuild.
346 375 *
347 - * @since 1.0.0
376 + * Called once per request, at plugin bootstrap, next to the WP-Cron
377 + * listeners that run the rebuild these queue (both in
378 + * Plugin::register_sitemap_cron_listeners(), on plugins_loaded). The
379 + * constructor used to register them, so they existed only in a request
380 + * that happened to build a generator: the REST endpoint, the setup wizard,
381 + * an MCP ability. Block-editor saves go through REST and were heard. A
382 + * scheduled post published by WP-Cron, Quick Edit, the classic editor and
383 + * WP-CLI were not, so the post stayed out of the sitemap with nothing
384 + * pending to recover it (#824). Each instance also added its own set, so
385 + * one REST save ran the handlers once per generator built.
386 + *
387 + * The generator is built on the first change and shared for the rest of
388 + * the request, so a bulk edit does not construct one per post.
389 + *
390 + * @since 2.10.1
348 391 * @return void
349 392 */
350 - private function init_auto_generation_hooks(): void {
351 - // Content change hooks - use priority 20 to run after other plugins
352 - add_action('save_post', [$this, 'handle_content_change'], 20, 2);
353 - add_action('delete_post', [$this, 'handle_content_deletion'], 20);
354 - add_action('wp_trash_post', [$this, 'handle_content_deletion'], 20);
355 - add_action('untrash_post', [$this, 'handle_content_change_by_id'], 20);
393 + public static function register_content_listeners(): void {
394 + // Priority 20, to run after other plugins.
395 + add_action('save_post', static function (int $post_id, \WP_Post $post): void {
396 + self::listener()->handle_content_change($post_id, $post);
397 + }, 20, 2);
398 + add_action('delete_post', static function (int $post_id): void {
399 + self::listener()->handle_content_deletion($post_id);
400 + }, 20);
401 + add_action('wp_trash_post', static function (int $post_id): void {
402 + self::listener()->handle_content_deletion($post_id);
403 + }, 20);
404 + add_action('untrash_post', static function (int $post_id): void {
405 + self::listener()->handle_content_change_by_id($post_id);
406 + }, 20);
356 407
357 - // Taxonomy change hooks
358 - add_action('created_term', [$this, 'handle_taxonomy_change'], 20, 3);
359 - add_action('edited_term', [$this, 'handle_taxonomy_change'], 20, 3);
360 - add_action('delete_term', [$this, 'handle_taxonomy_change'], 20, 3);
408 + foreach (['created_term', 'edited_term', 'delete_term'] as $hook) {
409 + add_action($hook, static function (int $term_id, int $tt_id, string $taxonomy): void {
410 + self::listener()->handle_taxonomy_change($term_id, $tt_id, $taxonomy);
411 + }, 20, 3);
412 + }
361 413
362 - // NOTE: the WP-Cron regeneration listeners (thinkrank_regenerate_sitemap
363 - // and thinkrank_regenerate_sitemap_settings) are registered at plugin
364 - // bootstrap (Plugin::register_sitemap_cron_listeners(), on plugins_loaded)
365 - // rather than here. A cron run never builds this class via the REST
366 - // endpoint (no rest_api_init), so registering them in the constructor
367 - // would leave the scheduled events with no listener at cron time.
414 + // The sitemap leaves out what the robots tag noindexes and what
415 + // ThinkRank redirects (#911), so a change to either decides what the
416 + // published files should list. Neither is a post or term save, and
417 + // without these the files kept the old answer until unrelated content
418 + // changed.
419 + foreach (self::ROBOTS_SETTINGS_OPTIONS as $option) {
420 + add_action('update_option_' . $option, static function ($old_value, $value): void {
421 + self::handle_robots_settings_change($old_value, $value);
422 + }, 20, 2);
423 + add_action('add_option_' . $option, static function ($name, $value): void {
424 + self::handle_robots_settings_change([], $value);
425 + }, 20, 2);
426 + }
427 +
428 + add_action('thinkrank_object_redirect_saved', static function (): void {
429 + self::listener()->schedule_regeneration();
430 + }, 20, 0);
368 431 }
369 432
370 433 /**
434 + * Options holding robots directives the sitemap's item filter reads.
435 + *
436 + * @since 2.15.0
437 + * @var string[]
438 + */
439 + private const ROBOTS_SETTINGS_OPTIONS = [
440 + 'thinkrank_global_seo_settings',
441 + 'thinkrank_global_robot_meta_settings',
442 + ];
443 +
444 + /**
445 + * Queue a rebuild when a saved robots setting changes a noindex decision.
446 + *
447 + * Both options carry far more than robots directives (titles, schema,
448 + * feature switches), so only a change to a noindex outcome rebuilds.
449 + *
450 + * @since 2.15.0
451 + *
452 + * @param mixed $old_value Previous option value.
453 + * @param mixed $value New option value.
454 + * @return void
455 + */
456 + public static function handle_robots_settings_change($old_value, $value): void {
457 + if (self::noindex_fingerprint($old_value) === self::noindex_fingerprint($value)) {
458 + return;
459 + }
460 +
461 + // The matrix memoises the option for the request, and a rebuild that
462 + // runs in this request must read the value just saved.
463 + Content_Type_Settings::flush_cache();
464 +
465 + self::listener()->schedule_regeneration();
466 + }
467 +
468 + /**
469 + * The noindex decisions a robots option makes, keyed by what they apply to.
470 + *
471 + * Reads both shapes: the flat site-wide directives, and the per-entity
472 + * rows, where a row's directives apply only while its robots switch is on.
473 + * A row that is on but stores no `noindex` key changes nothing, matching
474 + * the array_merge() the robots tag does.
475 + *
476 + * @since 2.15.0
477 + *
478 + * @param mixed $value Option value.
479 + * @return array<string, bool|null>
480 + */
481 + private static function noindex_fingerprint($value): array {
482 + if (!is_array($value)) {
483 + return [];
484 + }
485 +
486 + $decisions = [];
487 +
488 + if (array_key_exists('noindex', $value) && !is_array($value['noindex'])) {
489 + $decisions['*'] = !empty($value['noindex']);
490 + }
491 +
492 + foreach ($value as $key => $row) {
493 + if (!is_array($row)) {
494 + continue;
495 + }
496 +
497 + $robots = $row['robots_meta'] ?? null;
498 +
499 + $decisions[(string) $key] = !empty($row['robots_meta_enabled']) && is_array($robots) && array_key_exists('noindex', $robots)
500 + ? !empty($robots['noindex'])
501 + : null;
502 + }
503 +
504 + ksort($decisions);
505 +
506 + return $decisions;
507 + }
508 +
509 + /**
510 + * The generator the content-change listeners share.
511 + *
512 + * @since 2.10.1
513 + * @return self
514 + */
515 + private static function listener(): self {
516 + return self::$listener ??= new self(false);
517 + }
518 +
519 + /**
371 520 * Generate XML sitemap
372 521 *
373 522 * @since 1.0.0
374 523 *
@@ -874,8 +1023,11 @@
874 1023 // well-bounded routine with no ceiling (#402).
875 1024 $total = count($all_ids);
876 1025
877 1026 for ($offset = 0; $offset < $total; $offset += self::ID_WALK_CHUNK) {
1027 + $this->assert_memory_headroom();
1028 + $chunk_start = memory_get_usage(true);
1029 +
878 1030 $chunk = array_slice($all_ids, $offset, self::ID_WALK_CHUNK);
879 1031
880 1032 $posts = get_posts($this->filter_query_args([
881 1033 'post_type' => $post_types,
@@ -884,8 +1036,12 @@
884 1036 'post__in' => $chunk,
885 1037 'orderby' => 'post__in', // preserve the resolved order
886 1038 ]));
887 1039
1040 + // get_featured_image() hydrates each featured image under the
1041 + // attachment's own ID, which the chunk's post IDs do not reach.
1042 + $attachment_ids = [];
1043 +
888 1044 foreach ($posts as $post) {
889 1045 if ($this->should_include_in_sitemap($post, $settings)) {
890 1046 /**
891 1047 * Filter a sitemap entry's permalink.
@@ -906,14 +1062,25 @@
906 1062 $priority = $this->calculate_intelligent_priority($post, $post->post_type);
907 1063 $changefreq = $this->calculate_change_frequency($post, $post->post_type);
908 1064 $images = $this->extract_post_images($post, $settings);
909 1065
1066 + $thumbnail_id = (int) get_post_thumbnail_id($post);
1067 + if ($thumbnail_id > 0) {
1068 + $attachment_ids[] = $thumbnail_id;
1069 + }
1070 +
910 1071 yield $this->generate_url_entry($url, $lastmod, $priority, $changefreq, $images);
911 1072 }
912 1073 }
913 1074
914 - // Free the hydrated chunk before loading the next one.
1075 + // Free the hydrated chunk before loading the next one — including
1076 + // the copies get_posts() left in the runtime object cache.
915 1077 unset($posts);
1078 + $this->release_walk_memory(
1079 + $chunk_start,
1080 + $this->chunk_post_cache_groups($post_types),
1081 + array_merge($chunk, $attachment_ids)
1082 + );
916 1083 }
917 1084 }
918 1085
919 1086 /**
@@ -973,8 +1140,11 @@
973 1140 // Same moving window as the post walk above, for the same reason.
974 1141 $total = count($all_ids);
975 1142
976 1143 for ($offset = 0; $offset < $total; $offset += self::TERM_WALK_CHUNK) {
1144 + $this->assert_memory_headroom();
1145 + $chunk_start = memory_get_usage(true);
1146 +
977 1147 $chunk = array_slice($all_ids, $offset, self::TERM_WALK_CHUNK);
978 1148
979 1149 $terms = get_terms($this->filter_term_query_args([
980 1150 'taxonomy' => $taxonomy,
@@ -987,12 +1157,12 @@
987 1157 continue;
988 1158 }
989 1159
990 1160 foreach ($terms as $term) {
991 - // A term the user marked noindex must not be advertised in the
992 - // sitemap: the robots tag now honours term meta, so listing it
993 - // here would have the sitemap contradict the page's own tag.
994 - if ($this->term_is_noindexed((int) $term->term_id)) {
1161 + // A term whose archive says noindex (its own override or its
1162 + // taxonomy's), or that redirects, must not be advertised: the
1163 + // sitemap would contradict the page's own signal (#911).
1164 + if (!Indexability::is_indexable_term($term)) {
995 1165 continue;
996 1166 }
997 1167
998 1168 $url = get_term_link($term);
@@ -1003,8 +1173,9 @@
1003 1173 }
1004 1174 }
1005 1175
1006 1176 unset($terms);
1177 + $this->release_walk_memory($chunk_start, ['terms', 'term_meta'], $chunk);
1007 1178 }
1008 1179 }
1009 1180
1010 1181 /**
@@ -1296,14 +1467,15 @@
1296 1467 if (is_wp_error($all_terms)) {
1297 1468 return [];
1298 1469 }
1299 1470
1300 - // Drop terms the user marked noindex. This path feeds the single general
1301 - // sitemap while collect_taxonomy_entries_iter() feeds the segmented ones,
1302 - // so both need the filter or the two disagree about the same term.
1471 + // Drop terms that are not indexable destinations. This path feeds the
1472 + // single general sitemap while collect_taxonomy_entries_iter() feeds
1473 + // the segmented ones, so both need the filter or the two disagree about
1474 + // the same term.
1303 1475 $all_terms = array_values(array_filter(
1304 1476 $all_terms,
1305 - fn($term) => !$this->term_is_noindexed((int) $term->term_id)
1477 + static fn($term) => $term instanceof \WP_Term && Indexability::is_indexable_term($term)
1306 1478 ));
1307 1479
1308 1480 // Group terms by taxonomy
1309 1481 return $this->group_terms_by_taxonomy($all_terms);
@@ -1485,17 +1657,16 @@
1485 1657 if (!in_array($post->post_status, ['publish', 'private'], true)) {
1486 1658 return false;
1487 1659 }
1488 1660
1489 - // Check if post overrides robots and sets noindex.
1490 - if ((bool) get_post_meta($post->ID, '_thinkrank_robots_meta_enabled', true)) {
1491 - $raw = get_post_meta($post->ID, '_thinkrank_robots_meta', true);
1492 - if (is_string($raw) && $raw !== '') {
1493 - $robots = json_decode($raw, true);
1494 - if (is_array($robots) && !empty($robots['noindex'])) {
1495 - return false;
1496 - }
1497 - }
1661 + // A URL whose page says noindex, or that ThinkRank redirects, is not a
1662 + // destination. Only the per-post noindex used to be read here, so a
1663 + // post type set to No-index still had every item listed, and redirected
1664 + // posts were submitted as "Page with redirect" (#911). The password
1665 + // check stays with the setting above: listing protected posts is a
1666 + // choice this sitemap has always offered.
1667 + if (Indexability::is_post_noindexed($post) || Indexability::is_post_redirected($post)) {
1668 + return false;
1498 1669 }
1499 1670
1500 1671 return true;
1501 1672 }
@@ -1534,35 +1705,8 @@
1534 1705 return $ids;
1535 1706 }
1536 1707
1537 1708 /**
1538 - * Whether a term carries an explicit noindex override.
1539 - *
1540 - * Mirrors the post-side check in should_include_post(); terms store the same
1541 - * `_thinkrank_robots_meta_enabled` / `_thinkrank_robots_meta` keys, written
1542 - * by the update-term-seo ability and by the SEO importer.
1543 - *
1544 - * @since 1.31.0
1545 - *
1546 - * @param int $term_id Term to test.
1547 - * @return bool True when the term is marked noindex.
1548 - */
1549 - private function term_is_noindexed(int $term_id): bool {
1550 - if (!(bool) get_term_meta($term_id, '_thinkrank_robots_meta_enabled', true)) {
1551 - return false;
1552 - }
1553 -
1554 - $raw = get_term_meta($term_id, '_thinkrank_robots_meta', true);
1555 - if (!is_string($raw) || $raw === '') {
1556 - return false;
1557 - }
1558 -
1559 - $robots = json_decode($raw, true);
1560 -
1561 - return is_array($robots) && !empty($robots['noindex']);
1562 - }
1563 -
1564 - /**
1565 1709 * Count total URLs in sitemap
1566 1710 *
1567 1711 * @since 1.0.0
1568 1712 *
@@ -1854,11 +1998,13 @@
1854 1998 $since = !empty($pending['since']) ? (int) $pending['since'] : time();
1855 1999 $current = isset($pending['source']) ? (string) $pending['source'] : '';
1856 2000 $source = ($current === 'settings' || $source === 'settings') ? 'settings' : 'content';
1857 2001
2002 + // Merged so the bookkeeping a rebuild keeps on the marker (`started`,
2003 + // `memory_limit`) survives an edit made while it is outstanding.
1858 2004 update_option(
1859 2005 self::REGENERATION_PENDING_OPTION,
1860 - [
2006 + array_merge($pending, [
1861 2007 'since' => $since,
1862 2008 'source' => $source,
1863 2009 'attempts' => !empty($pending['attempts']) ? (int) $pending['attempts'] : 0,
1864 2010 'next_attempt' => !empty($pending['next_attempt'])
@@ -1866,9 +2012,9 @@
1866 2012 : time() + self::REGENERATION_TAKEOVER_GRACE,
1867 2013 // Bumped on every change so a rebuild can tell whether the edit
1868 2014 // it started for is still the newest one outstanding.
1869 2015 'revision' => (!empty($pending['revision']) ? (int) $pending['revision'] : 0) + 1,
1870 - ],
2016 + ]),
1871 2017 true
1872 2018 );
1873 2019 }
1874 2020
@@ -1914,8 +2060,18 @@
1914 2060 $revision !== null
1915 2061 && is_array($pending)
1916 2062 && (int) ($pending['revision'] ?? 0) !== $revision
1917 2063 ) {
2064 + // This attempt succeeded, so drop what it claimed: the newer change
2065 + // waits the grace a fresh edit gets, not a failure backoff it never
2066 + // earned. Not zero: that edit queued its own debounced event, and
2067 + // a marker due at once had the next admin request rebuild in its
2068 + // shutdown and the event rebuild again seconds later.
2069 + unset($pending['started'], $pending['memory_limit']);
2070 + $pending['attempts'] = 0;
2071 + $pending['next_attempt'] = time() + self::REGENERATION_TAKEOVER_GRACE;
2072 +
2073 + update_option(self::REGENERATION_PENDING_OPTION, $pending, true);
1918 2074 return;
1919 2075 }
1920 2076
1921 2077 delete_option(self::REGENERATION_PENDING_OPTION);
@@ -1921,8 +2077,69 @@
1921 2077 delete_option(self::REGENERATION_PENDING_OPTION);
1922 2078 }
1923 2079
1924 2080 /**
2081 + * Record the attempt that is about to run before it runs.
2082 + *
2083 + * A PHP fatal — the memory limit or max_execution_time — is not a
2084 + * Throwable, so no catch or finally around the generation runs when the
2085 + * process dies, and a failure recorded afterwards was never recorded at
2086 + * all: `attempts` stayed 0, the backoff never applied, and the next request
2087 + * started the same doomed rebuild again (a fatal every few minutes for as
2088 + * long as an admin was logged in). Claiming the attempt up front makes the
2089 + * backoff hold even when nothing after this line gets to run, and leaves a
2090 + * `started` stamp the next attempt can recognise as an interrupted one.
2091 + *
2092 + * @since 2.10.1
2093 + * @return void
2094 + */
2095 + private function claim_regeneration_attempt(): void {
2096 + $pending = get_option(self::REGENERATION_PENDING_OPTION, null);
2097 +
2098 + // Nothing outstanding (e.g. a manual generation already satisfied it):
2099 + // there is no marker to retry from, so nothing to claim.
2100 + if (!is_array($pending) || empty($pending['since'])) {
2101 + return;
2102 + }
2103 +
2104 + if (!empty($pending['started'])) {
2105 + // The previous attempt claimed itself and never reported back.
2106 + update_option(
2107 + self::REGENERATION_ERROR_OPTION,
2108 + [
2109 + 'message' => __('The previous automatic sitemap rebuild stopped before it finished, most likely because PHP ran out of memory or time. It is retried with a growing delay. If this keeps happening, raise the PHP memory_limit or max_execution_time, or run WP-Cron from a system cron.', 'thinkrank'),
2110 + 'source' => isset($pending['source']) ? (string) $pending['source'] : 'content',
2111 + 'attempts' => !empty($pending['attempts']) ? (int) $pending['attempts'] : 1,
2112 + 'time' => (int) $pending['started'],
2113 + ],
2114 + false
2115 + );
2116 + }
2117 +
2118 + $attempts = (!empty($pending['attempts']) ? (int) $pending['attempts'] : 0) + 1;
2119 +
2120 + $pending['attempts'] = $attempts;
2121 + $pending['next_attempt'] = time() + $this->regeneration_backoff($attempts);
2122 + $pending['started'] = time();
2123 +
2124 + update_option(self::REGENERATION_PENDING_OPTION, $pending, true);
2125 + }
2126 +
2127 + /**
2128 + * Delay before the next takeover after the given number of attempts.
2129 + *
2130 + * @since 2.10.1
2131 + * @param int $attempts Attempts made so far (1 or more).
2132 + * @return int Seconds.
2133 + */
2134 + private function regeneration_backoff(int $attempts): int {
2135 + return (int) min(
2136 + self::REGENERATION_TAKEOVER_GRACE * (2 ** min(max($attempts, 1), 10)),
2137 + self::REGENERATION_MAX_BACKOFF
2138 + );
2139 + }
2140 +
2141 + /**
1925 2142 * Record a failed regeneration instead of discarding it.
1926 2143 *
1927 2144 * Keeps the pending marker in place so the rebuild is retried, but backs the
1928 2145 * next attempt off exponentially (capped) so a persistently failing
@@ -1928,22 +2145,30 @@
1928 2145 * next attempt off exponentially (capped) so a persistently failing
1929 2146 * generation cannot run on every admin request.
1930 2147 *
1931 2148 * @since 2.2.1
1932 - * @param string $message Failure detail.
1933 - * @param string $source Either 'content' or 'settings'.
2149 + * @since 2.10.1 Accepts the memory limit a rebuild had to stop short of, and
2150 + * does not count an attempt claim_regeneration_attempt()
2151 + * already counted.
2152 + * @param string $message Failure detail.
2153 + * @param string $source Either 'content' or 'settings'.
2154 + * @param int|null $memory_limit Memory limit (bytes) the rebuild stopped
2155 + * short of, when that was the failure.
1934 2156 * @return void
1935 2157 */
1936 - private function record_regeneration_failure(string $message, string $source): void {
2158 + private function record_regeneration_failure(string $message, string $source, ?int $memory_limit = null): void {
1937 2159 $pending = get_option(self::REGENERATION_PENDING_OPTION, []);
1938 2160 $pending = is_array($pending) ? $pending : [];
1939 - $attempts = (!empty($pending['attempts']) ? (int) $pending['attempts'] : 0) + 1;
2161 + $attempts = !empty($pending['attempts']) ? (int) $pending['attempts'] : 0;
1940 2162
1941 - $backoff = min(
1942 - self::REGENERATION_TAKEOVER_GRACE * (2 ** min($attempts, 10)),
1943 - self::REGENERATION_MAX_BACKOFF
1944 - );
2163 + // An attempt that claimed itself up front has already been counted.
2164 + if (empty($pending['started'])) {
2165 + $attempts++;
2166 + }
2167 + $attempts = max($attempts, 1);
1945 2168
2169 + $backoff = $this->regeneration_backoff($attempts);
2170 +
1946 2171 // Same precedence mark_regeneration_pending() enforces: a settings
1947 2172 // rebuild outranks a content one and must not be downgraded by a failed
1948 2173 // attempt. Overwriting it routed the retry back through the content
1949 2174 // path, where should_auto_generate() can be false and the completion
@@ -1952,20 +2177,24 @@
1952 2177 // whichever attempt actually failed.
1953 2178 $current = isset($pending['source']) ? (string) $pending['source'] : '';
1954 2179 $pending_source = ($current === 'settings' || $source === 'settings') ? 'settings' : 'content';
1955 2180
1956 - update_option(
1957 - self::REGENERATION_PENDING_OPTION,
1958 - [
1959 - 'since' => !empty($pending['since']) ? (int) $pending['since'] : time(),
1960 - 'source' => $pending_source,
1961 - 'attempts' => $attempts,
1962 - 'next_attempt' => time() + $backoff,
1963 - 'revision' => !empty($pending['revision']) ? (int) $pending['revision'] : 0,
1964 - ],
1965 - true
1966 - );
2181 + $marker = [
2182 + 'since' => !empty($pending['since']) ? (int) $pending['since'] : time(),
2183 + 'source' => $pending_source,
2184 + 'attempts' => $attempts,
2185 + 'next_attempt' => time() + $backoff,
2186 + 'revision' => !empty($pending['revision']) ? (int) $pending['revision'] : 0,
2187 + ];
1967 2188
2189 + // Remembered so has_memory_for_retry() can keep requests with no more
2190 + // memory than this from repeating the same attempt.
2191 + if ($memory_limit !== null && $memory_limit > 0) {
2192 + $marker['memory_limit'] = $memory_limit;
2193 + }
2194 +
2195 + update_option(self::REGENERATION_PENDING_OPTION, $marker, true);
2196 +
1968 2197 update_option(
1969 2198 self::REGENERATION_ERROR_OPTION,
1970 2199 [
1971 2200 'message' => $message,
@@ -2020,16 +2249,34 @@
2020 2249 if (!self::has_overdue_regeneration()) {
2021 2250 return;
2022 2251 }
2023 2252
2024 - // Cron is running: it is about to do exactly this work.
2253 + $pending = get_option(self::REGENERATION_PENDING_OPTION, []);
2254 + $pending = is_array($pending) ? $pending : [];
2255 + $source = isset($pending['source']) ? (string) $pending['source'] : 'content';
2256 +
2257 + // Cron is running and its own event for this rebuild is still queued
2258 + // and due: it is about to do exactly this work. Only then — an event
2259 + // that has already been consumed (e.g. it fired while another process
2260 + // held the generation lock) is never re-queued, and returning here
2261 + // unconditionally left the rebuild to requests that could not finish it.
2025 2262 if (wp_doing_cron()) {
2263 + $hook = $source === 'settings' ? 'thinkrank_regenerate_sitemap_settings' : 'thinkrank_regenerate_sitemap';
2264 + $next = wp_next_scheduled($hook);
2265 +
2266 + if ($next !== false && $next <= time()) {
2267 + return;
2268 + }
2269 + }
2270 +
2271 + // The last attempt had to stop short of this process's memory limit.
2272 + // Retrying at the same (or a lower) limit only repeats that, so leave
2273 + // the rebuild to a process with more room — WP-CLI, a system cron, or a
2274 + // host with a higher limit — instead of burning it on every request.
2275 + if (!$this->has_memory_for_retry($pending)) {
2026 2276 return;
2027 2277 }
2028 2278
2029 - $pending = get_option(self::REGENERATION_PENDING_OPTION, []);
2030 - $source = (is_array($pending) && isset($pending['source'])) ? (string) $pending['source'] : 'content';
2031 -
2032 2279 if ($source === 'settings') {
2033 2280 $this->regenerate_sitemap_from_settings();
2034 2281 return;
2035 2282 }
@@ -2063,8 +2310,228 @@
2063 2310 delete_transient(self::GENERATION_LOCK_TRANSIENT);
2064 2311 }
2065 2312
2066 2313 /**
2314 + * This process's PHP memory limit in bytes.
2315 + *
2316 + * @since 2.10.1
2317 + * @return int Bytes, or -1 when unlimited (or unreadable).
2318 + */
2319 + private function current_memory_limit(): int {
2320 + $limit = (string) ini_get('memory_limit');
2321 +
2322 + if ($limit === '' || $limit === '-1') {
2323 + return -1;
2324 + }
2325 +
2326 + $bytes = (int) wp_convert_hr_to_bytes($limit);
2327 +
2328 + return $bytes > 0 ? $bytes : -1;
2329 + }
2330 +
2331 + /**
2332 + * May this process retry a rebuild that last stopped at the memory limit?
2333 + *
2334 + * Raises the limit the way wp-admin does first, so a request that can get
2335 + * more room than the failed attempt had is still allowed to try.
2336 + *
2337 + * @since 2.10.1
2338 + * @param array $pending The pending marker.
2339 + * @return bool True when there is no recorded memory failure, or this
2340 + * process has more memory than the attempt that failed.
2341 + */
2342 + private function has_memory_for_retry(array $pending): bool {
2343 + if (empty($pending['memory_limit'])) {
2344 + return true;
2345 + }
2346 +
2347 + wp_raise_memory_limit('admin');
2348 +
2349 + $limit = $this->current_memory_limit();
2350 +
2351 + return $limit === -1 || $limit > (int) $pending['memory_limit'];
2352 + }
2353 +
2354 + /**
2355 + * Release what one walked chunk left behind.
2356 + *
2357 + * Hydrating a chunk through get_posts()/get_terms() also stores every
2358 + * object and its meta in the in-process object cache, which nothing
2359 + * empties until the request ends. Unsetting the chunk therefore freed
2360 + * nothing, and the walk grew with the size of the site instead of the size
2361 + * of a chunk — about 1.3 GB on a 45k-post site.
2362 + *
2363 + * A persistent object cache that supports it drops only its in-process
2364 + * copy (`flush_runtime`); the shared store keeps its data. WordPress's
2365 + * default cache has no shared store, and flushing it would empty every
2366 + * group for the rest of the request (options, the queried object, other
2367 + * plugins' data), so there only the chunk's own entries are deleted. A
2368 + * persistent cache without `flush_runtime` is left alone: deleting from it
2369 + * would evict the objects for every other request too.
2370 + *
2371 + * @since 2.10.1
2372 + * @param int $chunk_start memory_get_usage(true) before the chunk was hydrated.
2373 + * @param array $groups Cache groups keyed by the chunk's object IDs.
2374 + * @param int[] $ids The chunk's object IDs, plus any objects it
2375 + * hydrated under their own (featured images).
2376 + * @return void
2377 + * @throws \Error See assert_memory_headroom().
2378 + */
2379 + private function release_walk_memory(int $chunk_start, array $groups, array $ids): void {
2380 + // What one chunk costs before it is released: the margin the next one
2381 + // needs. Measured in the same real allocated size assert_memory_headroom()
2382 + // compares against the limit, so the two are the same unit.
2383 + $this->walk_chunk_cost = max($this->walk_chunk_cost, memory_get_usage(true) - $chunk_start);
2384 +
2385 + if (wp_using_ext_object_cache()) {
2386 + if (
2387 + function_exists('wp_cache_supports')
2388 + && wp_cache_supports('flush_runtime')
2389 + && function_exists('wp_cache_flush_runtime')
2390 + ) {
2391 + wp_cache_flush_runtime();
2392 + }
2393 + } elseif (!empty($ids)) {
2394 + foreach ($groups as $group) {
2395 + wp_cache_delete_multiple($ids, $group);
2396 + }
2397 + }
2398 +
2399 + $this->assert_memory_headroom();
2400 + }
2401 +
2402 + /**
2403 + * Cache groups get_posts() fills per post for the given post types.
2404 + *
2405 + * The post, its meta, and one relationships group per taxonomy the post
2406 + * type uses (update_object_term_cache()). Term objects themselves are
2407 + * bounded by the number of terms, not posts, so they are left cached.
2408 + *
2409 + * @since 2.10.1
2410 + * @param string[] $post_types Post types being walked.
2411 + * @return string[] Cache groups keyed by post ID.
2412 + */
2413 + private function chunk_post_cache_groups(array $post_types): array {
2414 + $groups = ['posts', 'post_meta'];
2415 +
2416 + foreach (get_object_taxonomies($post_types) as $taxonomy) {
2417 + $groups[] = $taxonomy . '_relationships';
2418 + }
2419 +
2420 + return array_values(array_unique($groups));
2421 + }
2422 +
2423 + /**
2424 + * Stop an automatic rebuild before the memory limit rather than at it.
2425 + *
2426 + * A PHP memory fatal skips every catch and finally, so the lock, the
2427 + * failure record and the backoff are all lost with it, while stopping here
2428 + * is an ordinary, fully recorded failure. Checked before each chunk is
2429 + * hydrated, against a margin of at least the largest chunk seen so far.
2430 + *
2431 + * It throws an \Error, not an \Exception, on purpose: the per-segment
2432 + * catch (\Exception) blocks in generate_multiple_sitemaps() would otherwise
2433 + * swallow it and carry on — writing an index without the aborted segments
2434 + * and then pruning their files as orphans. Only the automatic rebuild's
2435 + * catch (\Throwable) is meant to see it.
2436 + *
2437 + * @since 2.10.1
2438 + * @return void
2439 + * @throws \Error When the automatic rebuild is close to the memory limit.
2440 + */
2441 + private function assert_memory_headroom(): void {
2442 + if (!$this->memory_guard) {
2443 + return;
2444 + }
2445 +
2446 + $limit = $this->current_memory_limit();
2447 + if ($limit === -1) {
2448 + return;
2449 + }
2450 +
2451 + // A fifth of the limit (at least 32 MB) for writing the files, or one
2452 + // and a half of the costliest chunk if that is more — and never more
2453 + // than half the limit either way. Without that outer cap a single
2454 + // anomalously expensive chunk (500 posts of serialised page-builder or
2455 + // ACF meta reaches hundreds of megabytes) puts the margin above the
2456 + // limit itself, so every later check aborts at any usage at all, the
2457 + // failure records this process's limit, and has_memory_for_retry()
2458 + // then refuses every process that has the same limit. A site that
2459 + // never actually ran out of memory would stop rebuilding until WP-CLI
2460 + // or a system cron happened to run.
2461 + $headroom = (int) min(
2462 + max(
2463 + min(max($limit * 0.2, 32 * MB_IN_BYTES), $limit * 0.5),
2464 + $this->walk_chunk_cost * 1.5
2465 + ),
2466 + $limit * 0.5
2467 + );
2468 +
2469 + // The real allocated size, which is what PHP enforces memory_limit
2470 + // against; memory_get_usage(false) reports only what is handed out of
2471 + // those allocations and so understates the margin by the allocator's
2472 + // slack.
2473 + $usage = memory_get_usage(true);
2474 +
2475 + if ($usage > $limit - $headroom) {
2476 + throw new \Error(
2477 + sprintf(
2478 + /* translators: 1: memory in use, 2: PHP memory limit. */
2479 + esc_html__('The sitemap rebuild was stopped at %1$s of the %2$s PHP memory limit, before PHP would have run out of memory. It will be retried by a process with more memory (WP-CLI or a system cron). To let it finish in the admin, raise the PHP memory_limit.', 'thinkrank'),
2480 + esc_html((string) size_format($usage)),
2481 + esc_html((string) size_format($limit))
2482 + ),
2483 + // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- an integer class constant, not output.
2484 + self::MEMORY_ABORT_CODE
2485 + );
2486 + }
2487 + }
2488 +
2489 + /**
2490 + * Run an automatic rebuild's generation with the fatal-safe bookkeeping.
2491 + *
2492 + * @since 2.10.1
2493 + * @param array $settings Sitemap settings.
2494 + * @return bool Whatever generate_and_save() returned.
2495 + * @throws \Throwable Whatever generation throws, after the memory guard is
2496 + * switched back off.
2497 + */
2498 + private function generate_for_regeneration(array $settings): bool {
2499 + // Same headroom wp-admin gives itself; a no-op when the limit is
2500 + // already higher or unlimited.
2501 + wp_raise_memory_limit('admin');
2502 +
2503 + $this->claim_regeneration_attempt();
2504 + $this->memory_guard = true;
2505 + $this->walk_chunk_cost = 0;
2506 +
2507 + try {
2508 + return $this->generate_and_save($settings);
2509 + } finally {
2510 + $this->memory_guard = false;
2511 + }
2512 + }
2513 +
2514 + /**
2515 + * Record a failure thrown by an automatic rebuild.
2516 + *
2517 + * @since 2.10.1
2518 + * @param \Throwable $e What was thrown.
2519 + * @param string $source Either 'content' or 'settings'.
2520 + * @return void
2521 + */
2522 + private function record_thrown_regeneration_failure(\Throwable $e, string $source): void {
2523 + $memory_limit = null;
2524 +
2525 + if ($e instanceof \Error && $e->getCode() === self::MEMORY_ABORT_CODE) {
2526 + $memory_limit = $this->current_memory_limit();
2527 + $memory_limit = $memory_limit > 0 ? $memory_limit : null;
2528 + }
2529 +
2530 + $this->record_regeneration_failure($e->getMessage(), $source, $memory_limit);
2531 + }
2532 +
2533 + /**
2067 2534 * Report how automatic regeneration is faring, for the admin UI.
2068 2535 *
2069 2536 * The feature used to fail invisibly: `last_generated` simply stopped
2070 2537 * advancing and nothing drew attention to it (#629).
@@ -2214,9 +2681,9 @@
2214 2681 // so the switch has not taken effect (#764).
2215 2682 return $this->switch_to_dynamic_delivery($settings, $revision, 'settings');
2216 2683 }
2217 2684
2218 - if ($this->generate_and_save($settings)) {
2685 + if ($this->generate_for_regeneration($settings)) {
2219 2686 $this->mark_regeneration_complete($revision);
2220 2687
2221 2688 return true;
2222 2689 }
@@ -2227,9 +2694,9 @@
2227 2694 );
2228 2695
2229 2696 return false;
2230 2697 } catch (\Throwable $e) {
2231 - $this->record_regeneration_failure($e->getMessage(), 'settings');
2698 + $this->record_thrown_regeneration_failure($e, 'settings');
2232 2699
2233 2700 return false;
2234 2701 } finally {
2235 2702 $this->release_generation_lock();
@@ -2363,9 +2830,9 @@
2363 2830 $this->switch_to_dynamic_delivery($settings, $revision, 'content');
2364 2831 return;
2365 2832 }
2366 2833
2367 - if ($this->generate_and_save($settings)) {
2834 + if ($this->generate_for_regeneration($settings)) {
2368 2835 $this->mark_regeneration_complete($revision);
2369 2836 } else {
2370 2837 // Previously this returned quietly and last_generated simply
2371 2838 // stopped advancing, leaving the site owner with no way to learn
@@ -2375,9 +2842,9 @@
2375 2842 'content'
2376 2843 );
2377 2844 }
2378 2845 } catch (\Throwable $e) {
2379 - $this->record_regeneration_failure($e->getMessage(), 'content');
2846 + $this->record_thrown_regeneration_failure($e, 'content');
2380 2847 } finally {
2381 2848 $this->release_generation_lock();
2382 2849 }
2383 2850 }
@@ -3415,12 +3882,30 @@
3415 3882 $buffer = [];
3416 3883 }
3417 3884 }
3418 3885
3419 - // Flush the trailing partial page, or a single empty page when the
3420 - // type had no entries at all (parity with the previous behavior of
3421 - // always writing at least one page per configured child).
3422 - if (!empty($buffer) || $page === 0) {
3886 + // Flush the trailing partial page.
3887 + //
3888 + // A type that produced nothing writes no page at all in index
3889 + // mode (#836). It used to write one empty urlset and list it in
3890 + // the index, so a crawler was asked to fetch a file that
3891 + // answers with no URLs — Search Console reports an empty
3892 + // sitemap referenced from an index as a warning, and the fetch
3893 + // is wasted on every pass. On this site three of eleven
3894 + // children were empty: a post type with nothing published and
3895 + // two taxonomies with no terms.
3896 + //
3897 + // Single-file mode still writes its one page even when empty,
3898 + // because that file IS the site's /sitemap.xml and a 404 there
3899 + // is worse than an empty urlset. Nothing lists it, so it costs
3900 + // no crawl budget.
3901 + //
3902 + // Skipping the write also keeps the filename out of
3903 + // $results['sitemaps_generated'], which is what
3904 + // prune_orphaned_segments() treats as "written this run" — so
3905 + // a type that empties after previously publishing has its
3906 + // stale file deleted rather than left serving.
3907 + if (!empty($buffer) || ($page === 0 && $index_config === null)) {
3423 3908 $page++;
3424 3909 $this->write_sitemap_page($this->paginate_url($sitemap_config['url'], $page), $this->wrap_urlset($buffer, $settings, $image_ns), $type, count($buffer), $results, $index_children);
3425 3910 }
3426 3911