Skip to content

Commit fee94c4

Browse files
committed
SUP-7425: add script for deleting media and files
1 parent d36bfe5 commit fee94c4

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

scripts/delete_media_file.php

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php
2+
3+
/**
4+
* @file
5+
* Script to delete media and associated file.
6+
*
7+
* Usage: drush php:script delete_media_file.php "fid1,fid2,fid3"
8+
*/
9+
10+
use Drupal\media\Entity\Media;
11+
use Drupal\file\Entity\File;
12+
$utils = \Drupal::service('islandora.utils');
13+
14+
// Get command line arguments
15+
// $extra is used by drush scr command
16+
// For drush php:script, use $_SERVER['argv']
17+
$input = isset($extra[0]) ? $extra[0] : (isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '');
18+
19+
if (empty($input)) {
20+
echo "Error: No input parameters provided.\n";
21+
echo "Usage: drush php:script delete_media_file.php \"fid1,fid2,fid3\"\n";
22+
exit(1);
23+
}
24+
25+
// Parse comma-separated string into an array.
26+
$fids = array_map('trim', explode(',', $input));
27+
28+
// Remove empty values.
29+
$fids = array_filter($fids);
30+
31+
if (empty($fids)) {
32+
echo "Error: No valid file IDs provided.\n";
33+
exit(1);
34+
}
35+
36+
echo "Processing " . count($fids) . " file(s)...\n\n";
37+
38+
foreach ($fids as $fid) {
39+
echo "--- Processing file: {$fid} ---\n";
40+
$file = File::load($fid);
41+
42+
if (!$file) {
43+
echo "Warning: Could not load file {$fid}\n";
44+
continue;
45+
}
46+
47+
foreach ($utils->getReferencingMedia($fid) as $media) {
48+
if ($media) {
49+
echo "Deleted media ID: " . $media->id() . "\n";
50+
$media->delete();
51+
}
52+
}
53+
echo "Deleted file ID: " . $file->id() . "\n";
54+
$file->delete();
55+
}
56+
57+
echo "\n";
58+
59+
echo "Processing complete.\n";

0 commit comments

Comments
 (0)