PluginProbe
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot / 4.9.4
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot v4.9.4
4.9.4 4.9.3 4.9.2 4.9.1 4.9.0 4.8.2 4.8.1 4.8.0 4.7.0 4.6.2 4.6.1 4.6.0 4.5.6 4.5.5 4.5.4 4.5.3 4.5.2 4.5.1 4.5.0 4.4.1 4.4.0 3.3.4 3.4.0 3.4.1 3.4.2 All 202 releases
← All changes | includes/Core/Request.php +379 -5 4.7.0 → 4.9.4 View file →
@@ -6,8 +6,9 @@
6 6 }
7 7
8 8
9 9 use WPDeveloper\BetterDocs\Utils\Base;
10 +use WPDeveloper\BetterDocs\Utils\Helper;
10 11
11 12 class Request extends Base {
12 13 /**
13 14 * Flag for already parsed or not
@@ -151,8 +152,15 @@
151 152 * Hook into template_redirect to validate category-post relationships
152 153 * Priority 0 to run before WordPress canonical redirect (priority 10)
153 154 */
154 155 add_action( 'template_redirect', [ $this, 'validate_single_docs_category_redirect' ], 0 );
156 +
157 + /**
158 + * Hook into template_redirect to 301 non-canonical single doc URLs.
159 + * Priority 5: after the validation above (0) so requests already headed for
160 + * a 404 are left alone, and before WordPress canonical redirect (10).
161 + */
162 + add_action( 'template_redirect', [ $this, 'redirect_to_canonical_docs_url' ], 5 );
155 163 }
156 164
157 165 public function provide_compatibility( $element_id, $uri_parts, $request_url ) {
158 166 if ( $request_url == $this->settings->get( 'docs_slug' ) ) {
@@ -394,8 +402,225 @@
394 402 }
395 403 }
396 404
397 405 /**
406 + * 301 redirect a single doc to its canonical permalink.
407 + *
408 + * With `enable_category_hierarchy_slugs` enabled the single doc rewrite rule
409 + * captures every segment between the base and the doc slug into `doc_category`
410 + * (see Rewrite::rules), and the category validation above only requires ONE of
411 + * those segments to match. That looseness is deliberate — a strict match would
412 + * 404 legitimate Multiple KB and WPML URLs, where the KB slug and translated
413 + * segments share the same capture group — but it also means a doc resolves on an
414 + * unlimited number of URLs, e.g. /docs/anything/real-category/doc-slug/.
415 + *
416 + * Rather than tightening the match, this compares the requested category path
417 + * against every path the doc legitimately has and redirects the rest. Every URL
418 + * that resolves today keeps resolving; only the extra ones collapse.
419 + */
420 + public function redirect_to_canonical_docs_url() {
421 + global $wp_query;
422 +
423 + /**
424 + * Allow the canonical redirect to be disabled.
425 + *
426 + * @param bool $enabled Whether non-canonical single doc URLs should 301.
427 + */
428 + if ( ! apply_filters( 'betterdocs_enable_canonical_redirect', true ) ) {
429 + return;
430 + }
431 +
432 + if ( is_admin() || wp_doing_ajax() || is_feed() || is_embed() || is_preview() || is_customize_preview() ) {
433 + return;
434 + }
435 +
436 + $request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : 'GET';
437 + if ( $request_method !== 'GET' ) {
438 + return;
439 + }
440 +
441 + if ( ! is_singular( 'docs' ) || is_404() ) {
442 + return;
443 + }
444 +
445 + /**
446 + * The request is already headed for a 404 — leave it alone. Note that
447 + * prevent_any_redirect_for_invalid_docs() cancels every wp_redirect() while
448 + * this flag is set, so the redirect below would be swallowed anyway.
449 + */
450 + if ( $this->invalid_request_query_vars !== null ) {
451 + return;
452 + }
453 +
454 + $requested_category = isset( $wp_query->query_vars['doc_category'] ) ? $wp_query->query_vars['doc_category'] : '';
455 + if ( ! is_string( $requested_category ) || $requested_category === '' ) {
456 + return;
457 + }
458 +
459 + $post_id = get_queried_object_id();
460 + if ( ! $post_id ) {
461 + return;
462 + }
463 +
464 + $valid_paths = $this->get_valid_category_paths( $post_id );
465 + if ( empty( $valid_paths ) ) {
466 + return;
467 + }
468 +
469 + $requested_category = urldecode( trim( $requested_category, '/' ) );
470 +
471 + /**
472 + * Under Multiple KB the knowledge base segment is parsed into its own query
473 + * var, so put it back in front of the category chain before comparing —
474 + * otherwise a crossed `/kb-a/category-of-kb-b/doc/` would look canonical.
475 + */
476 + $requested_kb = isset( $wp_query->query_vars['knowledge_base'] ) ? $wp_query->query_vars['knowledge_base'] : '';
477 + if ( is_string( $requested_kb ) && $requested_kb !== '' ) {
478 + $requested_category = urldecode( trim( $requested_kb, '/' ) ) . '/' . $requested_category;
479 + }
480 +
481 + if ( in_array( $requested_category, $valid_paths, true ) ) {
482 + return; // Already canonical (or another legitimate category of this doc).
483 + }
484 +
485 + $canonical = get_permalink( $post_id );
486 + if ( ! $canonical ) {
487 + return;
488 + }
489 +
490 + // Keep the multipage segment the rewrite rule captured.
491 + $page = isset( $wp_query->query_vars['page'] ) ? absint( $wp_query->query_vars['page'] ) : 0;
492 + if ( $page > 1 ) {
493 + $canonical = trailingslashit( $canonical ) . user_trailingslashit( $page, 'single_paged' );
494 + }
495 +
496 + /**
497 + * Belt and braces: never redirect a URL onto itself. The allowed set is built
498 + * from the same term chains get_permalink() uses, so this should be
499 + * unreachable, but a third party filtering the permalink could otherwise turn
500 + * a redirect into a loop.
501 + */
502 + $requested_path = isset( $_SERVER['REQUEST_URI'] ) ? wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
503 + $canonical_path = wp_parse_url( $canonical, PHP_URL_PATH );
504 + if ( untrailingslashit( urldecode( (string) $requested_path ) ) === untrailingslashit( urldecode( (string) $canonical_path ) ) ) {
505 + return;
506 + }
507 +
508 + $query_string = isset( $_SERVER['QUERY_STRING'] ) ? sanitize_text_field( wp_unslash( $_SERVER['QUERY_STRING'] ) ) : '';
509 + if ( $query_string !== '' ) {
510 + $canonical .= ( strpos( $canonical, '?' ) === false ? '?' : '&' ) . $query_string;
511 + }
512 +
513 + if ( wp_safe_redirect( $canonical, 301 ) ) {
514 + exit;
515 + }
516 + }
517 +
518 + /**
519 + * Every category path a doc can legitimately be reached at.
520 + *
521 + * Includes the full parent/child chain of each assigned category, and — because
522 + * the hierarchy rewrite rule folds the knowledge base slug into `doc_category`
523 + * for the `docs/%knowledge_base%/%doc_category%` structure — the KB-prefixed
524 + * variants too.
525 + *
526 + * @param int $post_id The doc id.
527 + * @return string[] Normalised (urldecoded, unslashed) category paths.
528 + */
529 + protected function get_valid_category_paths( $post_id ) {
530 + $cat_terms = wp_get_object_terms( $post_id, 'doc_category' );
531 +
532 + if ( is_wp_error( $cat_terms ) ) {
533 + return [];
534 + }
535 +
536 + $paths = [];
537 + $cat_paths = [];
538 +
539 + if ( empty( $cat_terms ) ) {
540 + $paths[] = 'uncategorized';
541 + } else {
542 + foreach ( $cat_terms as $cat_term ) {
543 + $path = PostType::build_category_path( $cat_term );
544 +
545 + if ( $path !== '' ) {
546 + $paths[] = $path;
547 + $cat_paths[ $cat_term->term_id ] = $path;
548 + }
549 + }
550 + }
551 +
552 + if ( taxonomy_exists( 'knowledge_base' ) ) {
553 + $kb_terms = wp_get_object_terms( $post_id, 'knowledge_base', [ 'fields' => 'slugs' ] );
554 +
555 + if ( ! is_wp_error( $kb_terms ) && ! empty( $kb_terms ) ) {
556 + $kb_paths = [];
557 +
558 + /**
559 + * Read the KB association once per category rather than once per
560 + * KB/category pair. The wp_get_object_terms() call above primes the
561 + * term meta cache for these terms (`update_term_meta_cache` defaults
562 + * to true), so these reads are cache hits and add no queries.
563 + *
564 + * The association mirrors how PostType::post_link() picks the
565 + * category via `doc_category_knowledge_base`. Without it a doc in
566 + * KB A / category A and KB B / category B would treat the crossed
567 + * `/kb-a/category-b/doc/` as canonical. A term with no association
568 + * meta is unassigned rather than KB specific, so it stays valid
569 + * under every KB — post_link() falls back the same way.
570 + */
571 + $term_kbs = [];
572 +
573 + if ( ! empty( $cat_paths ) ) {
574 + foreach ( array_keys( $cat_paths ) as $term_id ) {
575 + $meta = get_term_meta( $term_id, 'doc_category_knowledge_base', true );
576 + $term_kbs[ $term_id ] = ( ! empty( $meta ) && is_array( $meta ) ) ? $meta : null;
577 + }
578 + }
579 +
580 + foreach ( $kb_terms as $kb_slug ) {
581 + if ( empty( $cat_paths ) ) {
582 + // Uncategorised doc: the KB slug is the only prefix there is.
583 + foreach ( $paths as $path ) {
584 + $kb_paths[] = $kb_slug . '/' . $path;
585 + }
586 + continue;
587 + }
588 +
589 + foreach ( $cat_paths as $term_id => $path ) {
590 + if ( $term_kbs[ $term_id ] !== null && ! in_array( $kb_slug, $term_kbs[ $term_id ], true ) ) {
591 + continue;
592 + }
593 +
594 + $kb_paths[] = $kb_slug . '/' . $path;
595 + }
596 + }
597 +
598 + $paths = array_merge( $paths, $kb_paths );
599 + }
600 + }
601 +
602 + /**
603 + * Non-Latin slugs are stored URL encoded while the requested path arrives
604 + * decoded, so normalise both sides before comparing.
605 + */
606 + $paths = array_map(
607 + function ( $path ) {
608 + return urldecode( trim( $path, '/' ) );
609 + },
610 + $paths
611 + );
612 +
613 + /**
614 + * Filter the category paths a doc is allowed to be reached at.
615 + *
616 + * @param string[] $paths Valid category paths.
617 + * @param int $post_id The doc id.
618 + */
619 + return array_values( array_unique( apply_filters( 'betterdocs_valid_docs_category_paths', $paths, $post_id ) ) );
620 + }
621 +
622 + /**
398 623 * Check if a URL matches a BetterDocs single docs permalink structure
399 624 * but has invalid KB/category slugs that don't match the post.
400 625 *
401 626 * @param string $url The URL to check.
@@ -687,8 +912,17 @@
687 912 if ( $this->invalid_request_query_vars !== null ) {
688 913 return;
689 914 }
690 915
916 + // A single-doc request whose main query returned nothing (private or
917 + // draft doc for a visitor who can't read it, a doc in another/inactive
918 + // WPML language) must stay a 404. Marking it singular here would render
919 + // the single template against a null post and expose the doc's title
920 + // through the queried object. See betterdocs/betterdocs#173.
921 + if ( $this->is_singular_docs_request() && ! $this->main_query_has_posts() ) {
922 + return;
923 + }
924 +
691 925 // Check if we have doc_category or knowledge_base in query vars
692 926 if ( isset( $wp_query->query_vars['doc_category'] ) && ! empty( $wp_query->query_vars['doc_category'] ) ) {
693 927 // If this is already identified as singular, don't override it
694 928 if ( $wp_query->is_singular() || $wp_query->is_singular ) {
@@ -723,14 +957,40 @@
723 957
724 958 // Check if we have 'docs' query var (alternative to 'name')
725 959 if ( isset( $wp_query->query_vars['docs'] ) && ! empty( $wp_query->query_vars['docs'] ) ) {
726 960
961 + // Verify the requested doc actually exists (and is visible to the
962 + // current user) before forcing a single-doc render. Category-in-path
963 + // permalinks put the doc slug in the `docs` var alongside a valid
964 + // doc_category; without this guard a missing slug under a real
965 + // category rendered the single template against a null post — an
966 + // HTTP 200 soft-404 plus "read property on null" warnings on every
967 + // (often bot) hit. See betterdocs/betterdocs#169.
968 + $doc_post = get_page_by_path( $wp_query->query_vars['docs'], OBJECT, 'docs' );
969 + $doc_visible = $doc_post
970 + && ( 'private' !== $doc_post->post_status || current_user_can( 'read_private_docs' ) );
971 +
972 + if ( ! $doc_visible ) {
973 + // No such doc (or private and not permitted) — serve a genuine
974 + // 404 instead of a single render against a null post.
975 + $wp_query->set_404();
976 + status_header( 404 );
977 + nocache_headers();
978 + add_filter( 'template_include', function( $template ) {
979 + $not_found = get_404_template();
980 + return $not_found ? $not_found : $template;
981 + }, 999 );
982 + return;
983 + }
984 +
727 985 // Explicitly set this as a single post
728 - $wp_query->is_single = true;
729 - $wp_query->is_singular = true;
730 - $wp_query->is_404 = false;
731 - $wp_query->is_archive = false;
732 - $wp_query->is_tax = false;
986 + $wp_query->is_single = true;
987 + $wp_query->is_singular = true;
988 + $wp_query->is_404 = false;
989 + $wp_query->is_archive = false;
990 + $wp_query->is_tax = false;
991 + $wp_query->queried_object = $doc_post;
992 + $wp_query->queried_object_id = $doc_post->ID;
733 993 return;
734 994 }
735 995
736 996 // If 'name' is set, check if a post with that name exists
@@ -829,8 +1089,16 @@
829 1089 if ( $this->invalid_request_query_vars !== null ) {
830 1090 return $status_header;
831 1091 }
832 1092
1093 + // A single-doc request whose main query returned nothing is a genuine
1094 + // 404 — whatever the slug/term lookups below would find. Checked before
1095 + // both overrides, so neither can turn it into a soft-404 200.
1096 + // See betterdocs/betterdocs#173.
1097 + if ( 404 === (int) $code && $this->is_singular_docs_request() && ! $this->main_query_has_posts() ) {
1098 + return $status_header;
1099 + }
1100 +
833 1101 // If a 404 is being sent but the queried object is a valid single docs post,
834 1102 // override with 200. This guards against false 404s on single docs pages.
835 1103 if ( $code == 404 &&
836 1104 isset( $wp_query->queried_object ) &&
@@ -850,8 +1118,24 @@
850 1118 if ( $code == 404 && (
851 1119 (isset($wp_query->query_vars['doc_category']) && ! empty($wp_query->query_vars['doc_category'])) ||
852 1120 (isset($wp_query->query_vars['doc_tag']) && ! empty($wp_query->query_vars['doc_tag']))
853 1121 ) ) {
1122 + // A single-doc request (category-in-path permalinks carry the doc slug
1123 + // in the `docs`/`name` var alongside doc_category) must resolve to a real
1124 + // doc. A valid doc is already served 200 by the queried-object branch
1125 + // above; if we reach here with a single-doc indicator but no resolvable
1126 + // post, the doc does not exist — keep the genuine 404 rather than forcing
1127 + // a soft-404 200 off the category term alone. See betterdocs/betterdocs#169.
1128 + $single_doc_slug = '';
1129 + if ( isset( $wp_query->query_vars['docs'] ) && ! empty( $wp_query->query_vars['docs'] ) ) {
1130 + $single_doc_slug = $wp_query->query_vars['docs'];
1131 + } elseif ( isset( $wp_query->query_vars['name'] ) && ! empty( $wp_query->query_vars['name'] ) ) {
1132 + $single_doc_slug = $wp_query->query_vars['name'];
1133 + }
1134 + if ( '' !== $single_doc_slug && ! get_page_by_path( $single_doc_slug, OBJECT, 'docs' ) ) {
1135 + return $status_header;
1136 + }
1137 +
854 1138 // Validate existence before forcing 200
855 1139 // Use encoded fallback so Bengali/Arabic/CJK slugs are found correctly.
856 1140 if ( isset($wp_query->query_vars['doc_category']) && ! empty($wp_query->query_vars['doc_category']) ) {
857 1141 $term = $this->get_term_by_slug_or_encoded( $wp_query->query_vars['doc_category'], 'doc_category' );
@@ -878,8 +1162,41 @@
878 1162 return $status_header;
879 1163 }
880 1164
881 1165 /**
1166 + * Whether the main query targets a single doc (`name`, `docs` or `p`),
1167 + * as opposed to an archive.
1168 + *
1169 + * @return bool
1170 + */
1171 + protected function is_singular_docs_request() {
1172 + global $wp_query;
1173 +
1174 + if ( ! $wp_query instanceof \WP_Query ) {
1175 + return false;
1176 + }
1177 +
1178 + $query_vars = $wp_query->query_vars;
1179 +
1180 + return ! empty( $query_vars['name'] )
1181 + || ! empty( $query_vars['docs'] )
1182 + || ( isset( $query_vars['p'] ) && (int) $query_vars['p'] > 0 );
1183 + }
1184 +
1185 + /**
1186 + * Whether the main query actually returned posts. Slug and term lookups
1187 + * only prove something exists; this is what the visitor can see — it
1188 + * already honours post status, capabilities and WPML's language filter.
1189 + *
1190 + * @return bool
1191 + */
1192 + protected function main_query_has_posts() {
1193 + global $wp_query;
1194 +
1195 + return $wp_query instanceof \WP_Query && ! empty( $wp_query->posts );
1196 + }
1197 +
1198 + /**
882 1199 * Ensure tax_query is always initialized as an object
883 1200 * This prevents null reference errors from WPML and other plugins
884 1201 * Only applies to BetterDocs post type and taxonomies
885 1202 */
@@ -1473,8 +1790,17 @@
1473 1790
1474 1791 public function parse( $wp ) {
1475 1792 static::$already_parsed = true;
1476 1793
1794 + // An API Reference rewrite rule already matched (/docs/api/{slug}).
1795 + // The permalink magic below re-interprets the raw path against the
1796 + // docs/category/KB structures and would hijack the request whenever a
1797 + // doc_category or knowledge_base term shares the reference's slug —
1798 + // an explicit CPT match always wins.
1799 + if ( isset( $wp->query_vars['betterdocs_api_ref'] ) ) {
1800 + return;
1801 + }
1802 +
1477 1803 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- legacy public filter name, retained for back-compat with Pro/extensions.
1478 1804 $this->perma_structure = apply_filters('docs_rewrite_rules', $this->perma_structure);
1479 1805
1480 1806 $this->permalink_magic( $wp );
@@ -1505,8 +1831,15 @@
1505 1831 // Strip optional language prefix injected by Polylang/WPML (e.g. "en/", "bn/", "pt-br/")
1506 1832 // so that "bn/docs/..." matches the structure "docs/..." correctly.
1507 1833 $request_without_lang = preg_replace( '#^[a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,8})?/#', '', $request );
1508 1834
1835 + // When WPML translates a taxonomy base slug per language (e.g. doc_tag
1836 + // "docs-tag" -> "docs-tag-bn"), the incoming URL uses the translated slug,
1837 + // but perma_structure is built from the default-language slug. Map the
1838 + // leading translated slug back to its default so the raw structures match.
1839 + // No-op on non-WPML sites and when the slug isn't translated.
1840 + $request_canonical = $this->canonicalize_translated_slug( $request_without_lang );
1841 +
1509 1842 foreach ( $this->perma_structure as $_type => $structure ) {
1510 1843 // First try the raw (possibly language-prefixed) request, then the lang-stripped variant.
1511 1844 // This ensures we still match non-multilingual sites without stripping valid slugs.
1512 1845 $_perma_vars = $this->is_perma_valid_for( $structure, $request );
@@ -1512,8 +1845,11 @@
1512 1845 $_perma_vars = $this->is_perma_valid_for( $structure, $request );
1513 1846 if ( ! $_perma_vars && $request_without_lang !== $request ) {
1514 1847 $_perma_vars = $this->is_perma_valid_for( $structure, $request_without_lang );
1515 1848 }
1849 + if ( ! $_perma_vars && $request_canonical !== $request_without_lang ) {
1850 + $_perma_vars = $this->is_perma_valid_for( $structure, $request_canonical );
1851 + }
1516 1852
1517 1853 // $_valid = empty( $_valid ) && $_perma_vars ? [ 'type' => $_type, 'query_vars' => $_perma_vars ] : $_valid;
1518 1854 if ( ( $_perma_vars && method_exists( $this, $_type ) && call_user_func_array( [$this, $_type], [ & $_perma_vars] ) ) ) {
1519 1855
@@ -1561,8 +1897,46 @@
1561 1897 unset( $wp->query_vars['attachment'] );
1562 1898 }
1563 1899 }
1564 1900 }
1901 +
1902 + /**
1903 + * Map a leading WPML-translated taxonomy base slug back to its default-language
1904 + * value so the default-language perma_structure patterns can match a translated URL.
1905 + *
1906 + * Only the first path segment is considered (the taxonomy base). Returns the
1907 + * request unchanged when WPML is inactive or the leading segment isn't a
1908 + * translated BetterDocs slug.
1909 + *
1910 + * @param string $request Language-stripped request path (no leading/trailing slash).
1911 + * @return string
1912 + */
1913 + private function canonicalize_translated_slug( $request ) {
1914 + if ( $request === '' || strpos( $request, '/' ) === false ) {
1915 + return $request;
1916 + }
1917 +
1918 + $slug_map = [
1919 + 'doc_tag' => trim( $this->settings->get( 'tag_slug', 'docs-tag' ), '/' ),
1920 + 'doc_category' => trim( $this->settings->get( 'category_slug', 'docs-category' ), '/' ),
1921 + ];
1922 +
1923 + $segments = explode( '/', $request );
1924 +
1925 + foreach ( $slug_map as $taxonomy => $default ) {
1926 + if ( $default === '' ) {
1927 + continue;
1928 + }
1929 +
1930 + $translated = Helper::wpml_translated_tax_slug( $taxonomy, $default );
1931 + if ( $translated !== $default && $segments[0] === $translated ) {
1932 + $segments[0] = $default;
1933 + return implode( '/', $segments );
1934 + }
1935 + }
1936 +
1937 + return $request;
1938 + }
1565 1939
1566 1940 /**
1567 1941 * This method is responsible for checking a structure is valid again a request.
1568 1942 *