Skip to content

Instantly share code, notes, and snippets.

@caugner
Created August 25, 2017 17:46
Show Gist options
  • Save caugner/ec133c65993e86c028030cbe089cfffd to your computer and use it in GitHub Desktop.
Save caugner/ec133c65993e86c028030cbe089cfffd to your computer and use it in GitHub Desktop.
Migrate Trac 0.10 attachments to 1.0 attachments.
<?php
/**
* Migrates Trac 0.10 attachments to 1.0 attachments.
*
* Based on:
* - https://trac.edgewall.org/browser/branches/1.0-stable/trac/upgrades/db28.py
* - https://trac.edgewall.org/browser/branches/1.0-stable/trac/attachment.py
*/
if ($argc != 3) {
printf("USAGE: %s INPUT_DIR OUTPUT_DIR", $argv[0]);
exit(1);
} else if(!is_dir($argv[1])) {
printf("ERROR: %s is not a valid INPUT_DIR!", $argv[1]);
exit(1);
} else if (!is_dir($argv[2])) {
printf("ERROR: %s is not a valid OUTPUT_DIR!", $argv[2]);
exit(1);
}
define('INPUT_DIR', realpath($argv[1]));
define('OUTPUT_DIR', realpath($argv[2]));
$files = [];
// Determine attachments to migrate.
$fh = opendir(INPUT_DIR);
while ($ticket = readdir($fh)) {
if (in_array($ticket, ['.', '..'])) {
continue;
}
$fh2 = opendir(INPUT_DIR . DIRECTORY_SEPARATOR . $ticket);
while ($file = readdir($fh2)) {
if (in_array($file, ['.', '..'])) {
continue;
}
$files[] = [
$ticket, $file
];
}
}
// Migrate attachments.
foreach ($files as $ticketAndFile) {
list($ticket, $file) = $ticketAndFile;
// Ticket id.
$parent_hash = sha1($ticket);
$prefix = substr($parent_hash, 0, 3);
// Filename.
$decoded_file = rawurldecode($file);
$file_hash = sha1($decoded_file);
// File extension.
preg_match("/\.[A-Za-z0-9]+\Z/", $decoded_file, $match);
$file_extension = $match[0];
// Directory.
$source_directory = INPUT_DIR . DIRECTORY_SEPARATOR . $ticket . DIRECTORY_SEPARATOR;
$target_directory = OUTPUT_DIR . DIRECTORY_SEPARATOR . $prefix . DIRECTORY_SEPARATOR . $parent_hash . DIRECTORY_SEPARATOR;
if (!is_dir($target_directory)) {
mkdir($target_directory, 0777, true);
}
// Path.
$source = $source_directory . $file;
$target = $target_directory . $file_hash . $file_extension;
copy($source, $target);
// Log.
printf("%s\n -> \n%s\n\n", $source, $target);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment