PluginProbe
Search Atlas SEO – OTTO AI SEO Automation for WordPress / 2.7.0
Search Atlas SEO – OTTO AI SEO Automation for WordPress v2.7.0
2.7.1 2.7.2 2.7.0 2.6.26 2.6.25 2.6.24 2.6.23 2.6.22 2.6.21 2.6.20 2.6.19 2.6.18 2.6.17 2.6.16 2.6.15 2.6.14 2.6.13 2.6.12 2.6.11 2.6.10 2.6.9 2.6.8 2.6.7 2.6.6 2.6.5 All 141 releases
metasync / includes / metasync-helpers.php

metasync-helpers.php in Search Atlas SEO – OTTO AI SEO Automation for WordPress 2.7.0, at includes/metasync-helpers.php

495 lines 19.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Shared MetaSync helper functions.
4 *
5 * Always loaded (in all request contexts: admin, REST, MCP, AJAX) so that the
6 * custom/LPS page detection rule lives in exactly one place and every SEO
7 * surface applies the same exclusion without copy-paste drift.
8 *
9 * @package Search_Atlas
10 */
11
12 if (!defined('ABSPATH')) {
13 exit;
14 }
15
16 if (!function_exists('metasync_is_custom_or_lps_page')) {
17 /**
18 * Determine whether a post is a MetaSync-built custom page that ships its own
19 * complete, self-contained SEO (Custom HTML pages and LPS-imported pages).
20 *
21 * These pages already include a full SEO head (title, meta description, OG,
22 * Twitter, JSON-LD schema) generated by LPS, so OTTO must not run on them —
23 * otherwise it injects/overwrites SEO from a different/older OTTO project and
24 * produces a page with two contradictory SEO identities.
25 *
26 * @param int $post_id Post ID to inspect.
27 * @return bool True when the post carries any custom-page / LPS marker.
28 */
29 function metasync_is_custom_or_lps_page($post_id){
30 $post_id = (int) $post_id;
31 if ($post_id <= 0 || !class_exists('Metasync_Custom_Pages')) {
32 return false;
33 }
34
35 if (get_post_meta($post_id, Metasync_Custom_Pages::META_IS_CUSTOM_HTML_PAGE, true) === '1') {
36 return true;
37 }
38 if (!empty(get_post_meta($post_id, Metasync_Custom_Pages::META_LPS_IMPORT, true))) {
39 return true;
40 }
41 if (!empty(get_post_meta($post_id, Metasync_Custom_Pages::META_CREATED_VIA_API, true))) {
42 return true;
43 }
44
45 return false;
46 }
47 }
48
49 if (!function_exists('metasync_is_scrape_request')) {
50 /**
51 * Detect WordPress core's internal file-editor "scrape" self-check request.
52 *
53 * When an admin saves a file in the Plugin/Theme Editor, WP core
54 * (wp_edit_theme_plugin_file()) fires a loopback request carrying
55 * wp_scrape_key + wp_scrape_nonce to detect whether the edit white-screened
56 * the site. For a THEME edit that loopback targets home_url('/') — a
57 * front-end GET that is NOT is_admin() — so it slips past OTTO's admin/AJAX/
58 * REST guards in metasync_start_otto(). OTTO must never buffer/rewrite it:
59 * the SimpleHtmlDom rewrite, and any fatal thrown inside the
60 * ob_start() display handler, corrupt the scrape and surface as the
61 * misleading "preg_match(): Cannot use output buffering in output buffering
62 * display handlers" error.
63 *
64 * @return bool True when the current request is a WP core scrape self-check.
65 */
66 function metasync_is_scrape_request(){
67 return isset($_GET['wp_scrape_key']) || isset($_GET['wp_scrape_nonce']);
68 }
69 }
70
71 if (!function_exists('metasync_get_custom_page_exclusion_meta_query')) {
72 /**
73 * Build a WP_Query meta_query fragment that excludes custom/LPS pages.
74 *
75 * Mirrors the sibling predicate metasync_is_custom_or_lps_page(): a post is
76 * excluded when ANY of the three markers is set — _metasync_is_custom_html_page
77 * = '1', or a non-empty _metasync_lps_import / _metasync_created_via_api.
78 * Checking only the first marker let LPS placeholder pages leak into SEO
79 * audits as real pages.
80 *
81 * @return array meta_query fragment.
82 */
83 function metasync_get_custom_page_exclusion_meta_query(){
84 return array(
85 'relation' => 'AND',
86 array(
87 'relation' => 'OR',
88 array(
89 'key' => '_metasync_is_custom_html_page',
90 'compare' => 'NOT EXISTS',
91 ),
92 array(
93 'key' => '_metasync_is_custom_html_page',
94 'value' => '1',
95 'compare' => '!=',
96 ),
97 ),
98 array(
99 'relation' => 'OR',
100 array(
101 'key' => '_metasync_lps_import',
102 'compare' => 'NOT EXISTS',
103 ),
104 // IN ('', '0') mirrors empty() semantics for stored strings.
105 array(
106 'key' => '_metasync_lps_import',
107 'value' => array('', '0'),
108 'compare' => 'IN',
109 ),
110 ),
111 array(
112 'relation' => 'OR',
113 array(
114 'key' => '_metasync_created_via_api',
115 'compare' => 'NOT EXISTS',
116 ),
117 array(
118 'key' => '_metasync_created_via_api',
119 'value' => array('', '0'),
120 'compare' => 'IN',
121 ),
122 ),
123 );
124 }
125 }
126
127 if (!function_exists('metasync_get_custom_page_exclusion_where_sql')) {
128 /**
129 * Build a prepared SQL WHERE fragment that excludes custom/LPS pages.
130 *
131 * Produces three AND-ed NOT EXISTS correlated anti-joins against wp_postmeta.
132 * Unlike WP core's meta_query translation (which generates unanchored
133 * post_id-only LEFT JOINs multiplied across meta rows), this WHERE clause
134 * checks only the 3 specific marker keys and avoids joining postmeta.
135 *
136 * Semantics match metasync_is_custom_or_lps_page() and
137 * metasync_get_custom_page_exclusion_meta_query() exactly:
138 * - Excluded if _metasync_is_custom_html_page = '1'
139 * - Excluded if _metasync_lps_import NOT IN ('', '0')
140 * - Excluded if _metasync_created_via_api NOT IN ('', '0')
141 *
142 * @return string Prepared SQL fragment starting with ' AND ...'
143 */
144 function metasync_get_custom_page_exclusion_where_sql() {
145 global $wpdb;
146
147 if (!isset($wpdb) || !is_object($wpdb) || empty($wpdb->postmeta) || empty($wpdb->posts)) {
148 return '';
149 }
150
151 $sql = " AND NOT EXISTS (\n"
152 . "\tSELECT 1 FROM {$wpdb->postmeta} AS _ms_ex_html\n"
153 . "\tWHERE _ms_ex_html.post_id = {$wpdb->posts}.ID\n"
154 . "\t\tAND _ms_ex_html.meta_key = %s\n"
155 . "\t\tAND _ms_ex_html.meta_value = %s\n"
156 . ")\n"
157 . "AND NOT EXISTS (\n"
158 . "\tSELECT 1 FROM {$wpdb->postmeta} AS _ms_ex_lps\n"
159 . "\tWHERE _ms_ex_lps.post_id = {$wpdb->posts}.ID\n"
160 . "\t\tAND _ms_ex_lps.meta_key = %s\n"
161 . "\t\tAND _ms_ex_lps.meta_value NOT IN ('', '0')\n"
162 . ")\n"
163 . "AND NOT EXISTS (\n"
164 . "\tSELECT 1 FROM {$wpdb->postmeta} AS _ms_ex_api\n"
165 . "\tWHERE _ms_ex_api.post_id = {$wpdb->posts}.ID\n"
166 . "\t\tAND _ms_ex_api.meta_key = %s\n"
167 . "\t\tAND _ms_ex_api.meta_value NOT IN ('', '0')\n"
168 . ")";
169
170 return $wpdb->prepare(
171 $sql,
172 '_metasync_is_custom_html_page',
173 '1',
174 '_metasync_lps_import',
175 '_metasync_created_via_api'
176 );
177 }
178 }
179
180 if (!function_exists('metasync_filter_exclude_custom_pages_where')) {
181 /**
182 * WP_Query posts_where filter callback to exclude custom/LPS pages.
183 *
184 * Checks for the sentinel query variable 'metasync_exclude_custom_pages'.
185 *
186 * @param string $where Existing WHERE clause.
187 * @param WP_Query $query Current query.
188 * @return string Modified WHERE clause.
189 */
190 function metasync_filter_exclude_custom_pages_where($where, $query) {
191 if (empty($query->get('metasync_exclude_custom_pages'))) {
192 return $where;
193 }
194
195 return $where . metasync_get_custom_page_exclusion_where_sql();
196 }
197 }
198
199 if (!function_exists('metasync_get_sitemap_post_type_objects')) {
200 /**
201 * Return the post types that may be selected by a sitemap picker.
202 *
203 * Sitemap settings are shared by the general, news, and video sitemap
204 * screens. Keep their visibility rules in one helper so the three pickers
205 * cannot drift apart when a page builder or WordPress adds an internal
206 * post type.
207 *
208 * @return array<int, WP_Post_Type> Viewable public post type objects.
209 */
210 function metasync_get_sitemap_post_type_objects(): array
211 {
212 $default_excluded_post_types = [
213 'attachment',
214 'revision',
215 'nav_menu_item',
216 'elementor_library',
217 'elementor-hf',
218 'e-floating-buttons',
219 'bricks_template',
220 'ct_template',
221 'oxy_user_library',
222 'brizy-template',
223 'fusion_template',
224 'fusion_tb_section',
225 'ae_global_templates',
226 'custom_css',
227 'customize_changeset',
228 'oembed_cache',
229 'user_request',
230 'wp_block',
231 'wp_template',
232 'wp_template_part',
233 'wp_global_styles',
234 'wp_navigation',
235 'acf-field-group',
236 'acf-field',
237 'fl-builder-template',
238 'fl-theme-layout',
239 'wpr_mega_menu',
240 'wpr_templates',
241 ];
242
243 /**
244 * Allow integrations to remove additional internal post types from
245 * all sitemap post-type pickers.
246 *
247 * @param string[] $excluded_post_types Post type slugs to exclude.
248 */
249 /** @var mixed $filtered_excluded_post_types */
250 $filtered_excluded_post_types = apply_filters(
251 'metasync_sitemap_excluded_post_types',
252 $default_excluded_post_types
253 );
254 $excluded_post_types = is_array($filtered_excluded_post_types)
255 ? $filtered_excluded_post_types
256 : $default_excluded_post_types;
257
258 /**
259 * Allow integrations and tests to adjust the public post-type objects
260 * before the common exclusion and viewability rules are applied.
261 *
262 * @param array<string, WP_Post_Type> $post_types Public post types.
263 */
264 /** @var mixed $filtered_post_types */
265 $filtered_post_types = apply_filters(
266 'metasync_sitemap_post_types',
267 get_post_types(['public' => true], 'objects')
268 );
269 $post_types = is_array($filtered_post_types) ? $filtered_post_types : [];
270 $filtered = [];
271 foreach ($post_types as $post_type) {
272 if (!is_object($post_type) || empty($post_type->name)) {
273 continue;
274 }
275 if (in_array($post_type->name, $excluded_post_types, true)) {
276 continue;
277 }
278 if (!is_post_type_viewable($post_type)) {
279 continue;
280 }
281 $filtered[] = $post_type;
282 }
283
284 return $filtered;
285 }
286 }
287
288 if (!function_exists('metasync_repair_scheme_prefixed_media_id')) {
289 /**
290 * Recover a media-library attachment ID from the corrupted value the legacy
291 * logo sanitizer wrote.
292 *
293 * The legacy save path ran the Local Business logo through
294 * sanitize_url() (= esc_url_raw()), which prepends a scheme to any value
295 * that has none. A stored attachment ID such as "45589" therefore became
296 * "http://45589". That shape is unambiguous — "https?://" followed by
297 * digits only, with no dot and no path, which can never be a resolvable
298 * host — so the digits are exactly the original attachment ID and
299 * recovering them is mechanically safe.
300 *
301 * Values that are not of that shape are returned untouched, so this is
302 * safe to call on every read of a media setting: a real URL (which always
303 * carries a dot in its host) and a plain attachment ID both pass through.
304 *
305 * Used by the schema output, the admin preview, and the one-time database
306 * repair migration, so all three can never disagree.
307 *
308 * @param mixed $value Stored media setting (attachment ID, URL, or corrupted value).
309 * @return string|int The attachment ID when $value was corrupted, $value otherwise.
310 */
311 function metasync_repair_scheme_prefixed_media_id($value){
312 if (is_numeric($value) || !is_string($value)) {
313 return $value;
314 }
315
316 if (!preg_match('/^https?:\/\/(\d+)\/?$/i', trim($value), $matches)) {
317 return $value;
318 }
319
320 return (int) $matches[1];
321 }
322 }
323
324 if (!function_exists('metasync_discard_buffered_output')) {
325 /**
326 * Discard any pending output buffers before emitting a machine-readable body.
327 *
328 * Endpoints that serve XML/plain text (sitemaps, llms.txt, the IndexNow key
329 * file) must start at the very first byte of the response. When another
330 * plugin emits output earlier in the request — most commonly a PHP
331 * Deprecated/Notice/Warning rendered as HTML because display_errors or
332 * WP_DEBUG_DISPLAY is on — that text sits in the output buffer and gets
333 * flushed ahead of the `<?xml` declaration, making the response invalid and
334 * causing crawlers to reject the whole document.
335 *
336 * Call immediately before the header()/echo pair. On a healthy request there
337 * is nothing buffered and this is a no-op.
338 *
339 * @return bool True when the output is guaranteed clean; false when stray
340 * bytes could not be discarded (see the two cases below).
341 */
342 function metasync_discard_buffered_output(){
343 // Headers already sent means the buffer was flushed to the client, so the
344 // stray bytes are on the wire and cannot be recalled. Discarding buffers
345 // now would only drop legitimate content.
346 if (headers_sent()) {
347 return false;
348 }
349
350 while (ob_get_level() > 0) {
351 $status = ob_get_status();
352 $flags = isset($status['flags']) ? (int) $status['flags'] : 0;
353 $needed = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
354
355 // Some buffers cannot be discarded at all — zlib.output_compression
356 // and handlers started without the cleanable/removable flags. Check
357 // first, because calling ob_end_clean() on one emits a PHP notice,
358 // which would add to the very corruption this guards against.
359 if (($flags & $needed) !== $needed) {
360 return false;
361 }
362
363 $level_before = ob_get_level();
364 ob_end_clean();
365
366 // Only keep going while the level is actually falling. Looping on
367 // ob_get_level() alone would spin forever against a buffer that
368 // refuses to close.
369 if (ob_get_level() >= $level_before) {
370 return false;
371 }
372 }
373
374 return true;
375 }
376 }
377
378 if (!function_exists('metasync_escape_json_ld_for_script')) {
379 /**
380 * Escape a JSON document string for safe embedding inside a
381 * `<script type="application/ld+json">` element.
382 *
383 * A JSON-LD block lives inside the HTML document, so a string value that
384 * contains the literal `</script>` (or any `</` that could grow into one)
385 * would let the browser close the script element early and parse the rest
386 * of the payload as page markup (XSS / page corruption). JSON itself has
387 * no closing-tag concept, so the sequence is neutralised by replacing every
388 * `</` with `<\/` — `\/` is a valid JSON escape for `/`, so any
389 * spec-compliant JSON consumer (Google, validators, OTTO) decodes the value
390 * back to identical content.
391 *
392 * @param string $json An already-encoded JSON document.
393 * @return string The escaped JSON, safe to echo inside a script element.
394 */
395 function metasync_escape_json_ld_for_script($json){
396 return str_replace('</', '<\/', (string) $json);
397 }
398 }
399
400 if (!function_exists('metasync_safe_json_ld_encode')) {
401 /**
402 * Encode a JSON-LD document so it is safe to embed inside a
403 * `<script type="application/ld+json">` element.
404 *
405 * Encodes with wp_json_encode() using the caller's flags, then applies
406 * metasync_escape_json_ld_for_script() so a literal `</script>` inside any
407 * string value cannot break out of the surrounding script block. When no
408 * `</` is present the output is byte-identical to wp_json_encode().
409 *
410 * @param mixed $data The JSON-LD document to encode.
411 * @param int $flags json_encode bitmask, e.g. JSON_UNESCAPED_SLASHES.
412 * @return string|false The safely-encoded JSON, or false on encode failure
413 * (mirrors wp_json_encode semantics).
414 */
415 function metasync_safe_json_ld_encode($data, $flags = JSON_UNESCAPED_SLASHES){
416 $json = wp_json_encode($data, $flags);
417
418 if (!is_string($json)) {
419 return $json;
420 }
421
422 return metasync_escape_json_ld_for_script($json);
423 }
424 }
425
426 if (!function_exists('metasync_escape_json_ld_blocks_in_html')) {
427 /**
428 * Escape every JSON-LD script block inside an HTML fragment.
429 *
430 * Remote HTML fragments (e.g. OTTO's header insertion) arrive as assembled
431 * markup, so a JSON string value that contains a literal `</script>` cannot
432 * be fixed with a naive non-greedy `<script>...</script>` match — the match
433 * would stop at the injected closer and leave the payload live. Instead,
434 * for each `application/ld+json` opening tag the content is extended past
435 * successive closing tags until it parses as valid JSON: that is the span
436 * the producer meant to be script content, so every `</` inside it is
437 * neutralised as `<\/` (a valid JSON escape decoding to the same value).
438 *
439 * Blocks whose content never parses as JSON are left untouched rather than
440 * guessing at their extent. Non-JSON-LD script tags are never modified.
441 *
442 * @param string $html HTML fragment possibly containing JSON-LD blocks.
443 * @return string Fragment with JSON-LD payload closers escaped.
444 */
445 function metasync_escape_json_ld_blocks_in_html($html){
446 $html = (string) $html;
447 if (stripos($html, 'application/ld+json') === false) {
448 return $html;
449 }
450
451 preg_match_all('/<script\b[^>]*application\/ld\+json[^>]*>/i', $html, $opens, PREG_OFFSET_CAPTURE);
452 if (empty($opens[0])) {
453 return $html;
454 }
455 if (!preg_match_all('/<\/script\s*>/i', $html, $closers, PREG_OFFSET_CAPTURE)) {
456 return $html;
457 }
458
459 $result = $html;
460 $processed_from = PHP_INT_MAX;
461
462 // Right to left, so escaping a block never invalidates the offsets of
463 // the blocks still to be processed.
464 for ($i = count($opens[0]) - 1; $i >= 0; $i--) {
465 $open = $opens[0][$i];
466 $content_start = $open[1] + strlen($open[0]);
467 if ($open[1] >= $processed_from) {
468 continue; // already inside an escaped span
469 }
470
471 foreach ($closers[0] as $closer) {
472 $end = $closer[1];
473 if ($end <= $content_start) {
474 continue;
475 }
476
477 $candidate = substr($html, $content_start, $end - $content_start);
478 json_decode($candidate);
479 if (json_last_error() !== JSON_ERROR_NONE) {
480 continue; // keep extending to the next closing tag
481 }
482
483 $escaped = str_replace('</', '<\/', $candidate);
484 if ($escaped !== $candidate) {
485 $result = substr_replace($result, $escaped, $content_start, $end - $content_start);
486 }
487 $processed_from = min($processed_from, $content_start);
488 break;
489 }
490 }
491
492 return $result;
493 }
494 }
495