array( 'post', 'term' ), 'term' => array( 'post' ), 'age' => array( 'post' ), 'slug' => array( 'post', 'term' ), 'count' => array( 'term' ), 'parent' => array( 'post', 'term' ), ); const OPS = array( 'meta' => array( '=', '!=', '<', '<=', '>', '>=', 'contains', 'not_contains', 'exists', 'not_exists' ), 'term' => array( 'in', 'not_in' ), 'age' => array( 'older_than_days', 'newer_than_days' ), 'slug' => array( 'is', 'is_not', 'contains', 'not_contains' ), 'count' => array( '=', '!=', '<', '<=', '>', '>=' ), 'parent' => array( 'has_parent', 'is_top' ), ); const NO_VALUE = array( 'exists', 'not_exists', 'has_parent', 'is_top' ); const NUMERIC = array( '<', '<=', '>', '>=', 'older_than_days', 'newer_than_days' ); private static $settings = null; private static $column = null; private static $prefetch = null; public static function boot() { foreach ( array( 'post', 'term' ) as $kind ) { add_action( "added_{$kind}_meta", array( __CLASS__, 'meta_changed' ), 10, 3 ); add_action( "updated_{$kind}_meta", array( __CLASS__, 'meta_changed' ), 10, 3 ); add_action( "deleted_{$kind}_meta", array( __CLASS__, 'meta_deleted' ), 10, 3 ); } } public static function settings() { if ( null === self::$settings ) { self::$settings = self::sanitize( get_option( self::OPTION, array() ), $ignored, false ); } return self::$settings; } public static function save( $raw, &$errors = null ) { $clean = self::sanitize( $raw, $errors, true ); update_option( self::OPTION, $clean, false ); self::$settings = $clean; return $clean; } public static function reset() { self::$settings = null; self::$column = null; self::$prefetch = null; } public static function sanitize( $raw, &$errors = null, $strict = true ) { $errors = array(); $raw = is_array( $raw ) ? $raw : array(); $only = array(); foreach ( array_slice( (array) ( $raw['only'] ?? array() ), 0, 200 ) as $target ) { $target = self::clean_target( $target, $strict ); if ( '' !== $target ) { $only[] = $target; } } $rules = array(); foreach ( array_values( array_slice( (array) ( $raw['rules'] ?? array() ), 0, self::MAX_RULES ) ) as $i => $rule ) { $target = self::clean_target( is_array( $rule ) ? ( $rule['target'] ?? '' ) : '', $strict ); if ( '' === $target ) { $errors[] = sprintf( __( 'Rule %d: choose a content type.', 'ai-eshop-optimizer' ), $i + 1 ); continue; } $problems = array(); $n = 0; $when = self::clean_tree( $rule['when'] ?? array(), substr( $target, 0, 4 ), 0, $strict, $problems, $n ); if ( $problems ) { foreach ( $problems as $problem ) { $errors[] = sprintf( __( 'Rule %1$d: %2$s', 'ai-eshop-optimizer' ), $i + 1, $problem ); } continue; } $rules[] = array( 'target' => $target, 'when' => $when, ); } return array( 'only' => array_values( array_unique( $only ) ), 'home' => ! empty( $raw['home'] ), 'rules' => $rules, ); } private static function clean_target( $target, $strict ) { if ( ! is_string( $target ) || ! preg_match( '/^(post|term):([^\s:<>"\'&]{1,64})$/u', $target, $m ) ) { return ''; } if ( $strict && ! ( 'post' === $m[1] ? post_type_exists( $m[2] ) : taxonomy_exists( $m[2] ) ) ) { return ''; } return $m[1] . ':' . $m[2]; } private static function clean_tree( $tree, $kind, $depth, $strict, array &$problems, &$n ) { $tree = is_array( $tree ) ? $tree : array(); $out = array( 'op' => ( 'or' === ( $tree['op'] ?? '' ) ) ? 'or' : 'and', 'conditions' => array(), ); $list = (array) ( $tree['conditions'] ?? array() ); if ( count( $list ) > self::MAX_CONDITIONS ) { $problems[] = sprintf( __( 'a group holds at most %d conditions.', 'ai-eshop-optimizer' ), self::MAX_CONDITIONS ); return $out; } if ( $depth > 0 && ! $list ) { $problems[] = __( 'a group of conditions is empty.', 'ai-eshop-optimizer' ); return $out; } foreach ( $list as $c ) { if ( is_array( $c ) && isset( $c['conditions'] ) ) { if ( $depth >= self::MAX_DEPTH ) { $problems[] = __( 'groups of conditions nest at most two deep.', 'ai-eshop-optimizer' ); continue; } $out['conditions'][] = self::clean_tree( $c, $kind, $depth + 1, $strict, $problems, $n ); continue; } ++$n; $leaf = self::clean_leaf( is_array( $c ) ? $c : array(), $kind, $strict ); if ( is_string( $leaf ) ) { $problems[] = sprintf( __( 'condition %1$d %2$s', 'ai-eshop-optimizer' ), $n, $leaf ); continue; } $out['conditions'][] = $leaf; } return $out; } private static function clean_leaf( array $c, $kind, $strict ) { $field = is_string( $c['field'] ?? null ) ? $c['field'] : ''; $op = is_string( $c['op'] ?? null ) ? $c['op'] : ''; if ( ! isset( self::FIELDS[ $field ] ) || ! in_array( $kind, self::FIELDS[ $field ], true ) || ! in_array( $op, self::OPS[ $field ], true ) ) { return __( 'is not one this content type offers.', 'ai-eshop-optimizer' ); } $leaf = array( 'field' => $field, 'op' => $op, ); if ( 'meta' === $field ) { $key = is_scalar( $c['key'] ?? null ) ? trim( (string) $c['key'] ) : ''; if ( '' === $key || ! preg_match( '/^[^\s<>"\'&]{1,191}$/u', $key ) ) { return __( 'needs a field key.', 'ai-eshop-optimizer' ); } $leaf['key'] = $key; } if ( 'term' === $field ) { $tax = is_string( $c['taxonomy'] ?? null ) ? trim( $c['taxonomy'] ) : ''; if ( '' === $tax || ! preg_match( '/^[^\s:<>"\'&]{1,64}$/u', $tax ) || ( $strict && ! taxonomy_exists( $tax ) ) ) { return __( 'needs a taxonomy.', 'ai-eshop-optimizer' ); } $leaf['taxonomy'] = $tax; $slugs = is_array( $c['value'] ?? null ) ? $c['value'] : explode( ',', is_scalar( $c['value'] ?? null ) ? (string) $c['value'] : '' ); $slugs = array_slice( array_values( array_unique( array_filter( array_map( 'sanitize_title', array_map( 'strval', array_filter( $slugs, 'is_scalar' ) ) ) ) ) ), 0, self::MAX_SLUGS ); if ( ! $slugs ) { return __( 'needs at least one term slug.', 'ai-eshop-optimizer' ); } $leaf['value'] = $slugs; return $leaf; } if ( in_array( $op, self::NO_VALUE, true ) ) { return $leaf; } $value = is_scalar( $c['value'] ?? null ) ? trim( sanitize_text_field( (string) $c['value'] ) ) : ''; if ( in_array( $op, self::NUMERIC, true ) || 'count' === $field ) { $number = self::number( $value ); if ( null === $number ) { return __( 'needs a number.', 'ai-eshop-optimizer' ); } $leaf['value'] = (string) ( floor( $number ) == $number ? (int) $number : $number ); return $leaf; } if ( '' === $value ) { return __( 'needs a value.', 'ai-eshop-optimizer' ); } $leaf['value'] = function_exists( 'mb_substr' ) ? mb_substr( $value, 0, 200 ) : substr( $value, 0, 200 ); return $leaf; } public static function number( $value ) { if ( is_int( $value ) || is_float( $value ) ) { return (float) $value; } if ( ! is_string( $value ) ) { return null; } $s = str_replace( array( ' ', "\u{00A0}", "\u{202F}", "'", '_' ), '', trim( $value ) ); if ( '' === $s ) { return null; } if ( preg_match( '/^[-+]?[1-9]\d{0,2}([.,])\d{3}(?:\1\d{3})*$/', $s ) ) { return (float) str_replace( array( '.', ',' ), '', $s ); } if ( preg_match( '/^[-+]?\d+(?:[.,]\d+)?$/', $s ) ) { return (float) str_replace( ',', '.', $s ); } if ( preg_match( '/^[-+]?[1-9]\d{0,2}(?:,\d{3})+\.\d+$/', $s ) ) { return (float) str_replace( ',', '', $s ); } if ( preg_match( '/^[-+]?[1-9]\d{0,2}(?:\.\d{3})+,\d+$/', $s ) ) { return (float) str_replace( array( '.', ',' ), array( '', '.' ), $s ); } return is_numeric( $s ) ? (float) $s : null; } public static function kind( $object_type ) { if ( post_type_exists( (string) $object_type ) ) { return 'post'; } return taxonomy_exists( (string) $object_type ) ? 'term' : ''; } public static function item_mode( $kind, $object_id ) { $mode = self::meta_raw( $kind, (int) $object_id, self::META ); return is_string( $mode ) && in_array( $mode, array( 'always', 'never' ), true ) ? $mode : ''; } public static function decide( $object_type, $object_id, $kind = '' ) { $object_type = (string) $object_type; $object_id = (int) $object_id; $kind = in_array( $kind, array( 'post', 'term' ), true ) ? $kind : self::kind( $object_type ); if ( '' === $kind || $object_id <= 0 ) { return 1; } $mode = self::item_mode( $kind, $object_id ); $target = $kind . ':' . $object_type; $rule = ''; if ( 'always' === $mode ) { $include = true; } elseif ( 'never' === $mode ) { $include = false; } elseif ( 'term' === $kind && self::hidden_default_term( $object_type, $object_id ) ) { $include = false; $rule = 'uncategorized'; } else { $settings = self::settings(); $include = empty( $settings['only'] ) || in_array( $target, $settings['only'], true ); if ( $include ) { foreach ( $settings['rules'] as $i => $r ) { if ( $r['target'] === $target && self::matches( $r['when'], $kind, $object_id ) ) { $include = false; $rule = (string) $i; break; } } } } $include = (bool) apply_filters( 'aieo_seo_sitemap_include', $include, $object_type, $object_id, array( 'kind' => $kind, 'mode' => $mode, 'rule' => $rule ) ); return $include ? ( 'always' === $mode ? 2 : 1 ) : 0; } private static function hidden_default_term( $taxonomy, $term_id ) { if ( 'product_cat' === $taxonomy && (int) get_option( 'default_product_cat', 0 ) === (int) $term_id ) { $cats = get_option( 'aieo_dmm_product_categories_settings', array() ); return ! is_array( $cats ) || ! array_key_exists( 'hide_uncategorized', $cats ) || ! empty( $cats['hide_uncategorized'] ); } if ( 'category' === $taxonomy && (int) get_option( 'default_category', 0 ) === (int) $term_id ) { return 'uncategorized' === get_term_field( 'slug', (int) $term_id, 'category' ); } return false; } public static function matches( array $tree, $kind, $object_id, $top = true ) { $conditions = (array) ( $tree['conditions'] ?? array() ); if ( empty( $conditions ) ) { return (bool) $top; } $any = ( 'or' === ( $tree['op'] ?? 'and' ) ); foreach ( $conditions as $c ) { $hit = isset( $c['conditions'] ) ? self::matches( (array) $c, $kind, $object_id, false ) : self::leaf( (array) $c, $kind, (int) $object_id ); if ( $any && $hit ) { return true; } if ( ! $any && ! $hit ) { return false; } } return ! $any; } private static function leaf( array $c, $kind, $id ) { $op = (string) ( $c['op'] ?? '' ); $value = $c['value'] ?? ''; switch ( $c['field'] ?? '' ) { case 'meta': $have = self::meta_value( $kind, $id, (string) ( $c['key'] ?? '' ) ); if ( 'exists' === $op ) { return null !== $have && '' !== $have; } if ( 'not_exists' === $op ) { return null === $have || '' === $have; } if ( null === $have || is_bool( $have ) ) { return false; } return self::compare( is_scalar( $have ) ? $have : (string) wp_json_encode( $have ), (string) $value, $op ); case 'term': $tax = (string) ( $c['taxonomy'] ?? '' ); if ( ! taxonomy_exists( $tax ) || ! $value ) { return false; } $terms = get_the_terms( $id, $tax ); if ( is_wp_error( $terms ) ) { return false; } $slugs = is_array( $terms ) ? wp_list_pluck( $terms, 'slug' ) : array(); $hit = (bool) array_intersect( $slugs, (array) $value ); return 'in' === $op ? $hit : ! $hit; case 'age': $post = get_post( $id ); $days = self::number( (string) $value ); if ( ! $post || null === $days || ! $post->post_date_gmt || '0000-00-00 00:00:00' === $post->post_date_gmt ) { return false; } $age = ( time() - (int) strtotime( $post->post_date_gmt . ' UTC' ) ) / DAY_IN_SECONDS; return 'older_than_days' === $op ? $age > $days : $age < $days; case 'slug': $slug = 'term' === $kind ? get_term_field( 'slug', $id ) : get_post_field( 'post_name', $id ); if ( is_wp_error( $slug ) ) { return false; } return self::compare( rawurldecode( (string) $slug ), (string) $value, 'is' === $op ? '=' : ( 'is_not' === $op ? '!=' : $op ) ); case 'count': $count = get_term_field( 'count', $id ); return ! is_wp_error( $count ) && self::compare( (int) $count, (string) $value, $op ); case 'parent': $parent = 'term' === $kind ? get_term_field( 'parent', $id ) : get_post_field( 'post_parent', $id ); if ( is_wp_error( $parent ) ) { return false; } return 'has_parent' === $op ? (int) $parent > 0 : 0 === (int) $parent; } return false; } public static function meta_value( $kind, $id, $key ) { $key = (string) $key; if ( '' === $key ) { return null; } $own = self::meta_raw( $kind, $id, $key ); if ( null !== $own || false === strpos( $key, '.' ) ) { return $own; } $path = explode( '.', $key ); $node = self::meta_raw( $kind, $id, array_shift( $path ) ); foreach ( $path as $step ) { if ( is_string( $node ) ) { $decoded = json_decode( $node, true ); $node = is_array( $decoded ) ? $decoded : null; } if ( is_object( $node ) ) { $node = (array) $node; } if ( ! is_array( $node ) || ! array_key_exists( $step, $node ) ) { return null; } $node = $node[ $step ]; } return $node; } private static function meta_raw( $kind, $id, $key ) { if ( null !== self::$prefetch ) { return self::$prefetch[ $kind ][ $id ][ $key ] ?? null; } return metadata_exists( $kind, $id, $key ) ? get_metadata( $kind, $id, $key, true ) : null; } private static function compare( $have, $want, $op ) { if ( in_array( $op, array( '<', '<=', '>', '>=' ), true ) ) { $a = self::number( is_string( $have ) ? $have : ( is_scalar( $have ) ? $have + 0 : null ) ); $b = self::number( $want ); if ( null === $a || null === $b ) { return false; } switch ( $op ) { case '<': return $a < $b; case '<=': return $a <= $b; case '>': return $a > $b; default: return $a >= $b; } } $text = self::lower( (string) $have ); $want = self::lower( $want ); if ( '' === $want ) { return false; } if ( 'contains' === $op || 'not_contains' === $op ) { $hit = false !== strpos( $text, $want ); return 'contains' === $op ? $hit : ! $hit; } $a = self::number( is_string( $have ) ? $have : (string) $have ); $b = self::number( $want ); $same = ( null !== $a && null !== $b ) ? abs( $a - $b ) < 1e-9 : $text === $want; if ( '=' === $op ) { return $same; } return '!=' === $op ? ! $same : false; } private static function lower( $s ) { $s = trim( (string) $s ); return function_exists( 'mb_strtolower' ) ? mb_strtolower( $s, 'UTF-8' ) : strtolower( $s ); } public static function column_ok() { if ( null === self::$column ) { global $wpdb; $t = $wpdb->prefix . 'aieo_seo_posts'; $prev = $wpdb->suppress_errors( true ); self::$column = (bool) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = %s', $t, 'sitemap' ) ); $wpdb->suppress_errors( $prev ); } return self::$column; } public static function store( $object_type, $object_id, $flag, $row = null ) { if ( ! self::column_ok() ) { return false; } global $wpdb; $t = $wpdb->prefix . 'aieo_seo_posts'; $flag = max( 0, min( 2, (int) $flag ) ); if ( is_array( $row ) && array_key_exists( 'sitemap', $row ) && (int) $row['sitemap'] === $flag ) { return false; } $uncut = ( 2 === $flag && class_exists( 'AIEO_SEO_Sitemap_Priority' ) && AIEO_SEO_Sitemap_Priority::columns_ok() ) ? ', sitemap_cut = 0' : ''; $changed = (bool) $wpdb->query( $wpdb->prepare( "UPDATE `{$t}` SET sitemap = %d{$uncut} WHERE object_type = %s AND object_id = %d AND sitemap <> %d", $flag, (string) $object_type, (int) $object_id, $flag ) ); if ( $changed && class_exists( 'AIEO_SEO_Store' ) ) { AIEO_SEO_Store::forget( $object_type, $object_id ); } return $changed; } public static function refresh( $object_type, $object_id, $kind = '' ) { return self::store( $object_type, $object_id, self::decide( $object_type, $object_id, $kind ) ); } public static function apply_batch( $last_id, $limit = 1000 ) { global $wpdb; $t = $wpdb->prefix . 'aieo_seo_posts'; $rows = self::column_ok() ? (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, object_type, object_id, sitemap FROM `{$t}` WHERE id > %d ORDER BY id ASC LIMIT %d", (int) $last_id, max( 1, (int) $limit ) ), ARRAY_A ) : array(); $ids = array( 'post' => array(), 'term' => array(), ); $kinds = array(); $types = array(); foreach ( $rows as $row ) { $type = (string) $row['object_type']; if ( ! isset( $kinds[ $type ] ) ) { $kinds[ $type ] = self::kind( $type ); } if ( '' !== $kinds[ $type ] ) { $ids[ $kinds[ $type ] ][] = (int) $row['object_id']; $types[ $kinds[ $type ] ][ $type ] = true; } } $uses = self::uses(); self::$prefetch = array( 'post' => self::prefetch( 'post', $ids['post'], $uses['keys']['post'] ), 'term' => self::prefetch( 'term', $ids['term'], $uses['keys']['term'] ), ); if ( $ids['post'] && $uses['posts'] ) { _prime_post_caches( $ids['post'], false, false ); } if ( $ids['post'] && $uses['terms'] ) { update_object_term_cache( $ids['post'], array_keys( $types['post'] ?? array() ) ); } if ( $ids['term'] && $uses['term_rows'] ) { _prime_term_caches( $ids['term'], false ); } $changed = 0; try { foreach ( $rows as $row ) { $type = (string) $row['object_type']; if ( '' === $kinds[ $type ] ) { continue; } if ( self::store( $type, (int) $row['object_id'], self::decide( $type, (int) $row['object_id'], $kinds[ $type ] ), $row ) ) { ++$changed; } } } finally { self::$prefetch = null; } $count = count( $rows ); return array( 'last_id' => $count ? (int) $rows[ $count - 1 ]['id'] : (int) $last_id, 'rows' => $count, 'changed' => $changed, 'done' => $count < max( 1, (int) $limit ), ); } private static function uses() { $out = array( 'keys' => array( 'post' => array( self::META => true ), 'term' => array( self::META => true ), ), 'posts' => false, 'terms' => false, 'term_rows' => false, ); $walk = static function ( array $tree, $kind ) use ( &$walk, &$out ) { foreach ( (array) ( $tree['conditions'] ?? array() ) as $c ) { if ( isset( $c['conditions'] ) ) { $walk( (array) $c, $kind ); continue; } $field = (string) ( $c['field'] ?? '' ); if ( 'meta' === $field ) { $key = (string) ( $c['key'] ?? '' ); $out['keys'][ $kind ][ $key ] = true; $out['keys'][ $kind ][ strtok( $key, '.' ) ] = true; } elseif ( 'term' === $field ) { $out['terms'] = true; } elseif ( 'post' === $kind && in_array( $field, array( 'age', 'slug', 'parent' ), true ) ) { $out['posts'] = true; } elseif ( 'term' === $kind && in_array( $field, array( 'slug', 'count', 'parent' ), true ) ) { $out['term_rows'] = true; } } }; foreach ( self::settings()['rules'] as $rule ) { $walk( (array) $rule['when'], substr( (string) $rule['target'], 0, 4 ) ); } $out['keys']['post'] = array_keys( $out['keys']['post'] ); $out['keys']['term'] = array_keys( $out['keys']['term'] ); return $out; } private static function prefetch( $kind, array $ids, array $keys ) { $out = array(); if ( ! $ids || ! $keys ) { return $out; } global $wpdb; $table = 'term' === $kind ? $wpdb->termmeta : $wpdb->postmeta; $column = 'term' === $kind ? 'term_id' : 'post_id'; $ids = array_map( 'intval', $ids ); $sql = "SELECT {$column} AS id, meta_key, meta_value FROM {$table} WHERE {$column} IN (" . implode( ',', $ids ) . ') AND meta_key IN (' . implode( ',', array_fill( 0, count( $keys ), '%s' ) ) . ') ORDER BY meta_id ASC'; foreach ( (array) $wpdb->get_results( $wpdb->prepare( $sql, $keys ), ARRAY_A ) as $m ) { $id = (int) $m['id']; if ( ! isset( $out[ $id ] ) || ! array_key_exists( $m['meta_key'], $out[ $id ] ) ) { $out[ $id ][ $m['meta_key'] ] = maybe_unserialize( $m['meta_value'] ); } } return $out; } public static function meta_changed( $meta_id, $object_id, $meta_key ) { if ( self::META === $meta_key ) { self::refresh_item( current_filter(), (int) $object_id ); } } public static function meta_deleted( $meta_ids, $object_id, $meta_key ) { if ( self::META === $meta_key && (int) $object_id > 0 ) { self::refresh_item( current_filter(), (int) $object_id ); } } private static function refresh_item( $hook, $object_id ) { if ( false !== strpos( (string) $hook, '_term_meta' ) ) { $term = get_term( $object_id ); if ( $term && ! is_wp_error( $term ) ) { self::refresh( $term->taxonomy, $object_id, 'term' ); } return; } $type = get_post_type( $object_id ); if ( $type ) { self::refresh( $type, $object_id, 'post' ); } } public static function targets() { $out = array(); foreach ( get_post_types( array( 'public' => true ), 'objects' ) as $name => $obj ) { if ( in_array( $name, array( 'attachment', 'revision', 'nav_menu_item' ), true ) ) { continue; } $out[ 'post:' . $name ] = (string) $obj->labels->name; } foreach ( get_taxonomies( array( 'public' => true ), 'objects' ) as $name => $obj ) { if ( 'post_format' === $name ) { continue; } $out[ 'term:' . $name ] = sprintf( __( '%s (archive pages)', 'ai-eshop-optimizer' ), (string) $obj->labels->name ); } return $out; } }