Skip to content

Commit

Permalink
feat: new option "cleanup media" added
Browse files Browse the repository at this point in the history
to configure fine grained what data should be cleaned up before import
  • Loading branch information
lgersman committed Feb 5, 2024
1 parent c50f841 commit 6e351ad
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 43 deletions.
32 changes: 12 additions & 20 deletions plugins/cm4all-wp-impex/inc/class-impex-import.php
Expand Up @@ -33,10 +33,14 @@ abstract class ImpexImport extends ImpexPart

const WP_FILTER_PROFILES = 'impex_import_filter_profiles';

// post, media, block pattern, nav_menu an reusable block items
// cleanup post, block pattern, nav_menu an reusable block items
const OPTION_CLEANUP_CONTENTS = 'impex-import-option-cleanup_contents';
const OPTION_CLEANUP_CONTENTS_DEFAULT = false;

// cleanup media items
const OPTION_CLEANUP_MEDIA = 'impex-import-option-cleanup_media';
const OPTION_CLEANUP_MEDIA_DEFAULT = false;

protected function _createProvider(string $name, callable $cb): ImpexImportProvider
{
return new class($name, $cb) extends ImpexImportProvider
Expand Down Expand Up @@ -174,7 +178,7 @@ function consume(ImpexImportTransformationContext $transformationContext, int $l

// do clean up before importing first slices
if($offset===0) {
if(($options[self::OPTION_CLEANUP_CONTENTS] ?? false) == true) {
if(($options[self::OPTION_CLEANUP_CONTENTS] ?? self::OPTION_CLEANUP_CONTENTS_DEFAULT) == true) {
$menus = \wp_get_nav_menus(['fields' => 'ids' ]);
foreach ($menus as $menu) {
\wp_delete_nav_menu( $menu);
Expand All @@ -184,14 +188,18 @@ function consume(ImpexImportTransformationContext $transformationContext, int $l
foreach ($postsToDelete as $postToDelete) {
\wp_delete_post( $postToDelete, true );
}
}

if(($options[self::OPTION_CLEANUP_MEDIA] ?? self::OPTION_CLEANUP_MEDIA_DEFAULT) == true) {
$attachmentsToDelete= \get_posts( ['post_type'=>'attachment','numberposts'=>-1,'fields' => 'ids'] );
foreach ($attachmentsToDelete as $attachmentToDelete) {
\wp_delete_attachment($attachmentToDelete, true);
}
} else {
$this->_delete_transient_import_metadata();
}

/*else {
$this->_delete_transient_import_metadata();
}*/
}

foreach ($this->get_slices($transformationContext->id, $limit, $offset) as $slice) {
Expand Down Expand Up @@ -257,22 +265,6 @@ function($accu, $row) {
},
[],
);
/*
array_reduce(
\get_posts([
'fields' => 'ids',
'numberposts'=>-1,
'post_type' => 'any',
'meta_query' => [
['key' => self::KEY_TRANSIENT_IMPORT_METADATA, 'compare' => 'EXISTS', ],
],
]),
function($accu, $post_id) {
$accu[(int)\get_post_meta($post_id, self::KEY_TRANSIENT_IMPORT_METADATA, true)] = $post_id;
return $accu;
},
[],
);*/

$imported = [
'terms' => &$imported_term_ids,
Expand Down
20 changes: 14 additions & 6 deletions plugins/cm4all-wp-impex/src/components/import.mjs
Expand Up @@ -53,6 +53,7 @@ export default function Import() {
const [importProfile, setImportProfile] = element.useState();

const [cleanupContent, setCleanupContent] = element.useState(true);
const [cleanupMedia, setCleanupMedia] = element.useState(true);

element.useEffect(() => {
if (importProfiles.length === 1) {
Expand All @@ -75,17 +76,17 @@ export default function Import() {
),
});

await consumeImport(_import.id, {
await consumeImport(_import.id, {
// @see PHP class ImpexExport::OPTION_CLEANUP_CONTENTS
'impex-import-option-cleanup_contents' : cleanupContent,
},
null,
},
null,
null
);

setProgress();
};

const onUpload = async () => {
let importDirHandle = null;
// showDirectoryPicker will throw a DOMException in case the user pressed cancel
Expand Down Expand Up @@ -158,13 +159,20 @@ export default function Import() {
className="import-options-form"
>
<components.ToggleControl
help={ cleanupContent ? __("Clean up existing post, page, media, block pattern, nav_menu an reusable block items", "cm4all-wp-impex") : __("Keep existing post, page, media, block pattern, nav_menu an reusable block items. Media might be partly overwritten by export", "cm4all-wp-impex") }
help={ cleanupContent ? __("Clean up existing post, page, block pattern, nav_menu an reusable block items", "cm4all-wp-impex") : __("Keep existing post, page, block pattern, nav_menu an reusable block items.", "cm4all-wp-impex") }
checked={ cleanupContent }
disabled={ !imports.length }
onChange={ setCleanupContent }
label={__("Remove existing content before importing uploaded snapshot", "cm4all-wp-impex")}
>
</components.ToggleControl>
<components.ToggleControl
help={ cleanupMedia ? __("Clean up existing media like images and videos (located at WordPress uploads)", "cm4all-wp-impex") : __("Keep existing media items. Media might be partly overwritten by export", "cm4all-wp-impex") }
checked={ cleanupMedia }
disabled={ !imports.length }
onChange={ setCleanupMedia }
label={__("Remove existing media before import", "cm4all-wp-impex")}
>
</components.ToggleControl>
</components.PanelBody>
{imports.map((_, index) => (
<components.PanelBody
Expand Down
25 changes: 21 additions & 4 deletions plugins/cm4all-wp-impex/src/components/screen.mjs
Expand Up @@ -54,7 +54,7 @@ async function ImportExportGeneratorConsumer(gen, setProgress, defaultErrorPopup
),
});
break;
case "info":
case "info":
gen.next(new Promise((resolve) => {
setProgress({
component: (
Expand Down Expand Up @@ -124,10 +124,20 @@ function SimpleTab() {

const [progress, setProgress] = element.useState(null);
const [cleanupContent, setCleanupContent] = element.useState(true);
const [cleanupMedia, setCleanupMedia] = element.useState(true);

const _createAndUploadConsumeImport = async () => {
console.log({ importProfile, screenContext });
const gen = await createAndUploadConsumeImport(importProfile, cleanupContent, screenContext);
const gen = await createAndUploadConsumeImport(
importProfile,
{
// @see PHP class ImpexExport::OPTION_CLEANUP_CONTENTS
'impex-import-option-cleanup_contents' : cleanupContent,
// @see PHP class ImpexExport::OPTION_CLEANUP_MEDIA
'impex-import-option-cleanup_media' : cleanupMedia,
},
screenContext
);

await ImportExportGeneratorConsumer(gen, setProgress, __("Import failed", "cm4all-wp-impex"));
};
Expand Down Expand Up @@ -170,14 +180,21 @@ function SimpleTab() {
onChange={setImportProfile}
/>
<components.ToggleControl
help={ cleanupContent ? __("Clean up existing post, page, media, block pattern, nav_menu an reusable block items", "cm4all-wp-impex") : __("Keep existing post, page, media, block pattern, nav_menu an reusable block items. Media might be partly overwritten by export", "cm4all-wp-impex") }
help={ cleanupContent ? __("Clean up existing post, page, block pattern, nav_menu an reusable block items", "cm4all-wp-impex") : __("Keep existing post, page, block pattern, nav_menu an reusable block items.", "cm4all-wp-impex") }
checked={ cleanupContent }
onChange={ setCleanupContent }
label={__("Remove existing content before import", "cm4all-wp-impex")}
>
</components.ToggleControl>
<components.ToggleControl
help={ cleanupMedia ? __("Clean up existing media like images and videos (located at WordPress uploads)", "cm4all-wp-impex") : __("Keep existing items. Media might be partly overwritten by export", "cm4all-wp-impex") }
checked={ cleanupMedia }
onChange={ setCleanupMedia }
label={__("Remove existing media before import", "cm4all-wp-impex")}
>
</components.ToggleControl>
<components.Button
isDestructive
isDestructive
isPrimary
disabled={!importProfile}
onClick={_createAndUploadConsumeImport}
Expand Down
23 changes: 10 additions & 13 deletions plugins/cm4all-wp-impex/src/wp.impex.store.mjs
Expand Up @@ -33,9 +33,9 @@ export default async function (settings) {

const actions = {
// this is a redux thunk (see https://make.wordpress.org/core/2021/10/29/thunks-in-gutenberg/)
createAndUploadConsumeImport : (importProfile, cleanupContent, screenContext) =>
createAndUploadConsumeImport : (importProfile, importOptions, screenContext) =>
async function* ({ dispatch, registry, resolveSelect, select }) {
debug({importProfile, cleanupContent});
debug({importProfile, importOptions});

let importDirHandle = null;
// showDirectoryPicker will throw a DOMException in case the user pressed cancel
Expand All @@ -62,7 +62,7 @@ export default async function (settings) {
importProfile, { }))
.payload;


try {
yield {
type: "progress",
Expand All @@ -82,12 +82,9 @@ export default async function (settings) {


await dispatch.consumeImport(
createdImport.id,
{
// @see PHP class ImpexExport::OPTION_CLEANUP_CONTENTS
'impex-import-option-cleanup_contents' : cleanupContent,
},
null,
createdImport.id,
importOptions,
null,
null
);

Expand Down Expand Up @@ -179,10 +176,10 @@ export default async function (settings) {
);

debug({ exportDirHandle });

let createdExport = null;

try {
try {
// const exports = select.getExports();
// debug({ exports });

Expand Down Expand Up @@ -356,14 +353,14 @@ export default async function (settings) {
data: { options },
});

// process returned callbacks
// process returned callbacks
const postConsumeCallbacks = callbacks.map(
callback => apiFetch({
path : `${settings.base_uri}/${callback.path}`,
method: callback.method,
data: callback.data,
}).catch(error => {
// silently ignore errors from timed out metadata updates
// silently ignore errors from timed out metadata updates
if(error.code==='fetch_error') {
log.push({
type: 'warning',
Expand Down

0 comments on commit 6e351ad

Please sign in to comment.