Component name => sha256 hash. Empty if the post does not exist. */ public static function compute_components( $post_id ) { clean_post_cache( $post_id ); $post = get_post( $post_id ); if ( ! $post ) { return array(); } $payload = array( 'post_title' => $post->post_title, 'post_content' => $post->post_content, 'post_excerpt' => $post->post_excerpt, 'post_author' => (string) $post->post_author, 'post_date' => $post->post_date, 'post_parent' => (string) $post->post_parent, ); $taxonomies = get_object_taxonomies( $post->post_type ); sort( $taxonomies ); $terms = array(); foreach ( $taxonomies as $taxonomy ) { $ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); if ( ! is_wp_error( $ids ) && ! empty( $ids ) ) { $ids = array_map( 'intval', $ids ); sort( $ids ); $terms[ $taxonomy ] = $ids; } } $payload['terms'] = $terms; $excluded = self::excluded_meta_keys(); $meta = get_post_meta( $post->ID ); $clean = array(); if ( is_array( $meta ) ) { ksort( $meta ); foreach ( $meta as $key => $values ) { if ( in_array( $key, $excluded, true ) ) { continue; } sort( $values ); $clean[ $key ] = $values; } } $payload['meta'] = $clean; /** * Filter the integrity payload, for example to add product data. * * @param array $payload Payload components. * @param \WP_Post $post Post. */ $payload = apply_filters( 'slugh_integrity_payload', $payload, $post ); $components = array(); foreach ( $payload as $name => $value ) { $json = wp_json_encode( $value ); $components[ $name ] = hash( 'sha256', false === $json ? maybe_serialize( $value ) : $json ); } return $components; } /** * Combine component hashes into one integrity hash. * * @param array $components Components from compute_components(). * @return string */ public static function combine( array $components ) { if ( empty( $components ) ) { return ''; } ksort( $components ); return hash( 'sha256', (string) wp_json_encode( $components ) ); } /** * Compute the integrity hash for a post. * * @param int $post_id Post ID. * @return string */ public static function compute_post_hash( $post_id ) { return self::combine( self::compute_components( $post_id ) ); } /** * List the component names that differ between two snapshots. * * @param array $before Components before. * @param array $after Components after. * @return string[] */ public static function diff( array $before, array $after ) { $changed = array(); foreach ( array_unique( array_merge( array_keys( $before ), array_keys( $after ) ) ) as $key ) { if ( ! isset( $before[ $key ], $after[ $key ] ) || ! hash_equals( $before[ $key ], $after[ $key ] ) ) { $changed[] = $key; } } return $changed; } /** * Verify pre-update and post-update hashes match. * * @param string $pre_hash Pre-update hash. * @param string $post_hash Post-update hash. * @return bool */ public static function verify( $pre_hash, $post_hash ) { if ( empty( $pre_hash ) || empty( $post_hash ) ) { return false; } return hash_equals( $pre_hash, $post_hash ); } }