-
Notifications
You must be signed in to change notification settings - Fork 2
/
move_file.drush
75 lines (59 loc) · 2.03 KB
/
move_file.drush
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
#!/usr/bin/env drush
/**
* Usage: drush move_file.drush
*/
use Drupal\file\Entity\File;
drush_print('Ready to move private image files...');
$confirm = drush_confirm('Do you want to move all managed private image files to public files?');
// Stop if confirmation step failed.
if (!$confirm) {
drush_set_context('DRUSH_EXECUTION_COMPLETED', TRUE);
drush_set_context('DRUSH_EXIT_CODE', DRUSH_SUCCESS);
exit(0);
}
// Select all private image files.
$file_ids = \Drupal::database()->select('file_managed', 'f')
->fields('f', ['fid'])
->condition('f.uri', 'private://%', 'LIKE')
->condition('f.filemime', 'image%', 'LIKE')
->execute()->fetchCol();
// Exit if we have nothing to do.
if (empty($file_ids)) {
drush_print('Nothing to do...');
drush_set_context('DRUSH_EXECUTION_COMPLETED', TRUE);
drush_set_context('DRUSH_EXIT_CODE', DRUSH_SUCCESS);
exit(0);
}
$time_start = microtime(true);
$chunks = array_chunk($file_ids, 50);
// Process the file chunks.
foreach ($chunks as $chunk) {
process_files($chunk);
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start);
drush_print('Finished processing ' . count($file_ids) . ' files...');
drush_print('Total Execution Time: ' . round($execution_time, 2) . ' seconds');
drush_print('You may consider clearing the cache now.');
/**
* Process files.
*/
function process_files($file_ids) {
drush_print('Starting to process files...');
$i = 0;
$total = count($file_ids);
$files = File::loadMultiple($file_ids);
// Loop through the files.
foreach ($files as $file) {
// Loop through the results and move them to the public folder.
$destination = $file->getFileUri();
// Change the destination and move the file.
$destination = str_replace('private', 'public', $destination);
if (file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
file_move($file, $destination);
}
drush_print('Processed file with ID ' . $file->id() . ' (' . ($i + 1) . '/' . $total . ')');
$i++;
}
drush_print('Processed ' . $i . ' files...');
}