-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclass-suggested-tasks.php
More file actions
646 lines (556 loc) · 19.7 KB
/
class-suggested-tasks.php
File metadata and controls
646 lines (556 loc) · 19.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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
<?php
/**
* Recommendations class.
*
* @package Progress_Planner
*/
namespace Progress_Planner;
use Progress_Planner\Activities\Suggested_Task as Suggested_Task_Activity;
use Progress_Planner\Suggested_Tasks\Tasks_Manager;
use Progress_Planner\Suggested_Tasks\Providers\Content_Review;
/**
* Recommendations class.
*
* @package Progress_Planner
*/
class Suggested_Tasks {
/**
* Status map for task statuses.
* This is mostly used for backwards compatibility.
*
* @var array<string, string>
*/
const STATUS_MAP = [
'completed' => 'trash',
'pending_celebration' => 'pending',
'pending' => 'publish',
'snoozed' => 'future',
];
/**
* An object containing tasks.
*
* @var \Progress_Planner\Suggested_Tasks\Tasks_Manager
*/
private Tasks_Manager $tasks_manager;
/**
* Constructor.
*/
public function __construct() {
$this->tasks_manager = new Tasks_Manager();
if ( \is_admin() ) {
\add_action( 'admin_init', [ $this, 'init' ], 20 ); // Wait for the post types to be initialized and transients to be set.
// Check GET parameter and maybe set task as pending.
\add_action( 'init', [ $this, 'maybe_complete_task' ] );
}
\add_action( 'wp_ajax_progress_planner_suggested_task_action', [ $this, 'suggested_task_action' ] );
// Add the automatic updates complete action.
\add_action( 'automatic_updates_complete', [ $this, 'on_automatic_updates_complete' ] );
// Register the custom post type.
\add_action( 'init', [ $this, 'register_post_type' ], 0 );
// Register the custom taxonomies.
\add_action( 'init', [ $this, 'register_taxonomy' ], 0 );
// Filter the REST API tax query.
\add_filter( 'rest_prpl_recommendations_query', [ $this, 'rest_api_tax_query' ], 10, 2 );
// Filter the REST API response.
\add_filter( 'rest_prepare_prpl_recommendations', [ $this, 'rest_prepare_recommendation' ], 10, 2 );
\add_filter( 'wp_trash_post_days', [ $this, 'change_trashed_posts_lifetime' ], 10, 2 );
}
/**
* Run the tasks.
*
* @return void
*/
public function init(): void {
// Check for completed tasks.
$completed_tasks = $this->tasks_manager->evaluate_tasks();
foreach ( $completed_tasks as $task ) {
if ( ! $task->post_name && $task->ID ) {
continue;
}
// Change the task status to pending.
$task->celebrate();
// Insert an activity.
$this->insert_activity( \progress_planner()->get_suggested_tasks()->get_task_id_from_slug( $task->post_name ) );
}
}
/**
* Insert an activity.
*
* @param string $task_id The task ID.
*
* @return void
*/
public function insert_activity( string $task_id ): void {
// Insert an activity.
$activity = new Suggested_Task_Activity();
$activity->type = 'completed';
$activity->data_id = (string) $task_id;
$activity->date = new \DateTime();
$activity->user_id = \get_current_user_id();
$activity->save();
// Allow other classes to react to the completion of a suggested task.
\do_action( 'progress_planner_suggested_task_completed', $task_id );
}
/**
* Delete an activity.
*
* @param string $task_id The task ID.
*
* @return void
*/
public function delete_activity( string $task_id ): void {
$activity = \progress_planner()->get_activities__query()->query_activities(
[
'data_id' => $task_id,
'type' => 'completed',
]
);
if ( empty( $activity ) ) {
return;
}
\progress_planner()->get_activities__query()->delete_activity( $activity[0] );
}
/**
* If done via automatic updates, the "core update" task should be marked as "trashed" (and skip "pending" status).
*
* @return void
*/
public function on_automatic_updates_complete(): void {
$pending_tasks = \progress_planner()->get_suggested_tasks_db()->get(
[
'numberposts' => 1,
'post_status' => 'publish',
'provider_id' => 'update-core',
'date_query' => [ [ 'after' => 'this Monday' ] ],
]
);
if ( empty( $pending_tasks ) ) {
return;
}
\progress_planner()->get_suggested_tasks_db()->update_recommendation( $pending_tasks[0]->ID, [ 'post_status' => 'trash' ] );
// Insert an activity.
$this->insert_activity( \progress_planner()->get_suggested_tasks()->get_task_id_from_slug( $pending_tasks[0]->post_name ) );
}
/**
* Get the tasks manager.
*
* @return \Progress_Planner\Suggested_Tasks\Tasks_Manager
*/
public function get_tasks_manager(): Tasks_Manager {
return $this->tasks_manager;
}
/**
* Check if a task was completed. Task is considered completed if it was trashed or pending.
*
* @param string|int $task_id The task ID.
*
* @return bool
*/
public function was_task_completed( $task_id ): bool {
$task = \progress_planner()->get_suggested_tasks_db()->get_post( $task_id );
return $task && $task->is_completed();
}
/**
* Maybe complete a task.
* Primarly this is used for deeplinking, ie user is testing if the emails are working
* He gets an email with a link which automatically completes the task.
*
* Verify token to prevent CSRF attacks.
* Tokens are one-time use and expire after 24 hours.
*
* @return void
*/
public function maybe_complete_task() {
if ( ! \progress_planner()->is_on_progress_planner_dashboard_page() || ! isset( $_GET['prpl_complete_task'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
return;
}
$task_id = \sanitize_text_field( \wp_unslash( $_GET['prpl_complete_task'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( ! $task_id ) {
return;
}
// Verify token to prevent CSRF attacks.
if ( ! isset( $_GET['token'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
return;
}
$provided_token = \sanitize_text_field( \wp_unslash( $_GET['token'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$user_id = \get_current_user_id();
// Verify the token.
if ( ! $this->verify_task_completion_token( $task_id, $user_id, $provided_token ) ) {
return;
}
// Mark task as completed and delete the token.
$this->mark_task_as_completed( $task_id, $user_id );
}
/**
* Complete a task.
*
* @param string $task_id The task ID.
* @param int|null $user_id Optional. The user ID for token deletion. If provided, the token will be deleted.
* @param bool $skip_celebration Optional. Whether to skip the celebration.
*
* @return bool
*/
public function mark_task_as_completed( $task_id, $user_id = null, $skip_celebration = false ) {
if ( ! $this->was_task_completed( $task_id ) ) {
$task = \progress_planner()->get_suggested_tasks_db()->get_post( $task_id );
if ( $task ) {
$post_status = $skip_celebration ? 'trash' : 'pending';
\progress_planner()->get_suggested_tasks_db()->update_recommendation( $task->ID, [ 'post_status' => $post_status ] );
// Insert an activity.
$this->insert_activity( $task_id );
// Delete the token after successful use (one-time use) if user_id is provided.
if ( $user_id ) {
$this->delete_task_completion_token( $task_id, $user_id );
}
return true;
}
}
return false;
}
/**
* Generate a secure token for task completion via email link.
*
* This token prevents CSRF attacks by ensuring only legitimate email
* links can mark tasks as complete.
*
* @param string $task_id The task ID.
* @param int $user_id The user ID.
*
* @return string The generated token.
*/
public function generate_task_completion_token( $task_id, $user_id ) {
// Generate a cryptographically secure random token.
$random = \wp_generate_password( 32, false );
$token = \wp_hash( $task_id . $user_id . $random . \wp_salt( 'auth' ) );
// Store the token in a transient (expires after 24 hours).
\set_transient(
'prpl_complete_' . $task_id . '_' . $user_id,
$token,
DAY_IN_SECONDS
);
return $token;
}
/**
* Verify a task completion token.
*
* @param string $task_id The task ID.
* @param int $user_id The user ID.
* @param string $provided_token The token to verify.
*
* @return bool True if token is valid, false otherwise.
*/
protected function verify_task_completion_token( $task_id, $user_id, $provided_token ) {
$stored_token = \get_transient( 'prpl_complete_' . $task_id . '_' . $user_id );
if ( ! $stored_token ) {
return false; // Token expired or doesn't exist.
}
// Use hash_equals to prevent timing attacks.
return \hash_equals( $stored_token, $provided_token );
}
/**
* Delete a task completion token after use.
*
* @param string $task_id The task ID.
* @param int $user_id The user ID.
*
* @return bool True if deleted, false otherwise.
*/
protected function delete_task_completion_token( $task_id, $user_id ) {
return \delete_transient( 'prpl_complete_' . $task_id . '_' . $user_id );
}
/**
* Handle the suggested task action.
*
* @return void
*/
public function suggested_task_action() {
// Check the nonce.
if ( ! \check_ajax_referer( 'progress_planner', 'nonce', false ) ) {
\wp_send_json_error( [ 'message' => \esc_html__( 'Invalid nonce.', 'progress-planner' ) ] );
}
if ( ! isset( $_POST['post_id'] ) || ! isset( $_POST['action_type'] ) ) {
\wp_send_json_error( [ 'message' => \esc_html__( 'Missing data.', 'progress-planner' ) ] );
}
$action = \sanitize_text_field( \wp_unslash( $_POST['action_type'] ) );
$post_id = (string) \sanitize_text_field( \wp_unslash( $_POST['post_id'] ) );
$task = \progress_planner()->get_suggested_tasks_db()->get_post( $post_id );
if ( ! $task ) {
\wp_send_json_error( [ 'message' => \esc_html__( 'Task not found.', 'progress-planner' ) ] );
}
$provider = \progress_planner()->get_suggested_tasks()->get_tasks_manager()->get_task_provider( $task->get_provider_id() );
if ( ! $provider ) {
\wp_send_json_error( [ 'message' => \esc_html__( 'Provider not found.', 'progress-planner' ) ] );
}
if ( ! $provider->capability_required() ) {
\wp_send_json_error( [ 'message' => \esc_html__( 'You do not have permission to complete this task.', 'progress-planner' ) ] );
}
$updated = false;
switch ( $action ) {
case 'complete':
// Insert an activity.
$this->insert_activity( \progress_planner()->get_suggested_tasks()->get_task_id_from_slug( $task->post_name ) );
$updated = true;
break;
case 'pending': // User task was marked as pending.
case 'delete':
$this->delete_activity( \progress_planner()->get_suggested_tasks()->get_task_id_from_slug( $task->post_name ) );
$updated = true;
break;
}
/**
* Allow other classes to react to the completion of a suggested task.
*
* @param string $post_id The post ID.
* @param bool $updated Whether the action was successful.
*/
\do_action( "progress_planner_ajax_task_{$action}", $post_id, $updated );
if ( ! $updated ) {
\wp_send_json_error( [ 'message' => \esc_html__( 'Not saved.', 'progress-planner' ) ] );
}
\wp_send_json_success( [ 'message' => \esc_html__( 'Saved.', 'progress-planner' ) ] );
}
/**
* Register a custom post type for suggested tasks.
*
* @return void
*/
public function register_post_type() {
\register_post_type(
'prpl_recommendations',
[
'label' => \__( 'Recommendations', 'progress-planner' ),
'public' => false,
'show_ui' => \apply_filters( 'progress_planner_tasks_show_ui', false ),
'show_in_admin_bar' => \apply_filters( 'progress_planner_tasks_show_ui', false ),
'show_in_rest' => true,
'rest_controller_class' => \Progress_Planner\Rest\Recommendations_Controller::class,
'supports' => [ 'title', 'excerpt', 'editor', 'author', 'custom-fields', 'page-attributes' ],
'rewrite' => false,
'menu_icon' => 'dashicons-admin-tools',
'menu_position' => 5,
'hierarchical' => true,
'exclude_from_search' => true,
]
);
$rest_meta_fields = [
'prpl_url' => [
'type' => 'string',
'single' => true,
'show_in_rest' => true,
],
'menu_order' => [
'type' => 'number',
'single' => true,
'show_in_rest' => true,
'default' => 0,
],
];
foreach ( $rest_meta_fields as $key => $field ) {
\register_post_meta(
'prpl_recommendations',
$key,
$field
);
}
}
/**
* Custom trash lifetime by post type.
*
* @param int $days The number of days to keep in trash.
* @param \WP_Post $post The post.
*
* @return int
*/
public function change_trashed_posts_lifetime( $days, $post ) {
return 'prpl_recommendations' === $post->post_type ? 60 : $days;
}
/**
* Register a custom taxonomies for suggested tasks.
*
* @return void
*/
public function register_taxonomy() {
// Register only the provider taxonomy.
\register_taxonomy(
'prpl_recommendations_provider',
[ 'prpl_recommendations' ],
[
'public' => false,
'hierarchical' => false,
'labels' => [
'name' => \__( 'Providers', 'progress-planner' ),
],
'show_ui' => \apply_filters( 'progress_planner_tasks_show_ui', false ),
'show_admin_column' => false,
'query_var' => true,
'rewrite' => [ 'slug' => 'prpl_recommendations_provider' ],
'show_in_rest' => true,
'show_in_menu' => \apply_filters( 'progress_planner_tasks_show_ui', false ),
]
);
}
/**
* Filter the REST API tax query.
*
* @param array $args The arguments.
* @param \WP_REST_Request $request The request.
*
* @return array
*/
public function rest_api_tax_query( $args, $request ) {
$tax_query = [];
// Exclude terms.
if ( isset( $request['exclude_provider'] ) ) {
$tax_query[] = [
'taxonomy' => 'prpl_recommendations_provider',
'field' => 'slug',
'terms' => \explode( ',', $request['exclude_provider'] ),
'operator' => 'NOT IN',
];
}
$include_providers = [];
$providers_available_for_user = \progress_planner()->get_suggested_tasks()->get_tasks_manager()->get_task_providers_available_for_user();
foreach ( $providers_available_for_user as $provider ) {
$include_providers[] = $provider->get_provider_id();
}
// Include terms (matches any term in list).
if ( isset( $request['provider'] ) ) {
$request_providers = \explode( ',', $request['provider'] );
$include_providers = \array_intersect( $include_providers, $request_providers );
}
$tax_query[] = [
'taxonomy' => 'prpl_recommendations_provider',
'field' => 'slug',
'terms' => $include_providers,
'operator' => 'IN',
];
$args['tax_query'] = $tax_query; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
// Handle sorting parameters.
if ( isset( $request['filter']['orderby'] ) ) {
// @phpstan-ignore-next-line argument.templateType
$orderby = \sanitize_sql_orderby( $request['filter']['orderby'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$args['orderby'] = $orderby !== false ? $orderby : 'date';
}
if ( isset( $request['filter']['order'] ) ) {
$args['order'] = \in_array( \strtoupper( $request['filter']['order'] ), [ 'ASC', 'DESC' ], true )
? \strtoupper( $request['filter']['order'] )
: 'ASC';
}
return $args;
}
/**
* Filter the REST API response.
*
* @param \WP_REST_Response $response The response.
* @param \WP_Post $post The post.
*
* @return \WP_REST_Response
*/
public function rest_prepare_recommendation( $response, $post ) {
$provider_term = \wp_get_object_terms( $post->ID, 'prpl_recommendations_provider' );
if ( ! isset( $response->data['meta'] ) ) {
$response->data['meta'] = [];
}
$provider = false;
if ( $provider_term && ! \is_wp_error( $provider_term ) ) {
$provider = \progress_planner()->get_suggested_tasks()->get_tasks_manager()->get_task_provider( $provider_term[0]->slug );
}
$response->data['slug'] = \progress_planner()->get_suggested_tasks()->get_task_id_from_slug( $response->data['slug'] );
if ( $provider ) {
$response->data['prpl_provider'] = $provider_term[0];
// Link should be added during run time, since it is not added for users without required capability.
$response->data['meta']['prpl_url'] = $response->data['meta']['prpl_url'] && $provider->capability_required()
? \esc_url( (string) $response->data['meta']['prpl_url'] )
: '';
$response->data['prpl_popover_id'] = $provider->get_popover_id();
$response->data['prpl_points'] = $provider->get_points();
/*
* Check if task was completed before - for example, comments were disabled and then re-enabled, and remove points if so.
* Those are tasks which are completed by toggling an option, so non repetitive & not user tasks.
*/
if ( ! \has_term( 'user', 'prpl_recommendations_provider', $post->ID ) && ! $provider->is_repetitive() && $provider->task_has_activity( $response->data['slug'] ) ) {
$response->data['prpl_points'] = 0;
}
// Assign point only to golden user task.
if ( 'user' === $provider->get_provider_id() ) {
$response->data['prpl_points'] = ( ! empty( $post->post_excerpt ) && \str_contains( $post->post_excerpt, 'GOLDEN' ) ) ? 1 : 0;
}
// This has to be the last item to be added because actions use data from previous items.
$response->data['prpl_task_actions'] = $provider->get_task_actions( $response->data );
}
// Category taxonomy removed - no longer adding prpl_category to response.
return $response;
}
/**
* Get the pending tasks in REST format.
*
* @param array $args The arguments.
*
* @return array
*/
public function get_tasks_in_rest_format( array $args = [] ) {
$args = \wp_parse_args(
$args,
[
'post_status' => 'publish',
'exclude_provider' => [],
'include_provider' => [],
'posts_per_page' => -1,
]
);
// Build query args for get_tasks_by.
$query_args = [
'post_status' => $args['post_status'],
'posts_per_page' => $args['posts_per_page'],
];
if ( ! empty( $args['meta_query'] ) ) {
$query_args['meta_query'] = $args['meta_query']; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
}
// Add provider filters if specified.
if ( ! empty( $args['exclude_provider'] ) ) {
// Note: Database filtering doesn't support exclude_provider directly,
// so we'll fetch all tasks, filter, then limit.
$original_limit = $query_args['posts_per_page'];
$query_args['posts_per_page'] = -1; // Fetch all tasks.
$all_tasks = \progress_planner()->get_suggested_tasks_db()->get_tasks_by( $query_args );
$all_tasks = \array_filter(
$all_tasks,
function ( $task ) use ( $args ) {
return ! \in_array( $task->get_provider_id(), $args['exclude_provider'], true );
}
);
// Now limit to the originally requested number.
if ( -1 !== $original_limit ) {
$all_tasks = \array_slice( $all_tasks, 0, $original_limit );
}
} elseif ( ! empty( $args['include_provider'] ) ) {
$query_args['provider'] = $args['include_provider'];
$all_tasks = \progress_planner()->get_suggested_tasks_db()->get_tasks_by( $query_args );
} else {
$all_tasks = \progress_planner()->get_suggested_tasks_db()->get_tasks_by( $query_args );
}
// Convert tasks to REST format.
$tasks = [];
foreach ( $all_tasks as $task ) {
$tasks[] = $task->get_rest_formatted_data();
}
/**
* Allow other classes to modify the tasks in REST format.
*
* @param array $tasks The tasks.
* @param array $args The arguments.
*
* @return array
*/
return \apply_filters( 'progress_planner_suggested_tasks_in_rest_format', $tasks, $args );
}
/**
* Get the task ID from a slug.
*
* @param string $slug The slug.
* @return string
*/
public function get_task_id_from_slug( $slug ) {
return \explode( '__trashed', $slug )[0];
}
}