Migrates Drupal managed image to new directory specified in the field instance settings. Takes argument entity and bundle containing the image field.
<?php | |
$args = drush_get_arguments(); | |
$entities = array(); | |
$entity_info = entity_get_info(); | |
foreach ($entity_info as $name => $info) { | |
$entities[$name] = array_keys($info['bundles']); | |
} | |
if ( ! isset($args[2]) || ! isset($entities[$args[2]]) ) { | |
echo "Invalid of missing entity.\n"; | |
drush_set_error('Usage: drush @<alias> scr fix-image-location.php <entity> <bundle>'); | |
exit(); | |
} | |
$entity = $args[2]; | |
if ( ! isset($args[3]) || ! in_array($args[3], $entities[$entity]) ) { | |
echo "Invalid of missing bundle of $entity.\n"; | |
drush_set_error('Usage: drush @<alias> scr fix-image-location.php <entity> <bundle>'); | |
exit(); | |
} | |
$bundle = $args[3]; | |
$image_fields = array(); | |
foreach (field_info_instances($entity, $bundle) as $instance ) { | |
$info = field_info_field_by_id($instance['field_id']); | |
if ($info['type'] !== 'image' ) continue; | |
if (!$instance['settings']['file_directory']) continue; | |
$image_fields[$instance['field_name']] = $instance['settings']['file_directory']; | |
} | |
if (empty($image_fields)) { | |
echo "Entity $entity with bundle $bundle has no image fields.\n"; | |
drush_set_error('Usage: drush @<alias> scr fix-image-location.php <entity> <bundle>'); | |
exit(); | |
} | |
$query = new EntityFieldQuery; | |
$query->entityCondition('entity_type', $entity) | |
->entityCondition('bundle', $bundle); | |
$items = $query->execute(); | |
$ids = array(); | |
$migrated_files = array(); | |
if ( ! empty($items[$entity]) ) { | |
$objects = entity_load($entity, array_keys($items[$entity])); | |
foreach ($objects as $object) { | |
foreach ( $image_fields as $image_field => $file_directory ) { | |
$uri_destination = 'public://' . $file_directory; | |
$base_destination = dirname(drupal_realpath($uri_destination)); | |
if ( ! empty($object->{$image_field}) ) { | |
foreach ($object->{$image_field} as $lang => $files ) { | |
foreach ( $files as $file ) { | |
if ( in_array($file['fid'], $migrated_files) ) continue; | |
$sourceUri = $file['uri']; | |
$destinationUri = $uri_destination . '/' . basename($sourceUri); | |
if ( $sourceUri !== $destinationUri ) { | |
echo "$sourceUri to be moved to $destinationUri\n"; | |
copy(drupal_realpath($sourceUri), drupal_realpath($destinationUri)); | |
$file['uri'] = $destinationUri; | |
$file = (object) $file; | |
echo "Saving $file->fid with new uri $file->uri\n"; | |
file_save($file); | |
$migrated_files[] = $file->fid; | |
unlink(drupal_realpath($sourceUri)); | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment