Files
chrnx-dev-wp/inc/queries.php
T
2026-08-15 14:08:52 -05:00

729 lines
21 KiB
PHP

<?php
/**
* Editorial query services.
*
* @package CHRNX
*/
/**
* Whether a post is eligible for public editorial surfaces.
*
* @param int|WP_Post $post Post object or ID.
* @return bool Whether the post is eligible.
*/
function chrnx_is_eligible_editorial_post( $post ) {
$post = get_post( $post );
return $post instanceof WP_Post
&& 'post' === $post->post_type
&& 'publish' === $post->post_status
&& 1 === preg_match( '/\S/u', $post->post_title );
}
/** Clear request-local editorial query results after relevant mutations. */
function chrnx_clear_editorial_query_cache() {
$GLOBALS['chrnx_editorial_query_cache'] = array();
}
add_action( 'save_post_post', 'chrnx_clear_editorial_query_cache', 10, 0 );
add_action( 'deleted_post', 'chrnx_clear_editorial_query_cache', 10, 0 );
add_action( 'set_object_terms', 'chrnx_clear_editorial_query_cache', 10, 0 );
add_action( 'update_option_sticky_posts', 'chrnx_clear_editorial_query_cache', 10, 0 );
add_action( 'add_option_sticky_posts', 'chrnx_clear_editorial_query_cache', 10, 0 );
add_action( 'delete_option_sticky_posts', 'chrnx_clear_editorial_query_cache', 10, 0 );
/**
* Clear request-local results after direct relationship deletion.
*
* @param int $object_id Object whose relationships were deleted.
* @param int[] $term_taxonomy_ids Deleted term-taxonomy IDs.
* @param string $taxonomy Taxonomy name.
*/
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- The hook contract requires all three arguments.
function chrnx_clear_editorial_query_cache_after_relationship_delete( $object_id, $term_taxonomy_ids, $taxonomy ) {
chrnx_clear_editorial_query_cache();
}
add_action( 'deleted_term_relationships', 'chrnx_clear_editorial_query_cache_after_relationship_delete', 10, 3 );
/**
* Recursively normalize query arguments for a stable request-local cache key.
*
* @param mixed $value Query argument value.
* @return mixed Normalized value.
*/
function chrnx_normalize_editorial_query_cache_value( $value ) {
if ( ! is_array( $value ) ) {
return $value;
}
if ( ! array_is_list( $value ) ) {
ksort( $value );
}
foreach ( $value as $key => $item ) {
$value[ $key ] = chrnx_normalize_editorial_query_cache_value( $item );
}
return $value;
}
/**
* Restrict explicitly marked editorial queries to nonblank post titles.
*
* @param string $where Existing WHERE clause.
* @param WP_Query $query Query instance.
* @return string Filtered WHERE clause.
*/
function chrnx_filter_nonempty_editorial_titles( $where, $query ) {
if ( ! $query->get( 'chrnx_require_nonempty_title' ) ) {
return $where;
}
global $wpdb;
return $where . $wpdb->prepare( ' AND ' . $wpdb->posts . '.post_title REGEXP %s', '[^[:space:]]' );
}
/**
* Run one eligible editorial query with a tightly scoped title predicate.
*
* @param array<string,mixed> $args WP_Query arguments carrying the internal eligibility flag.
* @return WP_Query Completed query.
*/
function chrnx_run_eligible_query( array $args ) {
$already_registered = false !== has_filter( 'posts_where', 'chrnx_filter_nonempty_editorial_titles' );
if ( ! $already_registered ) {
add_filter( 'posts_where', 'chrnx_filter_nonempty_editorial_titles', 10, 2 );
}
try {
return new WP_Query( $args );
} finally {
if ( ! $already_registered ) {
remove_filter( 'posts_where', 'chrnx_filter_nonempty_editorial_titles', 10 );
}
}
}
/**
* Return a bounded eligible candidate set in deterministic publication order.
*
* @param array<string,mixed> $extra_args Additional WP_Query arguments.
* @return int[] Eligible post IDs.
*/
function chrnx_get_eligible_editorial_post_ids( $extra_args = array() ) {
$requested_limit = isset( $extra_args['posts_per_page'] ) ? (int) $extra_args['posts_per_page'] : 12;
$limit = min( 12, max( 1, $requested_limit ) );
$args = array_merge(
array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $limit,
'orderby' => array(
'date' => 'DESC',
'ID' => 'DESC',
),
'ignore_sticky_posts' => true,
'no_found_rows' => true,
'fields' => 'ids',
'cache_results' => false,
'suppress_filters' => false,
'chrnx_require_nonempty_title' => true,
),
$extra_args,
array( 'posts_per_page' => $limit )
);
$key = md5( (string) wp_json_encode( chrnx_normalize_editorial_query_cache_value( $args ) ) );
$cache = isset( $GLOBALS['chrnx_editorial_query_cache'] ) && is_array( $GLOBALS['chrnx_editorial_query_cache'] )
? $GLOBALS['chrnx_editorial_query_cache']
: array();
if ( isset( $cache[ $key ] ) ) {
return $cache[ $key ];
}
$query = chrnx_run_eligible_query( $args );
$ids = array_values( array_map( 'absint', $query->posts ) );
if ( ! empty( $ids ) ) {
_prime_post_caches( $ids, true, true );
}
$cache[ $key ] = $ids;
$GLOBALS['chrnx_editorial_query_cache'] = $cache;
return $ids;
}
/**
* Return the first assigned topic slug for a post.
*
* @param int $post_id Post ID.
* @return string Topic slug or empty string.
*/
function chrnx_get_post_topic_slug( $post_id ) {
$terms = get_the_terms( $post_id, 'chrnx_topic' );
if ( is_wp_error( $terms ) || empty( $terms ) ) {
return '';
}
$term = reset( $terms );
return $term instanceof WP_Term ? (string) $term->slug : '';
}
/**
* Select featured story IDs using sticky primary and topic-diverse secondaries.
*
* @param int $limit Maximum cards, bounded to 12.
* @return int[] Selected post IDs.
*/
function chrnx_get_featured_story_ids( int $limit = 3 ): array {
$limit = min( 12, max( 0, $limit ) );
$host = wp_parse_url( home_url( '/' ), PHP_URL_HOST );
if ( in_array( $host, array( 'localhost', '127.0.0.1' ), true ) ) {
$fixture_limit = absint( get_option( '_chrnx_fixture_featured_limit', 0 ) );
if ( in_array( $fixture_limit, array( 1, 2, 3 ), true ) ) {
$limit = min( $limit, $fixture_limit );
}
}
if ( 0 === $limit ) {
return array();
}
$sticky_ids = array_map( 'absint', (array) get_option( 'sticky_posts', array() ) );
$primary_ids = ! empty( $sticky_ids )
? chrnx_get_eligible_editorial_post_ids(
array(
'post__in' => $sticky_ids,
'posts_per_page' => 1,
)
)
: array();
if ( empty( $primary_ids ) ) {
$primary_ids = chrnx_get_eligible_editorial_post_ids( array( 'posts_per_page' => 1 ) );
}
if ( empty( $primary_ids ) ) {
return array();
}
$primary = $primary_ids[0];
$selected = array( $primary );
$used = array();
$topic = chrnx_get_post_topic_slug( $primary );
if ( '' !== $topic ) {
$used[] = $topic;
}
if ( count( $selected ) >= $limit ) {
return $selected;
}
$definitions = chrnx_get_editorial_taxonomies();
$candidates = array();
foreach ( array_keys( $definitions['chrnx_topic']['terms'] ) as $topic_slug ) {
if ( in_array( $topic_slug, $used, true ) ) {
continue;
}
$topic_ids = chrnx_get_eligible_editorial_post_ids(
array(
'posts_per_page' => 1,
'post__not_in' => array( $primary ),
'tax_query' => array(
array(
'taxonomy' => 'chrnx_topic',
'field' => 'slug',
'terms' => $topic_slug,
),
),
)
);
if ( ! empty( $topic_ids ) ) {
$candidates[] = $topic_ids[0];
}
}
usort(
$candidates,
static function ( $first_id, $second_id ) {
$first = get_post( $first_id );
$second = get_post( $second_id );
$date_compare = strcmp( $second->post_date, $first->post_date );
return 0 !== $date_compare ? $date_compare : $second_id <=> $first_id;
}
);
foreach ( $candidates as $candidate_id ) {
if ( count( $selected ) >= $limit ) {
break;
}
$selected[] = $candidate_id;
}
$remaining = $limit - count( $selected );
if ( $remaining > 0 ) {
$selected = array_merge(
$selected,
chrnx_get_eligible_editorial_post_ids(
array(
'posts_per_page' => $remaining,
'post__not_in' => $selected,
)
)
);
}
return $selected;
}
/**
* Select projects for the Selected work stage: hand-picked first, then recent.
*
* Sticky already belongs to the home featured stories, so the editorial choice
* lives in its own per-post flag instead of competing for the same signal.
*
* @param int $limit Maximum projects, bounded to 12.
* @return int[] Selected project post IDs.
*/
function chrnx_get_selected_project_ids( int $limit = 3 ): array {
$limit = min( 12, max( 0, $limit ) );
if ( 0 === $limit ) {
return array();
}
$topic_query = array(
array(
'taxonomy' => 'chrnx_topic',
'field' => 'slug',
'terms' => 'projects',
),
);
$selected = chrnx_get_eligible_editorial_post_ids(
array(
'posts_per_page' => $limit,
'tax_query' => $topic_query,
'meta_query' => array(
array(
'key' => 'chrnx_project_featured',
'value' => '1',
),
),
)
);
$remaining = $limit - count( $selected );
if ( $remaining > 0 ) {
$selected = array_merge(
$selected,
chrnx_get_eligible_editorial_post_ids(
array(
'posts_per_page' => $remaining,
'post__not_in' => $selected,
'tax_query' => $topic_query,
)
)
);
}
return $selected;
}
/**
* Validate a request taxonomy slug against an existing editorial term.
*
* @param mixed $value Requested value.
* @param string $taxonomy Editorial taxonomy.
* @return string Valid slug or empty string.
*/
function chrnx_validate_editorial_term_slug( $value, $taxonomy ) {
if ( ! is_string( $value ) || ! taxonomy_exists( $taxonomy ) ) {
return '';
}
$value = trim( wp_unslash( $value ) );
if ( '' === $value || sanitize_title( $value ) !== $value ) {
return '';
}
$term = get_term_by( 'slug', $value, $taxonomy );
return $term instanceof WP_Term ? $term->slug : '';
}
/**
* Parse a canonical public Journal page number.
*
* @param mixed $value Request-shaped page value.
* @return int A page from 1 through 10000, or 1 for invalid input.
*/
function chrnx_parse_journal_page( $value ) {
if ( is_int( $value ) ) {
$page = $value;
} elseif ( is_string( $value ) && preg_match( '/^[1-9][0-9]*$/', $value ) ) {
$page = (int) $value;
} else {
return 1;
}
return $page >= 1 && $page <= 10000 ? $page : 1;
}
/**
* Sanitize and bound public Journal search text.
*
* @param mixed $value Request-shaped search value.
* @return string Safe search text or an empty string.
*/
function chrnx_sanitize_journal_search( $value ) {
if ( ! is_scalar( $value ) ) {
return '';
}
return mb_substr( trim( sanitize_text_field( wp_unslash( (string) $value ) ) ), 0, 100, 'UTF-8' );
}
/**
* Return allowlisted fixed filter context for the current editorial taxonomy archive.
*
* @param mixed $queried_object Optional queried object; defaults to the current request.
* @return array<string,string> Taxonomy, slug, and label, or an empty array.
*/
function chrnx_get_journal_archive_filter( $queried_object = null ): array {
$queried_object = null === $queried_object ? get_queried_object() : $queried_object;
if ( ! $queried_object instanceof WP_Term || ! in_array( $queried_object->taxonomy, array( 'chrnx_topic', 'chrnx_language', 'chrnx_show' ), true ) ) {
return array();
}
$slug = chrnx_validate_editorial_term_slug( $queried_object->slug, $queried_object->taxonomy );
if ( '' === $slug ) {
return array();
}
return array(
'taxonomy' => $queried_object->taxonomy,
'slug' => $slug,
'label' => $queried_object->name,
);
}
/**
* Normalize public Journal filters and force allowlisted taxonomy archive context.
*
* @param array $request Request-shaped filter values.
* @param mixed $queried_object Optional queried object; defaults to the current request.
* @return array<string,mixed> Safe Journal request context.
*/
function chrnx_get_journal_request_context( array $request, $queried_object = null ): array {
$context = array(
'paged' => chrnx_parse_journal_page( $request['paged'] ?? null ),
);
foreach ( array( 'chrnx_topic', 'chrnx_language' ) as $taxonomy ) {
$slug = chrnx_validate_editorial_term_slug( $request[ $taxonomy ] ?? '', $taxonomy );
if ( '' !== $slug ) {
$context[ $taxonomy ] = $slug;
}
}
$search = chrnx_sanitize_journal_search( $request['s'] ?? '' );
if ( '' !== $search ) {
$context['s'] = $search;
}
$archive_filter = chrnx_get_journal_archive_filter( $queried_object );
if ( ! empty( $archive_filter ) ) {
$context[ $archive_filter['taxonomy'] ] = $archive_filter['slug'];
}
return $context;
}
/**
* Return the current Journal base URL while retaining required WP routing.
*
* @return string Safe current Page or archive URL.
*/
function chrnx_get_journal_base_url() {
$queried = get_queried_object();
if ( $queried instanceof WP_Post && 'page' === $queried->post_type ) {
$url = get_permalink( $queried );
return is_string( $url ) ? $url : '';
}
if ( $queried instanceof WP_Term && in_array( $queried->taxonomy, array( 'chrnx_topic', 'chrnx_language', 'chrnx_show' ), true ) ) {
$url = get_term_link( $queried );
return is_wp_error( $url ) ? '' : $url;
}
$url = get_pagenum_link( 1, false );
$base_url = strtok( $url, '?' );
$query_string = wp_parse_url( $url, PHP_URL_QUERY );
$routing_values = array();
if ( is_string( $query_string ) ) {
parse_str( html_entity_decode( $query_string, ENT_QUOTES | ENT_HTML5, 'UTF-8' ), $routing_values );
}
$routing_values = array_intersect_key(
$routing_values,
array_flip( array( 'page_id', 'p', 'pagename', 'name', 'post_type', 'taxonomy', 'term', 'cat', 'category_name', 'tag' ) )
);
return add_query_arg( $routing_values, $base_url );
}
/**
* Return the canonical full Journal destination independent of current filters.
*
* @return string Portable Journal URL.
*/
function chrnx_get_full_journal_url() {
$page = get_page_by_path( 'journal', OBJECT, 'page' );
if ( $page instanceof WP_Post && 'publish' === $page->post_status ) {
$url = get_permalink( $page );
if ( is_string( $url ) && '' !== $url ) {
return $url;
}
}
$posts_page_id = absint( get_option( 'page_for_posts' ) );
$posts_page = $posts_page_id > 0 ? get_post( $posts_page_id ) : null;
if ( $posts_page instanceof WP_Post && 'page' === $posts_page->post_type && 'publish' === $posts_page->post_status ) {
$url = get_permalink( $posts_page );
if ( is_string( $url ) && '' !== $url ) {
return $url;
}
}
return home_url( '/' );
}
/**
* Build a Journal page URL from only validated public filters.
*
* @param int $page Requested page number.
* @param array $filters Request-shaped Journal filters.
* @return string Safe Journal URL.
*/
function chrnx_get_journal_page_url( int $page, array $filters ) {
$base_url = chrnx_get_journal_base_url();
$args = array();
foreach ( array( 'chrnx_topic', 'chrnx_language', 'chrnx_show' ) as $taxonomy ) {
$slug = chrnx_validate_editorial_term_slug( $filters[ $taxonomy ] ?? '', $taxonomy );
if ( '' !== $slug ) {
$args[ $taxonomy ] = $slug;
}
}
$search = chrnx_sanitize_journal_search( $filters['s'] ?? '' );
if ( '' !== $search ) {
$args['s'] = $search;
}
$page = chrnx_parse_journal_page( $page );
if ( $page > 1 ) {
$args['paged'] = $page;
}
return add_query_arg( $args, $base_url );
}
/**
* Build safe Journal WP_Query arguments from request-shaped data.
*
* @param array $request Request values.
* @return array<string,mixed> Safe WP_Query arguments.
*/
function chrnx_get_journal_query_args( array $request ): array {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
'paged' => chrnx_parse_journal_page( $request['paged'] ?? null ),
'orderby' => array(
'date' => 'DESC',
'ID' => 'DESC',
),
'ignore_sticky_posts' => true,
'suppress_filters' => false,
'chrnx_require_nonempty_title' => true,
);
$tax_query = array();
foreach ( array( 'chrnx_topic', 'chrnx_language', 'chrnx_show' ) as $taxonomy ) {
$value = $request[ $taxonomy ] ?? '';
$slug = chrnx_validate_editorial_term_slug( $value, $taxonomy );
if ( '' !== $slug ) {
$tax_query[] = array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $slug,
);
}
}
if ( ! empty( $tax_query ) ) {
$args['tax_query'] = $tax_query;
}
$search = chrnx_sanitize_journal_search( $request['s'] ?? '' );
if ( '' !== $search ) {
$args['s'] = $search;
}
return $args;
}
/**
* Return the latest eligible podcast assigned to any show.
*
* @return int Podcast post ID or zero.
*/
function chrnx_get_latest_podcast_id(): int {
$ids = chrnx_get_eligible_editorial_post_ids(
array(
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'chrnx_topic',
'field' => 'slug',
'terms' => 'podcasts',
),
array(
'taxonomy' => 'chrnx_show',
'operator' => 'EXISTS',
),
),
)
);
return ! empty( $ids ) ? $ids[0] : 0;
}
/**
* Build query arguments for one validated show.
*
* @param string $show_slug Existing show slug.
* @param mixed $page Request-shaped page number.
* @return array<string,mixed> Safe WP_Query arguments.
*/
function chrnx_get_show_query_args( string $show_slug, $page = 1 ): array {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
'paged' => chrnx_parse_journal_page( $page ),
'orderby' => array(
'date' => 'DESC',
'ID' => 'DESC',
),
'ignore_sticky_posts' => true,
'suppress_filters' => false,
'chrnx_require_nonempty_title' => true,
);
$slug = chrnx_validate_editorial_term_slug( $show_slug, 'chrnx_show' );
if ( '' === $slug ) {
$args['post__in'] = array( 0 );
return $args;
}
$args['tax_query'] = array(
array(
'taxonomy' => 'chrnx_show',
'field' => 'slug',
'terms' => $slug,
),
);
return $args;
}
/**
* Return related posts tiered by topic, shared tags, then recency.
*
* @param int $post_id Current post ID.
* @param int $limit Maximum related stories, bounded to 12.
* @return int[] Related post IDs.
*/
function chrnx_get_related_post_ids( int $post_id, int $limit = 3 ): array {
$limit = min( 12, max( 0, $limit ) );
if ( 0 === $limit || ! chrnx_is_eligible_editorial_post( $post_id ) ) {
return array();
}
$topic = chrnx_get_post_topic_slug( $post_id );
$tag_ids = wp_get_post_tags( $post_id, array( 'fields' => 'ids' ) );
$tag_ids = is_wp_error( $tag_ids ) ? array() : array_map( 'absint', $tag_ids );
$selected = array();
if ( '' !== $topic ) {
$selected = chrnx_get_eligible_editorial_post_ids(
array(
'posts_per_page' => $limit,
'post__not_in' => array( $post_id ),
'tax_query' => array(
array(
'taxonomy' => 'chrnx_topic',
'field' => 'slug',
'terms' => $topic,
),
),
)
);
}
$remaining = $limit - count( $selected );
if ( $remaining > 0 && ! empty( $tag_ids ) ) {
$tag_matches = chrnx_get_eligible_editorial_post_ids(
array(
'posts_per_page' => $remaining,
'post__not_in' => array_merge( array( $post_id ), $selected ),
'tag__in' => $tag_ids,
)
);
$selected = array_merge( $selected, $tag_matches );
}
$remaining = $limit - count( $selected );
if ( $remaining > 0 ) {
$recent = chrnx_get_eligible_editorial_post_ids(
array(
'posts_per_page' => $remaining,
'post__not_in' => array_merge( array( $post_id ), $selected ),
)
);
$selected = array_merge( $selected, $recent );
}
return $selected;
}
/**
* Return the fixed theme-relative topic art asset path.
*
* @param string $topic_slug Supported topic slug.
* @return string Theme-relative asset path or empty string.
*/
function chrnx_get_topic_art_asset( string $topic_slug ): string {
$mapping = array(
'research' => 'alter-ego-research.png',
'code' => 'alter-ego-code.png',
'projects' => 'alter-ego-code.png',
'literature' => 'alter-ego-literature.png',
'music' => 'the-no-names-musician-cutout.png',
'music-collage' => 'the-no-names-collage.jpeg',
'podcast-frequency' => 'podcast-frequency-grunge.png',
'about-grunge' => 'about-grunge.png',
'placeholder-post' => 'placeholder-post.png',
'placeholder-release' => 'placeholder-release.png',
'placeholder-project' => 'placeholder-project.png',
'projects-grunge' => 'projects-grunge.png',
'podcasts' => 'alter-ego-podcasts.png',
'life' => 'alter-ego-life.png',
'gaming' => 'alter-ego-gaming-half-body.png',
);
return isset( $mapping[ $topic_slug ] ) ? 'assets/images/' . $mapping[ $topic_slug ] : '';
}
/**
* Return exact intrinsic dimensions for allowlisted topic art.
*
* @param string $topic_slug Supported topic slug.
* @return int[] Width and height, or an empty array.
*/
function chrnx_get_topic_art_dimensions( string $topic_slug ): array {
if ( '' === chrnx_get_topic_art_asset( $topic_slug ) ) {
return array();
}
// The landscape atmosphere backgrounds share one intrinsic size.
if ( in_array( $topic_slug, array( 'podcast-frequency', 'about-grunge', 'projects-grunge' ), true ) ) {
return array( 1536, 1024 );
}
if ( 'placeholder-post' === $topic_slug ) {
return array( 1440, 960 );
}
if ( 'placeholder-release' === $topic_slug ) {
return array( 1536, 1536 );
}
if ( 'placeholder-project' === $topic_slug ) {
return array( 1534, 1025 );
}
return 'gaming' === $topic_slug ? array( 1024, 1536 ) : array( 1122, 1402 );
}