Skip to content
Open
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
87e2a3b
feat(content-gate): add Block_Visibility class skeleton
dkoo Apr 7, 2026
4b2c0f2
test(content-gate): complete Block_Visibility hook coverage
dkoo Apr 7, 2026
bce2306
feat(content-gate): implement render_block fast path
dkoo Apr 7, 2026
e3920bb
test(content-gate): add is_admin fast path coverage
dkoo Apr 7, 2026
4479ff3
feat(content-gate): implement registration rule evaluation
dkoo Apr 7, 2026
a066381
style(content-gate): remove trailing whitespace in Block_Visibility t…
dkoo Apr 7, 2026
c572a67
test(content-gate): add access rule evaluation and caching tests
dkoo Apr 8, 2026
fe6fbe5
feat(content-gate): implement block visibility render filter
dkoo Apr 8, 2026
2dd68d6
feat(content-gate): register block attributes server-side
dkoo Apr 8, 2026
ea4eb67
feat(content-gate): enqueue block visibility editor assets
dkoo Apr 8, 2026
39954f5
fix(content-gate): use edit_others_posts cap and strip callbacks from…
dkoo Apr 8, 2026
ee8e3d0
feat(content-gate): add block visibility JS entry and attribute regis…
dkoo Apr 8, 2026
b2c8ea2
feat(content-gate): implement block visibility Inspector panel
dkoo Apr 8, 2026
9b6b327
feat(content-gate): add AccessRuleValueControl for block visibility p…
dkoo Apr 8, 2026
28a509f
fix(content-gate): handle is_boolean rules, use config.placeholder, f…
dkoo Apr 8, 2026
4b725c5
test(content-gate): add JS unit tests for block visibility attribute …
dkoo Apr 8, 2026
1af1acb
style: tweak styles for Access Control block visibility panel
dkoo Apr 8, 2026
1ea2dc8
refactor(content-gate): replace any with proper types in block-visibi…
dkoo Apr 8, 2026
323b7aa
refactor: prettier formatting
dkoo Apr 8, 2026
553a4ca
fix(content-gate): address code review issues in block visibility
dkoo Apr 8, 2026
1c141f2
fix(content-gate): address Copilot review feedback on block visibility
dkoo Apr 8, 2026
f7f2f15
fix: allow editors to bypass access requirements
dkoo Apr 8, 2026
ec7005b
test(content-gate): add editor front-end bypass and restrict tests
dkoo Apr 8, 2026
f3dccb5
refactor: allow the blocks that can get access rules to be filtered
dkoo Apr 8, 2026
e822588
docs: update docblock
dkoo Apr 8, 2026
2b50ec8
refactor: apply filter to all instances of $target_blocks
dkoo Apr 8, 2026
ff4ec4d
feat(content-gate): add gate mode to per-block access control
dkoo Apr 8, 2026
a0ee1ea
style: tweak UI in Access Control panel
dkoo Apr 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
212 changes: 212 additions & 0 deletions includes/content-gate/class-block-visibility.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
<?php
/**
* Newspack Block Access Control.
*
* Per-block visibility control based on content restriction rules.
*
* @package Newspack
*/

namespace Newspack;

defined( 'ABSPATH' ) || exit;

/**
* Block_Visibility class.
*/
class Block_Visibility {

/**
* Initialize hooks.
*/
public static function init() {
add_filter( 'render_block', [ __CLASS__, 'filter_render_block' ], 10, 2 );
add_action( 'enqueue_block_editor_assets', [ __CLASS__, 'enqueue_block_editor_assets' ] );
add_filter( 'register_block_type_args', [ __CLASS__, 'register_block_type_args' ], 10, 2 );
}

/**
* Filter rendered block output based on access control attributes.
*
* @param string $block_content Rendered block HTML.
* @param array $block Block data.
* @return string
*/
public static function filter_render_block( $block_content, $block ) {
$target_blocks = [ 'core/group', 'core/stack', 'core/row' ];
if ( ! in_array( $block['blockName'] ?? '', $target_blocks, true ) ) {
return $block_content;
}

if ( is_admin() ) {
return $block_content;
}

$rules = $block['attrs']['newspackAccessControlRules'] ?? [];

$has_registration = ! empty( $rules['registration']['active'] );
$has_access_rules = ! empty( $rules['custom_access']['active'] )
&& ! empty( $rules['custom_access']['access_rules'] );

if ( ! $has_registration && ! $has_access_rules ) {
return $block_content;
}

$visibility = $block['attrs']['newspackAccessControlVisibility'] ?? 'visible';
$user_id = get_current_user_id();
$user_matches = self::evaluate_rules_for_user( $rules, $user_id );

if ( 'visible' === $visibility ) {
return $user_matches ? $block_content : '';
}
// 'hidden'
return $user_matches ? '' : $block_content;
}

/**
* Register block attributes server-side for the three target block types.
*
* @param array $args Block type arguments.
* @param string $block_type Block type name.
* @return array
*/
public static function register_block_type_args( $args, $block_type ) {
$target_blocks = [ 'core/group', 'core/stack', 'core/row' ];
if ( ! in_array( $block_type, $target_blocks, true ) ) {
return $args;
}

$args['attributes'] = array_merge(
$args['attributes'] ?? [],
[
'newspackAccessControlVisibility' => [
'type' => 'string',
'default' => 'visible',
],
'newspackAccessControlRules' => [
'type' => 'object',
'default' => new \stdClass(),
],
]
);
return $args;
}

/**
* Enqueue block editor assets.
*/
public static function enqueue_block_editor_assets() {
if ( ! current_user_can( 'edit_others_posts' ) ) {
return;
}

$available_post_types = array_column(
Content_Restriction_Control::get_available_post_types(),
'value'
);
if ( ! in_array( get_post_type(), $available_post_types, true ) ) {
return;
}

$asset_file = dirname( NEWSPACK_PLUGIN_FILE ) . '/dist/content-gate-block-visibility.asset.php';
if ( ! file_exists( $asset_file ) ) {
return;
}
$asset = require $asset_file;

wp_enqueue_script(
'newspack-content-gate-block-visibility',
Newspack::plugin_url() . '/dist/content-gate-block-visibility.js',
$asset['dependencies'],
$asset['version'],
true
);

wp_localize_script(
'newspack-content-gate-block-visibility',
'newspackBlockVisibility',
[
'available_access_rules' => array_map(
function( $rule ) {
unset( $rule['callback'] );
return $rule;
},
Access_Rules::get_access_rules()
),
]
);
}

/**
* Per-request cache: keyed by "{user_id}:{md5(rules)}".
*
* @var bool[]
*/
private static $rules_match_cache = [];

/**
* Reset the per-request cache. Used in unit tests only.
*/
public static function reset_cache_for_tests() {
self::$rules_match_cache = [];
}

/**
* Public wrapper for tests. Calls evaluate_rules_for_user().
*
* @param array $rules Rules array.
* @param int $user_id User ID.
* @return bool
*/
public static function evaluate_rules_for_user_public( $rules, $user_id ) {
return self::evaluate_rules_for_user( $rules, $user_id );
}

/**
* Evaluate whether a user matches the block's access rules.
*
* @param array $rules Parsed newspackAccessControlRules attribute.
* @param int $user_id User ID (0 for logged-out).
* @return bool True if user matches (should be treated as "matching reader").
*/
private static function evaluate_rules_for_user( $rules, $user_id ) {
$cache_key = $user_id . ':' . md5( wp_json_encode( $rules ) );
if ( isset( self::$rules_match_cache[ $cache_key ] ) ) {
return self::$rules_match_cache[ $cache_key ];
}

$result = self::compute_rules_match( $rules, $user_id );
self::$rules_match_cache[ $cache_key ] = $result;
return $result;
}

/**
* Compute whether a user matches the block's access rules (uncached).
*
* @param array $rules Parsed newspackAccessControlRules attribute.
* @param int $user_id User ID (0 for logged-out).
* @return bool
*/
private static function compute_rules_match( $rules, $user_id ) {
$registration = $rules['registration'] ?? [];
$custom_access = $rules['custom_access'] ?? [];

$registration_passes = true;
if ( ! empty( $registration['active'] ) ) {
if ( ! $user_id ) {
$registration_passes = false;
} elseif ( ! empty( $registration['require_verification'] ) ) {
$registration_passes = (bool) get_user_meta( $user_id, Reader_Activation::EMAIL_VERIFIED, true );
}
}

$access_passes = true;
if ( ! empty( $custom_access['active'] ) && ! empty( $custom_access['access_rules'] ) ) {
$access_passes = Access_Rules::evaluate_rules( $custom_access['access_rules'], $user_id );
}

// AND logic: both must pass when both are configured.
return $registration_passes && $access_passes;
}
}
Block_Visibility::init();
1 change: 1 addition & 0 deletions includes/content-gate/class-content-gate.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ public static function init() {
include __DIR__ . '/class-institution.php';
include __DIR__ . '/class-user-gate-access.php';
include __DIR__ . '/class-premium-newsletters.php';
include __DIR__ . '/class-block-visibility.php';
}

/**
Expand Down
73 changes: 73 additions & 0 deletions src/content-gate/editor/block-visibility.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* Tests for block-visibility attribute registration filter.
*/

/**
* Capture callbacks registered via addFilter, keyed by namespace.
*/
const registeredFilters: Record< string, ( settings: any, name: string ) => any > = {};

Check warning on line 8 in src/content-gate/editor/block-visibility.test.ts

View workflow job for this annotation

GitHub Actions / lint-js-scss / Lint JS & SCSS files

Unexpected any. Specify a different type

Check warning on line 8 in src/content-gate/editor/block-visibility.test.ts

View workflow job for this annotation

GitHub Actions / lint-js-scss / Lint JS & SCSS files

Unexpected any. Specify a different type

jest.mock( '@wordpress/hooks', () => ( {
addFilter: jest.fn( ( _hook: string, namespace: string, callback: ( settings: any, name: string ) => any ) => {

Check warning on line 11 in src/content-gate/editor/block-visibility.test.ts

View workflow job for this annotation

GitHub Actions / lint-js-scss / Lint JS & SCSS files

Unexpected any. Specify a different type

Check warning on line 11 in src/content-gate/editor/block-visibility.test.ts

View workflow job for this annotation

GitHub Actions / lint-js-scss / Lint JS & SCSS files

Unexpected any. Specify a different type
registeredFilters[ namespace ] = callback;
} ),
} ) );

jest.mock( '@wordpress/compose', () => ( {
createHigherOrderComponent: jest.fn( ( fn: any ) => fn ),

Check warning on line 17 in src/content-gate/editor/block-visibility.test.ts

View workflow job for this annotation

GitHub Actions / lint-js-scss / Lint JS & SCSS files

Unexpected any. Specify a different type
} ) );
jest.mock( '@wordpress/block-editor', () => ( { InspectorControls: () => null } ) );
jest.mock( '@wordpress/components', () => ( {} ) );
jest.mock( '@wordpress/i18n', () => ( { __: ( s: string ) => s } ) );
jest.mock( '@wordpress/element', () => ( {
useState: jest.fn( ( v: any ) => [ v, jest.fn() ] ),

Check warning on line 23 in src/content-gate/editor/block-visibility.test.ts

View workflow job for this annotation

GitHub Actions / lint-js-scss / Lint JS & SCSS files

Unexpected any. Specify a different type
useEffect: jest.fn(),
} ) );
jest.mock( '@wordpress/api-fetch', () => jest.fn() );

// Importing the module triggers the addFilter side effects.
require( './block-visibility' );

const attributeFilter = registeredFilters[ 'newspack-plugin/block-visibility/attributes' ];

describe( 'block-visibility attribute registration', () => {
it( 'adds attributes to core/group', () => {
const result = attributeFilter( { attributes: {} }, 'core/group' );
expect( result.attributes ).toHaveProperty( 'newspackAccessControlVisibility' );
expect( result.attributes ).toHaveProperty( 'newspackAccessControlRules' );
} );

it( 'adds attributes to core/stack', () => {
const result = attributeFilter( { attributes: {} }, 'core/stack' );
expect( result.attributes ).toHaveProperty( 'newspackAccessControlVisibility' );
expect( result.attributes ).toHaveProperty( 'newspackAccessControlRules' );
} );

it( 'adds attributes to core/row', () => {
const result = attributeFilter( { attributes: {} }, 'core/row' );
expect( result.attributes ).toHaveProperty( 'newspackAccessControlVisibility' );
expect( result.attributes ).toHaveProperty( 'newspackAccessControlRules' );
} );

it( 'does not modify non-target blocks', () => {
const settings = { attributes: { align: { type: 'string' } } };
const result = attributeFilter( settings, 'core/paragraph' );
expect( result ).toBe( settings );
} );

it( 'newspackAccessControlVisibility defaults to visible', () => {
const result = attributeFilter( { attributes: {} }, 'core/group' );
expect( result.attributes.newspackAccessControlVisibility.default ).toBe( 'visible' );
} );

it( 'newspackAccessControlRules defaults to empty object', () => {
const result = attributeFilter( { attributes: {} }, 'core/group' );
expect( result.attributes.newspackAccessControlRules.default ).toEqual( {} );
} );

it( 'preserves existing attributes on target blocks', () => {
const result = attributeFilter( { attributes: { align: { type: 'string' } } }, 'core/group' );
expect( result.attributes ).toHaveProperty( 'align' );
expect( result.attributes ).toHaveProperty( 'newspackAccessControlVisibility' );
} );
} );
Loading
Loading