-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathclass-access-rules.php
More file actions
474 lines (440 loc) · 15.4 KB
/
Copy pathclass-access-rules.php
File metadata and controls
474 lines (440 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
<?php
/**
* Newspack Content Gate Access Rules
*
* @package Newspack
*/
namespace Newspack;
use Newspack\WooCommerce_Connection;
/**
* Main class.
*/
class Access_Rules {
const META_KEY = 'access_rules';
/**
* Registered rules.
*
* @var array
*/
private static $rules = [];
/**
* Initialize hooks.
*/
public static function init() {
add_action( 'init', [ __CLASS__, 'register_default_rules' ] );
}
/**
* Register a rule.
*
* @param array $config {
* The rule configuration.
*
* @type string $id The rule ID.
* @type string $name The rule name.
* @type string $description The rule description.
* @type mixed $default The rule default value.
* @type array $options The rule options.
* @type callable $callback The rule callback.
* @type bool $is_boolean Whether the rule is a boolean rule.
* @type bool $supports_anonymous Whether the rule's callback can evaluate access for
* a logged-out visitor (`user_id = 0`). Defaults to
* false — `evaluate_rule` short-circuits to false for
* anonymous users on rules that don't opt in. Rules
* that opt in are responsible for cache-safety
* (e.g. only running per-IP logic when the page is
* already uncached).
* }
*
* @return void|\WP_Error
*/
public static function register_rule( $config ) {
if ( ! isset( $config['id'] ) ) {
return new \WP_Error( 'invalid_rule_id', __( 'Rule ID is required.', 'newspack' ) );
}
if ( isset( self::$rules[ $config['id'] ] ) ) {
return new \WP_Error( 'rule_already_registered', __( 'Rule already registered.', 'newspack' ) );
}
if ( ! isset( $config['callback'] ) ) {
return new \WP_Error( 'invalid_rule_callback', __( 'Rule callback is required.', 'newspack' ) );
}
if ( ! is_callable( $config['callback'] ) ) {
return new \WP_Error( 'invalid_rule_callback', __( 'Rule callback is not callable.', 'newspack' ) );
}
$rule = wp_parse_args(
$config,
[
'name' => ucwords( str_replace( '_', ' ', $config['id'] ) ),
'description' => '',
'default' => ! empty( $config['options'] ) ? [] : '',
'options' => [],
'is_boolean' => false,
]
);
self::$rules[ $rule['id'] ] = $rule;
}
/**
* Get all registered rules.
*
* @return array The registered rules.
*/
public static function get_registered_rules() {
return self::$rules;
}
/**
* Register the default access rules.
*/
public static function register_default_rules() {
$rules = [
'subscription' => [
'name' => __( 'Active subscription', 'newspack-plugin' ),
'description' => __( 'Requires an active subscription to selected products.', 'newspack-plugin' ),
'options' => [ __CLASS__, 'get_subscription_products_options' ],
'callback' => [ __CLASS__, 'has_active_subscription' ],
],
'email_domain' => [
'name' => __( 'Whitelisted email domain', 'newspack-plugin' ),
'description' => __( 'Only allow readers with specific email domains.', 'newspack-plugin' ),
'placeholder' => __( 'example.com,another.com', 'newspack-plugin' ),
'callback' => [ __CLASS__, 'is_email_domain_whitelisted' ],
],
'reader_data' => [
'name' => __( 'Reader data', 'newspack-plugin' ),
'description' => __( 'Set custom conditions based on reader data key/value pairs.', 'newspack-plugin' ),
'callback' => [ __CLASS__, 'has_reader_data' ],
],
'institution' => [
'name' => __( 'Institutional access', 'newspack-plugin' ),
'description' => __( 'Grant access to readers from selected institutions.', 'newspack-plugin' ),
'options' => [ Institution::class, 'get_options' ],
'callback' => [ Institution::class, 'evaluate' ],
'supports_anonymous' => true,
],
];
foreach ( $rules as $id => $rule ) {
self::register_rule( array_merge( $rule, [ 'id' => $id ] ) );
}
}
/**
* Get access rules.
*
* @return array The access rules.
*/
public static function get_access_rules() {
return array_map(
function( $rule ) {
if ( ! empty( $rule['options'] ) && is_callable( $rule['options'] ) ) {
$rule['options'] = call_user_func( $rule['options'] );
}
return $rule;
},
self::$rules
);
}
/**
* Get the access rule by slug.
*
* @param string $slug Rule slug.
*
* @return array|null Rule config or null if not found.
*/
public static function get_rule( $slug ) {
return self::$rules[ $slug ] ?? null;
}
/**
* Evaluate whether the given or current user can bypass the given access rule.
*
* @param string $rule_slug Access rule slug.
* @param mixed $args Additional arguments for the access rule callback.
* @param int|null $user_id User ID. If not given, checks the current user.
*
* @return bool
*/
public static function evaluate_rule( $rule_slug, $args = null, $user_id = null ) {
$rule = self::get_rule( $rule_slug );
// Rule doesn't exist or lacks a callback function to execute, don't block access for it.
if ( empty( $rule['callback'] ) ) {
return true;
}
// If evaluating for the current user, they must be logged in (unless the rule supports anonymous evaluation).
$user_id = $user_id ?? \get_current_user_id();
if ( ! $user_id && empty( $rule['supports_anonymous'] ) ) {
return false;
}
// Access rule must have a callable callback function.
if ( ! is_callable( $rule['callback'] ) ) {
return false;
}
return call_user_func( $rule['callback'], $user_id, $args );
}
/**
* Determine whether the gate's custom_access rules grant access to an
* anonymous (logged-out) visitor.
*
* Only rules that (a) declare `supports_anonymous` and (b) have a populated
* `value` are considered. An unpopulated rule is treated as "not configured"
* rather than "matches everyone" — Access_Rules's underlying evaluators
* return true for empty values as the rule's own no-constraint semantics,
* which is correct for the rule in isolation but must not silently bypass
* registration here.
*
* Groups containing any non-eligible rule are dropped (the AND-within-group
* semantics would force the group to fail for an anonymous visitor anyway,
* since non-anonymous rules return false for `user_id = 0`).
*
* @param array $access_rules Custom access rules in grouped or flat format.
*
* @return bool True if a populated, anonymous-capable rule grants access.
*/
public static function evaluate_anonymous_rules( $access_rules ) {
if ( empty( $access_rules ) ) {
return false;
}
$eligible_groups = [];
foreach ( self::normalize_rules( $access_rules ) as $group ) {
if ( empty( $group ) || ! is_array( $group ) ) {
continue;
}
$group_eligible = true;
foreach ( $group as $rule ) {
// `empty()` is acceptable for `value` while the only `supports_anonymous` rule
// (`institution`) stores an array of post IDs — empty array means "no institutions
// selected." If a future anonymous-capable rule uses a falsy-but-valid scalar (e.g.
// `0`, `'0'`, `false`), tighten this check accordingly.
if ( ! isset( $rule['slug'] ) || empty( $rule['value'] ) ) {
$group_eligible = false;
break;
}
$rule_def = self::get_rule( $rule['slug'] );
if ( empty( $rule_def['supports_anonymous'] ) ) {
$group_eligible = false;
break;
}
}
if ( $group_eligible ) {
$eligible_groups[] = $group;
}
}
if ( empty( $eligible_groups ) ) {
return false;
}
return self::evaluate_rules( $eligible_groups, 0 );
}
/**
* Evaluate access rules with OR logic between groups and AND logic within groups.
*
* Rules structure: [ [ rule1, rule2 ], [ rule3, rule4 ] ]
* - Groups use OR logic: reader must pass at least one group
* - Rules within a group use AND logic: reader must pass all rules in the group
*
* @param array $access_rules The access rules (array of groups, each group is an array of rules).
* @param int $user_id Optional. User ID to evaluate rules for. Defaults to current user.
*
* @return bool True if access is granted, false if restricted.
*/
public static function evaluate_rules( $access_rules, $user_id = null ) {
if ( empty( $access_rules ) ) {
return true;
}
// Normalize legacy flat rules structure to grouped format.
$access_rules = self::normalize_rules( $access_rules );
// Evaluate each group with OR logic - if any group passes, grant access.
foreach ( $access_rules as $group ) {
if ( self::evaluate_rules_group( $group, $user_id ) ) {
return true;
}
}
// No group passed - restrict access.
return false;
}
/**
* Evaluate a single group of access rules with AND logic.
*
* @param array $group Array of rules in the group.
* @param int $user_id Optional. User ID to evaluate rules for. Defaults to current user.
*
* @return bool True if all rules in the group pass, false otherwise.
*/
private static function evaluate_rules_group( $group, $user_id = null ) {
if ( empty( $group ) || ! is_array( $group ) ) {
return true;
}
foreach ( $group as $rule ) {
if ( ! isset( $rule['slug'] ) ) {
continue;
}
if ( ! self::evaluate_rule( $rule['slug'], $rule['value'] ?? null, $user_id ) ) {
return false;
}
}
return true;
}
/**
* Normalize access rules to grouped format.
*
* Converts flat rules [ rule1, rule2 ] to grouped format [ [ rule1 ], [ rule2 ] ],
* where each rule is its own group (OR logic). Already grouped rules are left as-is.
*
* @param array $access_rules The access rules.
*
* @return array Normalized access rules in grouped format.
*/
public static function normalize_rules( $access_rules ) {
if ( empty( $access_rules ) ) {
return [];
}
// Check if already in grouped format (array of arrays with rules).
// A grouped format has arrays as first-level elements.
// A flat format has rule objects (with 'slug' key) as first-level elements.
$first_element = reset( $access_rules );
if ( is_array( $first_element ) && ! isset( $first_element['slug'] ) ) {
// Already in grouped format.
return $access_rules;
}
// Convert flat format to OR logic: each rule becomes its own group.
return array_map(
function ( $rule ) {
return [ $rule ];
},
$access_rules
);
}
/**
* Get subscriptions eligible for access rules.
*
* @return array Active subscription IDs.
*/
public static function get_subscription_products_options() {
if ( ! function_exists( 'wc_get_products' ) ) {
return [];
}
$products = \wc_get_products(
[
'type' => [ 'subscription', 'variable-subscription' ],
'limit' => -1,
]
);
$options = [];
foreach ( $products as $product ) {
$options[] = [
'label' => $product->get_name(),
'value' => $product->get_id(),
];
}
return $options;
}
/**
* Whether the user has an active subscription for one of the given products.
* Also checks if the user is a member of a group subscription with the required products.
*
* Note: `$strict` only constrains the built-in ownership / group-membership checks.
* The `newspack_access_rules_has_active_subscription` filter is always applied and
* its return value is the final result, so a third-party filter callback can grant
* access even when `$strict` is true. Filter authors should opt in to the 4th `$strict`
* arg (`accepted_args` >= 4) and respect it — e.g., short-circuit and return
* `$has_subscription` unchanged when `$strict` is true and the access claim isn't
* strictly an owned subscription. Otherwise callers using `$strict` to distinguish
* owner-vs-member access (e.g., `Content_Gate` source labels) may misclassify
* filter-granted access as local ownership.
*
* @param int $user_id User ID.
* @param array $product_ids Required product IDs.
* @param bool $strict If true, only consider active subscriptions owned by $user_id (ignore group subscription memberships).
* @return bool
*/
public static function has_active_subscription( $user_id, $product_ids, $strict = false ) {
$has_subscription = false;
// Check user's own subscriptions.
if ( ! empty( WooCommerce_Connection::get_active_subscriptions_for_user( $user_id, $product_ids ) ) ) {
$has_subscription = true;
}
// Check group subscriptions the user is a member of.
if ( ! $strict && ! $has_subscription && function_exists( 'wcs_get_subscription' ) ) {
$group_subscriptions = Group_Subscription::get_group_subscriptions_for_user( $user_id );
foreach ( $group_subscriptions as $subscription ) {
if ( ! $subscription || ! $subscription->has_status( WooCommerce_Connection::ACTIVE_SUBSCRIPTION_STATUSES ) ) {
continue;
}
// If no product filter, any active group subscription grants access.
if ( empty( $product_ids ) ) {
$has_subscription = true;
break;
}
// Check if the subscription has any of the required products.
foreach ( $product_ids as $product_id ) {
if ( $subscription->has_product( $product_id ) ) {
$has_subscription = true;
break 2;
}
}
}
}
/**
* Filters whether a user has an active subscription for the given products.
*
* @param bool $has_subscription Whether the user has an active subscription.
* @param int $user_id User ID.
* @param array $product_ids Required product IDs.
* @param bool $strict If true, only consider active subscriptions owned by $user_id (ignore group subscription memberships).
*/
return apply_filters( 'newspack_access_rules_has_active_subscription', $has_subscription, $user_id, $product_ids, $strict );
}
/**
* Whether the user’s email address contains one of the given domains.
*
* @param int $user_id User ID.
* @param string $domains Comma-delimited list of domains.
* @return bool
*/
public static function is_email_domain_whitelisted( $user_id, $domains ) {
// If no domains are specified, allow access.
if ( empty( $domains ) ) {
return true;
}
$domains = str_replace( PHP_EOL, ',', $domains );
$domains = explode( ',', $domains );
$domains = array_map( 'trim', $domains );
$user = \get_userdata( $user_id );
if ( ! $user ) {
return false;
}
$email = $user->data->user_email;
if ( ! $email ) {
return false;
}
if ( Reader_Activation::is_reader_verified( $user ) === false ) {
return false;
}
$email_domain = substr( $email, strrpos( $email, '@' ) + 1 );
return in_array( $email_domain, $domains, true );
}
/**
* Determine reader data key-values the reader must have.
*
* @param int $user_id User ID.
* @param string $data Key-value pairs separate by semicolon.
*
* @return bool Whether the reader has the required data.
*/
public static function has_reader_data( $user_id, $data ) {
if ( empty( $data ) ) {
return true;
}
$data = explode( ';', $data );
$data = array_map( 'trim', $data );
$data = array_filter( $data );
$data = array_map(
function( $item ) {
return explode( '=', $item );
},
$data
);
$reader_data = Reader_Data::get_data( $user_id );
foreach ( $data as $item ) {
if ( ! isset( $reader_data[ $item[0] ] ) || $reader_data[ $item[0] ] !== $item[1] ) {
return false;
}
}
return true;
}
}
Access_Rules::init();