Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
170 changes: 170 additions & 0 deletions includes/Admin/Uninstall.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
<?php
/**
* Handles removal of the plugin's data on uninstall.
*
* @package WordPress\AI\Admin
* @since x.x.x
*/

declare( strict_types=1 );

namespace WordPress\AI\Admin;

use WordPress\AI\Logging\AI_Request_Log_Schema;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
* Class - Uninstall.
*
* Removes the plugin's custom table, options and scheduled events
* when the site has opted in via the "remove all data on uninstall" setting.
*
* @internal
*
* @since x.x.x
*/
final class Uninstall {

/**
* Option that opts a site in to full data removal on uninstall.
*
* @since x.x.x
*
* @var string
*/
public const OPTION_REMOVE_DATA = 'wpai_remove_data_on_uninstall';

/**
* Scheduled cron hook used by the request log manager.
*
* @since x.x.x
*
* @var string
*/
private const REQUEST_LOG_CLEANUP_HOOK = 'wpai_request_logs_cleanup';

/**
* Runs the uninstall routine.
*
* Cleanup only happens for sites that have explicitly opted in. On
* multisite the opt-in is evaluated per site so each site keeps control of
* its own data.
*
* @since x.x.x
*
* @return void
*/
public static function run(): void {
if ( is_multisite() ) {
$site_ids = get_sites(
array(
'fields' => 'ids',
'number' => 0,
)
);

foreach ( $site_ids as $site_id ) {
switch_to_blog( (int) $site_id ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.switch_to_blog_switch_to_blog
self::maybe_clean_current_site();
restore_current_blog();
}

return;
}

self::maybe_clean_current_site();
}

/**
* Removes the plugin's data for the current site when opted in.
*
* @since x.x.x
*
* @return void
*/
private static function maybe_clean_current_site(): void {
if ( ! (bool) get_option( self::OPTION_REMOVE_DATA, false ) ) {
return;
}

self::drop_request_logs_table();
self::delete_options();
self::delete_transients();
self::clear_scheduled_events();
}

/**
* Drops the request logs custom table.
*
* @since x.x.x
*
* @return void
*/
private static function drop_request_logs_table(): void {
global $wpdb;

$table_name = $wpdb->prefix . AI_Request_Log_Schema::TABLE_NAME;

$wpdb->query( "DROP TABLE IF EXISTS `{$table_name}`" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
}

/**
* Deletes all of the plugin's options.
*
* @since x.x.x
*
* @return void
*/
private static function delete_options(): void {
global $wpdb;

$like = $wpdb->esc_like( 'wpai_' ) . '%';

$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
$like
)
);
}

/**
* Deletes the plugin's transients (regular and site transients).
*
* @since x.x.x
*
* @return void
*/
private static function delete_transients(): void {
global $wpdb;

$patterns = array(
$wpdb->esc_like( '_transient_wpai_' ) . '%',
$wpdb->esc_like( '_transient_timeout_wpai_' ) . '%',
$wpdb->esc_like( '_site_transient_wpai_' ) . '%',
$wpdb->esc_like( '_site_transient_timeout_wpai_' ) . '%',
);

foreach ( $patterns as $like ) {
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
$like
)
);
}
}

/**
* Clears the plugin's scheduled cron events.
*
* @since x.x.x
*
* @return void
*/
private static function clear_scheduled_events(): void {
wp_clear_scheduled_hook( self::REQUEST_LOG_CLEANUP_HOOK );
}
}
12 changes: 12 additions & 0 deletions includes/Settings/Settings_Registration.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace WordPress\AI\Settings;

use WordPress\AI\Admin\Uninstall;
use WordPress\AI\Features\Registry;
use WordPress\AI\REST\Models_Controller;

Expand Down Expand Up @@ -93,6 +94,17 @@ public function register_settings(): void {
)
);

register_setting(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I know this was mentioned in the attached Issue but not sure I agree with having a setting for this. This seems like a lot to ask the average user to have to decide if they want this checked or not (most won't fully understand what it means). I'm open to differing opinions here but I'd suggest we remove the setting and just have the data deletion happen by default. cc / @jeffpaul

New data settings section

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also fine to avoid an additional setting here as well and default to data deletion.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @dkotter @jeffpaul, In my opinion, we should go with what other plugins do mostly. As I have from 10 plugins, almost 8-9 plugins provide the an user option to cleanup the data in either way.

Either they provide the settings or when deactivate/uninstall they provide a modal popup to ask user choice to retain/remove the data.

In any how, we should respect the user's choice if they want to cleanup or not.

If we are not adding this, we can update this choice when user try to uninstall the plugin?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still feel like there's no need for a setting here. If someone is deliberately deleting the entire plugin, seems the right answer is to clean up after ourselves.

That said, I'm not opposed to adding a setting here if the consensus is that's what users want. I would argue that setting should be checked by default though, whereas this PR has that unchecked. I'd also suggest we put this in a new Advanced section instead of Data and maybe have that section collapsed by default

self::OPTION_GROUP,
Uninstall::OPTION_REMOVE_DATA,
array(
'type' => 'boolean',
'default' => false,
'sanitize_callback' => 'rest_sanitize_boolean',
'show_in_rest' => true,
)
);

// Register settings for each experiment.
foreach ( $this->registry->get_all_features() as $feature ) {
$feature_id = $feature::get_id();
Expand Down
46 changes: 46 additions & 0 deletions routes/ai-home/components/DataRemovalSetting.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* WordPress dependencies
*/
import { Notice, Stack } from '@wordpress/ui';
import { ToggleControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

/**
* Internal dependencies
*/
import { useDataRemovalSetting } from '../hooks/use-data-removal-setting';

/**
* Renders the "remove all plugin data on uninstall" opt-in.
*
* Rendered as the content of a collapsible settings section. A warning Notice
* accompanies the toggle because enabling it makes plugin deletion destructive:
* the request logs table and all plugin options are permanently removed when
* the plugin is uninstalled.
*
* @return {React.JSX.Element} The data removal setting.
*/
export function DataRemovalSetting(): React.JSX.Element {
const { enabled, update } = useDataRemovalSetting();

return (
<Stack direction="column" gap="md">
<Notice.Root intent="error">
<Notice.Description>
{ __(
'When the plugin is deleted, permanently remove all of its data, including the request logs table and every plugin option. This cannot be undone. Deactivating the plugin leaves your data untouched.',
'ai'
) }
</Notice.Description>
</Notice.Root>
<ToggleControl
className="ai-data-removal-card__toggle"
label={ __( 'Remove all plugin data on uninstall', 'ai' ) }
checked={ enabled }
onChange={ ( value ) => {
void update( value );
} }
/>
</Stack>
);
}
83 changes: 83 additions & 0 deletions routes/ai-home/hooks/use-data-removal-setting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* WordPress dependencies
*/
import { store as coreStore } from '@wordpress/core-data';
import { useDispatch, useSelect } from '@wordpress/data';
import { useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';

interface UseDataRemovalSettingReturn {
enabled: boolean;
update: ( next: boolean ) => Promise< void >;
isSaving: boolean;
}

/**
* Setting key registered on the `root`/`site` entity (see Settings_Registration).
*/
const OPTION_KEY = 'wpai_remove_data_on_uninstall';

/**
* Reads and writes the "remove all plugin data on uninstall" opt-in.
*
* The value is stored in the WordPress option `wpai_remove_data_on_uninstall`
* and exposed via the REST API settings endpoint.
*
* @return {UseDataRemovalSettingReturn} The setting value and update function.
*/
export function useDataRemovalSetting(): UseDataRemovalSettingReturn {
const { editedRecord, isSaving } = useSelect( ( select ) => {
const store: any = select( coreStore );
return {
editedRecord: store.getEditedEntityRecord( 'root', 'site' ) as
| Record< string, unknown >
| undefined,
isSaving: store.isSavingEntityRecord( 'root', 'site' ) as boolean,
};
}, [] );

const { editEntityRecord } = useDispatch( coreStore );
const { __experimentalSaveSpecifiedEntityEdits: saveSpecifiedEdits } =
useDispatch( coreStore ) as any;
const { createSuccessNotice, createErrorNotice } =
useDispatch( noticesStore );

const enabled = Boolean( editedRecord?.[ OPTION_KEY ] );

const update = useCallback(
async ( next: boolean ) => {
// @ts-expect-error -- core-data types don't expose editEntityRecord for 'root'/'site' args.
editEntityRecord( 'root', 'site', undefined, {
[ OPTION_KEY ]: next,
} );
try {
await saveSpecifiedEdits(
'root',
'site',
undefined,
[ OPTION_KEY ],
{ throwOnError: true }
);
createSuccessNotice(
next
? __( 'Data removal on uninstall enabled.', 'ai' )
: __( 'Data removal on uninstall disabled.', 'ai' ),
{ type: 'snackbar' }
);
} catch {
createErrorNotice( __( 'Failed to save settings.', 'ai' ), {
type: 'snackbar',
} );
}
},
[
editEntityRecord,
saveSpecifiedEdits,
createSuccessNotice,
createErrorNotice,
]
);

return { enabled, update, isSaving };
}
23 changes: 22 additions & 1 deletion routes/ai-home/stage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { store as noticesStore } from '@wordpress/notices';
* Internal dependencies
*/
import AIIcon from './ai-icon';
import { DataRemovalSetting } from './components/DataRemovalSetting';
import { DeveloperSettings } from './components/DeveloperSettings';
import { FeatureToggle } from './components/FeatureToggle';
import {
Expand Down Expand Up @@ -84,6 +85,7 @@ interface PageData {

const FEATURE_SETTING_PATTERN = /^wpai_feature_(.+)_enabled$/;
const GLOBAL_FIELD_ID = 'wpai_features_enabled';
const DATA_REMOVAL_FIELD_ID = 'wpai_remove_data_on_uninstall';
const noop = () => {};

function isRecord( value: unknown ): value is Record< string, unknown > {
Expand Down Expand Up @@ -861,7 +863,14 @@ function AISettingsPage() {
return baseField;
} );

return [ ...sectionActionsFields, ...featureFields ];
const dataRemovalField: Field< AISettings > = {
id: DATA_REMOVAL_FIELD_ID,
label: '',
type: 'text',
Edit: () => <DataRemovalSetting />,
};

return [ ...sectionActionsFields, ...featureFields, dataRemovalField ];
}, [ featureDefinitions, featureGroups, globalEnabled, handleChange ] );

const form = useMemo< Form >( () => {
Expand Down Expand Up @@ -952,6 +961,18 @@ function AISettingsPage() {
} );
}

sectionFields.push( {
id: getSectionId( 'data' ),
label: __( 'Data', 'ai' ),
layout: {
type: 'card',
withHeader: true,
isOpened: true,
isCollapsible: true,
},
children: [ DATA_REMOVAL_FIELD_ID ],
} );

return {
fields: sectionFields,
};
Expand Down
Loading
Loading