Repository navigation
Expand file tree
/
Copy pathNotice.php
More file actions
444 lines (378 loc) · 13.7 KB
/
Copy pathNotice.php
File metadata and controls
444 lines (378 loc) · 13.7 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
<?php
/**
* Admin notices: the opt-in prompt, deprecation warnings, and developer errors.
*
* @package Codexpert\PluginTracker
*/
namespace Codexpert\PluginTracker\Consent;
use Codexpert\PluginTracker\Config;
/**
* Reusable admin notices.
*
* The opt-in prompt is shipped rather than left to consumers because spec 10.4 requires it: every
* consumer hand-rolling their own consent UI means every consumer getting a chance to botch it,
* and a botched consent flow is what gets THEIR plugin pulled from WordPress.org.
*
* The prompt is honest by construction -- it names what is sent, links the full field list, and
* makes declining exactly as easy as accepting. A prompt that nags or pre-checks the box would
* defeat the purpose.
*/
class Notice {
/**
* How long a server-supplied notice lives when the server did not say, in seconds. Ninety days.
*
* There is no unbounded case. A notice with no expiry is one the server can never take back --
* `Tracker::apply()` can only ever set this option, so a message sent once outlives the release
* it warned about and every install keeps showing it.
*/
const NOTICE_TTL = 7776000;
/**
* Config.
*
* @var Config
*/
private $config;
/**
* Consent gate.
*
* @var Gate
*/
private $consent;
/**
* Constructor.
*
* @param Config $config Config.
* @param Gate $consent Consent gate.
*/
public function __construct( Config $config, Gate $consent ) {
$this->config = $config;
$this->consent = $consent;
}
/**
* Render whichever notice applies.
*
* @return void
*/
public function render() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
// The kill switch is checked before ANY output, server-supplied included. It used to sit
// below render_server_notice(), which meant a site that had switched the SDK off was still
// shown messages the SDK had fetched over the network.
if ( defined( 'CX_TRACKER_DISABLE' ) && CX_TRACKER_DISABLE ) {
return;
}
if ( $this->allowed( 'server' ) ) {
$this->render_server_notice();
}
// Only ask when the author has enabled telemetry, and only once -- an admin who declined
// is not asked again for this policy version.
if ( ! $this->config->enabled() || $this->consent->answered() ) {
return;
}
if ( ! $this->due() ) {
return;
}
if ( ! $this->allowed( 'prompt' ) ) {
return;
}
$this->render_prompt();
}
/**
* Render only the server-supplied notice. Network admin has no per-site consent to collect.
*
* @return void
*/
public function render_network() {
if ( ! current_user_can( 'manage_network_options' ) ) {
return;
}
if ( defined( 'CX_TRACKER_DISABLE' ) && CX_TRACKER_DISABLE ) {
return;
}
if ( $this->allowed( 'server' ) ) {
$this->render_server_notice();
}
}
/**
* May this notice be shown?
*
* The one way to keep the SDK and suppress its built-in UI. Without it a consumer rendering
* consent on their own settings screen had only `CX_TRACKER_DISABLE`, which also stops
* telemetry -- so "move the prompt" and "switch the product off" were the same switch.
*
* @param string $which 'prompt' or 'server'.
* @return bool
*/
private function allowed( $which ) {
if ( ! function_exists( 'apply_filters' ) ) {
return true;
}
/**
* Filter whether a built-in admin notice is rendered.
*
* @param bool $show Whether to render.
* @param string $which 'prompt' for the consent prompt, 'server' for a server-supplied notice.
* @param string $plugin Consumer plugin slug.
*/
return (bool) apply_filters( 'cx_tracker_show_notice', true, $which, $this->config->plugin() );
}
/**
* Has the author's delay elapsed on this site?
*
* The delay is an author's courtesy -- asking on a site's first day, before the plugin has done
* anything for anyone, is how a prompt gets dismissed without being read. It is deliberately the
* weakest of the gates: it postpones the question, it never withdraws it.
*
* **An absent stamp asks now rather than never.** A plugin that was already active when this SDK
* arrived has no activation to count from, and treating that as "not due yet" would leave those
* sites -- every existing install of an established plugin, which is most of them -- silently
* unasked forever, while the code reads as though consent were being collected.
*
* @return bool
*/
private function due() {
// Config floors this at CONSENT_AFTER_MIN, so there is no zero case to short-circuit.
$wait = $this->config->consent_after();
$since = (int) get_option( $this->config->option( 'activated' ) );
if ( $since < 1 ) {
return true;
}
// A clock moved backwards -- restored backup, corrected timezone, a host's NTP catching up --
// makes this difference negative, which must not become a delay nobody can wait out. Anything
// that cannot be read as elapsed time is treated as due.
$elapsed = time() - $since;
if ( $elapsed < 0 ) {
return true;
}
return $elapsed >= $wait;
}
/**
* User-facing prompt copy, filterable so a consumer can localise it.
*
* The SDK loads its OWN text domain (see I18n), so these strings are translated wherever a .mo
* for the site's locale has been placed under WP_LANG_DIR. None ships, so on most sites this
* filter is what changes the wording.
*
* This filter is the additional override, for a consumer who wants the prompt to match their
* own product's wording rather than merely translate it:
*
* add_filter( 'cx_tracker_notice_strings', function ( $s ) {
* $s['allow'] = __( 'Allow', 'my-plugin' );
* return $s;
* } );
*
* This matters beyond tidiness: the consent prompt is the one piece of UI a WordPress.org
* reviewer reads, and it has to be readable in the site's language.
*
* @return array
*/
private function strings() {
$defaults = array(
'intro' => __( 'can send anonymous usage data to help its developers decide what to build and which versions to support.', 'plugin-tracker-sdk' ),
// Says it is a beta, and says what that means for the reader rather than just labelling it.
// Issue #40 is "consent (opt-in beta)" and PLANS.md §11.E calls the programme a beta with
// "supported beta events" -- so what is collected can change, which is material to the
// decision being asked for. A bare "(beta)" badge would be decoration; this is the
// consequence.
'beta' => __( 'This is a beta programme: what is collected may change, and you will be asked again if it does.', 'plugin-tracker-sdk' ),
'sends' => __( 'It would send: an anonymous install ID, the plugin version, your WordPress and PHP versions, your site language, whether this is a multisite, and which features are used.', 'plugin-tracker-sdk' ),
'never' => __( 'It never sends your site address, email address, user accounts, or any content.', 'plugin-tracker-sdk' ),
'optional' => __( 'Nothing is sent unless you agree. You can change your mind at any time.', 'plugin-tracker-sdk' ),
'allow' => __( 'Allow', 'plugin-tracker-sdk' ),
'decline' => __( 'No thanks', 'plugin-tracker-sdk' ),
);
if ( ! function_exists( 'apply_filters' ) ) {
return $defaults;
}
/**
* Filter the consent prompt copy.
*
* @param array $defaults Default English strings.
* @param string $plugin Consumer plugin slug, so one consumer's filter cannot affect another's.
*/
$filtered = apply_filters( 'cx_tracker_notice_strings', $defaults, $this->config->plugin() );
if ( ! is_array( $filtered ) ) {
return $defaults;
}
// Merged over the defaults so a partial filter cannot blank a string, and cast at the point
// of use below.
return array_merge( $defaults, $filtered );
}
/**
* The opt-in prompt.
*
* @return void
*/
private function render_prompt() {
$action = admin_url( 'admin-post.php' );
$text = $this->strings();
$name = $this->config->name();
$plugin = $this->config->plugin();
$nonce_action = 'cx_tracker_consent_' . $plugin;
// See Feedback\Deactivation::render() for why this is __DIR__-relative and why views/ must
// stay out of .gitattributes' export-ignore list for the path to exist in a shipped copy.
include __DIR__ . '/../../views/consent/prompt.php';
}
/**
* A deprecation or advisory notice supplied by the ingestion response.
*
* This is the only channel that reaches a site running a years-old bundled copy of the SDK,
* because there is no composer update path (spec 10.2).
*
* @return void
*/
private function render_server_notice() {
$notice = get_option( $this->config->option( 'notice' ) );
if ( ! is_array( $notice ) || empty( $notice['message'] ) ) {
return;
}
$message = (string) $notice['message'];
$until = isset( $notice['until'] ) ? (int) $notice['until'] : 0;
// A row written before notices carried an expiry. Backfilled rather than deleted, which is
// what comparing against 0 would do.
if ( $until < 1 ) {
$until = time() + self::NOTICE_TTL;
$notice['until'] = $until;
update_option( $this->config->option( 'notice' ), $notice, false );
}
if ( time() > $until ) {
delete_option( $this->config->option( 'notice' ) );
return;
}
// Keyed to the message, so dismissing one does not swallow the next.
if ( isset( $notice['dismissed'] ) && self::fingerprint( $message ) === $notice['dismissed'] ) {
return;
}
// Reduced to a known member here rather than in the view, so the view receives a value that
// is already safe to place in a class attribute and cannot be handed anything else.
$level = isset( $notice['level'] ) && in_array( $notice['level'], array( 'error', 'warning', 'info' ), true )
? $notice['level']
: 'info';
$name = $this->config->name();
$plugin = $this->config->plugin();
$action = admin_url( 'admin-post.php' );
$nonce_action = 'cx_tracker_dismiss_' . $plugin;
$dismiss = __( 'Dismiss', 'plugin-tracker-sdk' );
include __DIR__ . '/../../views/consent/server-notice.php';
}
/**
* Identity of a stored message, so a dismissal cannot carry over to a different one.
*
* @param string $message Message.
* @return string
*/
private static function fingerprint( $message ) {
return md5( (string) $message );
}
/**
* Record that the current server-supplied message has been dismissed.
*
* @param Config $config Config.
* @return void
*/
public static function dismiss( Config $config ) {
$notice = get_option( $config->option( 'notice' ) );
if ( ! is_array( $notice ) || empty( $notice['message'] ) ) {
return;
}
$notice['dismissed'] = self::fingerprint( (string) $notice['message'] );
update_option( $config->option( 'notice' ), $notice, false );
}
/**
* Store a server-supplied notice.
*
* @param Config $config Config.
* @param array $notice Notice payload from the ingestion response.
* @return void
*/
public static function remember_server_notice( Config $config, array $notice ) {
if ( empty( $notice['message'] ) || ! is_string( $notice['message'] ) ) {
return;
}
update_option(
$config->option( 'notice' ),
array(
// Truncated because this string is server-supplied and rendered in wp-admin. It is
// escaped at output, but an unbounded string in an option is still not something to
// accept from the network.
'message' => substr( $notice['message'], 0, 500 ),
'level' => isset( $notice['level'] ) ? (string) $notice['level'] : 'info',
'until' => self::normalize_until( isset( $notice['until'] ) ? $notice['until'] : null ),
),
false
);
}
/**
* Reduce a server-supplied `until` to a usable timestamp.
*
* `is_numeric()` rather than a bare cast: `(int) '2030-01-01'` is 2030, a 1970 timestamp, so an
* ISO date used to drop the notice on its first render instead of showing it until 2030. A
* readable timestamp is kept as written, including one already past -- that is the server saying
* "do not show this" and is not ours to extend.
*
* @param mixed $until Raw value.
* @return int
*/
private static function normalize_until( $until ) {
if ( ! is_numeric( $until ) || (int) $until < 1 ) {
return time() + self::NOTICE_TTL;
}
return (int) $until;
}
/**
* Surface config validation errors to a developer.
*
* Only when WP_DEBUG is on -- a misconfigured SDK is a development-time mistake, and shouting
* about it on a production site would be the SDK damaging its consumer.
*
* @param Config $config Invalid config.
* @return void
*/
public static function config_errors( Config $config ) {
if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
return;
}
$errors = $config->errors();
if ( ! function_exists( 'add_action' ) ) {
return;
}
$render = function () use ( $errors ) {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
printf(
'<div class="notice notice-error"><p><strong>Plugin Tracker SDK misconfigured:</strong> %s</p></div>',
esc_html( implode( ' | ', $errors ) )
);
};
// Both screens: a network-activated plugin's only administrator may never open a site admin.
add_action( 'admin_notices', $render );
add_action( 'network_admin_notices', $render );
}
/**
* Log a development-time warning.
*
* @param Config $config Config.
* @param string $message Message.
* @return void
*/
public static function dev_warning( Config $config, $message ) {
unset( $config );
if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
return;
}
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log( (string) $message );
}
/**
* Forget stored notices.
*
* @param Config $config Config.
* @return void
*/
public static function forget( Config $config ) {
delete_option( $config->option( 'notice' ) );
}
}