Skip to content

Instantly share code, notes, and snippets.

@jbboehr
Created October 16, 2014 21:31
Show Gist options
  • Save jbboehr/5021c5ce4042fa6fbfa5 to your computer and use it in GitHub Desktop.
Save jbboehr/5021c5ce4042fa6fbfa5 to your computer and use it in GitHub Desktop.
<?php
$opts = getopt ('', array(
'access-key:',
'secret-key:',
'bucket:',
'prefix:',
'marker:'
));
if( !isset($opts['access-key'], $opts['secret-key'], $opts['bucket']) ) {
echo "--access-key --secret-key and --bucket are required\n";
exit(1);
}
require 'vendor/autoload.php';
function system_mime_type_extensions() {
# Returns the system MIME type mapping of MIME types to extensions, as defined in /etc/mime.types (considering the first
# extension listed to be canonical).
$out = array();
$file = fopen('/etc/mime.types', 'r');
while(($line = fgets($file)) !== false) {
$line = trim(preg_replace('/#.*/', '', $line));
if(!$line)
continue;
$parts = preg_split('/\s+/', $line);
if(count($parts) == 1)
continue;
$type = array_shift($parts);
if(!isset($out[$type]))
$out[$type] = array_shift($parts);
}
fclose($file);
return $out;
}
$mimes = array_flip(system_mime_type_extensions());
$aws = \Aws\Common\Aws::factory(array(
'key' => $opts['access-key'],
'secret' => $opts['secret-key']
));
$s3 = $aws->get('s3');
$iterator = $s3->getIterator('ListObjects', array_filter(array(
'Bucket' => $opts['bucket'],
'Prefix' => $opts['prefix'],
'Marker' => @$opts['marker'],
)));
foreach( $iterator as $item ) {
if( false === ($pos = strrpos($item['Key'], '.')) ) {
fwrite(STDERR, $item['Key'] . " - No file extension\n");
continue;
}
$extension = strtolower(substr($item['Key'], $pos+1));
if( !isset($mimes[$extension]) ) {
fwrite(STDERR, $item['Key'] . " - No mime for extension\n");
continue;
}
$mime = $mimes[$extension];
// Head object
$head = $s3->headObject(array(
'Bucket' => $opts['bucket'],
'Key' => $item['Key'],
));
if( $head['ContentType'] === $mime ) {
fwrite(STDERR, $item['Key']
. ' - Object is already at expected content type ' . $mime . "\n");
continue;
}
// Fix content type
try {
$result = $s3->copyObject(array_filter(array(
'ACL' => 'public-read',
'Bucket' => $opts['bucket'],
'CacheControl' => $head['CacheControl'],
'ContentDisposition' => $head['ContentDisposition'],
'ContentEncoding' => $head['ContentEncoding'],
'ContentLanguage' => $head['ContentLanguage'],
'ContentType' => $mime,
'CopySource' => $opts['bucket'] . '/' . $item['Key'],
'Expires' => $head['Expires'],
'Key' => $item['Key'],
'StorageClass' => $item['StorageClass'],
'ServerSideEncryption' => $head['ServerSideEncryption'],
)));
fwrite(STDERR, $item['Key'] . " - Content Type fixed to " . $mime . "\n");
} catch( \Exception $e ) {
echo $e;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment