| 1 |
<?php |
| 2 |
/** |
| 3 |
* Noted! — uninstall handler. |
| 4 |
* |
| 5 |
* Runs when the plugin is deleted from the WordPress admin (NOT on |
| 6 |
* deactivation). Only purges data when the user has opted in via the |
| 7 |
* "Delete all data on uninstall" toggle on the settings page. |
| 8 |
*/ |
| 9 |
|
| 10 |
declare(strict_types=1); |
| 11 |
|
| 12 |
if (! defined('WP_UNINSTALL_PLUGIN')) { |
| 13 |
exit; |
| 14 |
} |
| 15 |
|
| 16 |
const NOTED_OPTION_KEY = 'noted_settings'; |
| 17 |
const NOTED_POST_TYPE = 'noted_note'; |
| 18 |
|
| 19 |
$noted_settings = get_option(NOTED_OPTION_KEY, []); |
| 20 |
if (! is_array($noted_settings) || empty($noted_settings['delete_on_uninstall'])) { |
| 21 |
return; |
| 22 |
} |
| 23 |
|
| 24 |
global $wpdb; |
| 25 |
|
| 26 |
// 1. Delete every noted_note post and its associated meta. |
| 27 |
|
| 28 |
$note_ids = $wpdb->get_col($wpdb->prepare( |
| 29 |
"SELECT ID FROM {$wpdb->posts} WHERE post_type = %s", |
| 30 |
NOTED_POST_TYPE |
| 31 |
)); |
| 32 |
foreach ((array) $note_ids as $note_id) { |
| 33 |
wp_delete_post((int) $note_id, true); |
| 34 |
} |
| 35 |
|
| 36 |
// 2. Strip the `notedNote` block attribute from every post that contains it. |
| 37 |
|
| 38 |
$strip_noted_note = static function (array $block) use (&$strip_noted_note): array { |
| 39 |
if (isset($block['attrs']['notedNote'])) { |
| 40 |
unset($block['attrs']['notedNote']); |
| 41 |
} |
| 42 |
if (isset($block['attrs']['notedNoteUser'])) { |
| 43 |
unset($block['attrs']['notedNoteUser']); |
| 44 |
} |
| 45 |
if (! empty($block['innerBlocks'])) { |
| 46 |
$block['innerBlocks'] = array_map($strip_noted_note, $block['innerBlocks']); |
| 47 |
} |
| 48 |
return $block; |
| 49 |
}; |
| 50 |
|
| 51 |
$attribute_marker = '"notedNote"'; |
| 52 |
$like_pattern = '%' . $wpdb->esc_like($attribute_marker) . '%'; |
| 53 |
$candidate_ids = $wpdb->get_col($wpdb->prepare( |
| 54 |
"SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE %s", |
| 55 |
$like_pattern |
| 56 |
)); |
| 57 |
|
| 58 |
foreach ((array) $candidate_ids as $post_id) { |
| 59 |
$original_content = get_post_field('post_content', (int) $post_id); |
| 60 |
if (! is_string($original_content) || strpos($original_content, $attribute_marker) === false) { |
| 61 |
continue; |
| 62 |
} |
| 63 |
|
| 64 |
$blocks = parse_blocks($original_content); |
| 65 |
$cleaned_blocks = array_map($strip_noted_note, $blocks); |
| 66 |
$rewritten_content = serialize_blocks($cleaned_blocks); |
| 67 |
|
| 68 |
if ($rewritten_content === $original_content) { |
| 69 |
continue; |
| 70 |
} |
| 71 |
|
| 72 |
wp_update_post([ |
| 73 |
'ID' => (int) $post_id, |
| 74 |
'post_content' => $rewritten_content, |
| 75 |
]); |
| 76 |
} |
| 77 |
|
| 78 |
// 3. Drop the plugin option. |
| 79 |
|
| 80 |
delete_option(NOTED_OPTION_KEY); |
| 81 |
|