Repository navigation
Add a submission:download Artisan command
#4308
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
williamjallen
merged 1 commit into
Kitware:master
from
williamjallen:submission-download-command
Dec 3, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,272 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\Console\Commands; | ||
|
|
||
| use App\Models\Submission; | ||
| use App\Utils\ConsoleUtils; | ||
| use Illuminate\Console\Command; | ||
| use Illuminate\Support\Facades\Storage; | ||
| use Illuminate\Support\Str; | ||
| use RuntimeException; | ||
| use Symfony\Component\Console\Formatter\OutputFormatter; | ||
| use Symfony\Component\Console\Output\OutputInterface; | ||
| use Symfony\Component\Console\Output\StreamOutput; | ||
| use Throwable; | ||
|
|
||
| class DownloadSubmission extends Command | ||
| { | ||
| /** | ||
| * The name and signature of the console command. | ||
| * | ||
| * @var string | ||
| */ | ||
| protected $signature = 'submission:download | ||
| {id : The submission\'s ID, as listed by submission:list} | ||
| {--output= : Write the file here instead of to stdout. A directory gets the file under its default name} | ||
| {--force : Overwrite the file at --output if there is one}'; | ||
|
|
||
| /** | ||
| * The console command description. | ||
| * | ||
| * @var string | ||
| */ | ||
| protected $description = 'Write out a submitted file as it was received'; | ||
|
|
||
| /** | ||
| * The file is read in parts of this size. A NUL byte in the first marks it as binary. | ||
| */ | ||
| private const CHUNK_LENGTH = 8192; | ||
|
|
||
| /** | ||
| * The most of a client's filename kept in a default name, leaving room for the ID within the 255 bytes that most | ||
| * filesystems allow. | ||
| */ | ||
| private const MAX_CLIENT_NAME_LENGTH = 200; | ||
|
|
||
| /** | ||
| * Execute the console command. | ||
| */ | ||
| public function handle(): int | ||
| { | ||
| $id = (string) $this->argument('id'); | ||
| if (!Str::isUuid($id)) { | ||
| return $this->failWith("{$id} is not a valid submission ID"); | ||
| } | ||
|
|
||
| $output = $this->option('output'); | ||
| $writes_to_file = is_string($output) && $output !== ''; | ||
| if (!$writes_to_file && $this->input->hasParameterOption('--output')) { | ||
| return $this->failWith('--output needs a path'); | ||
| } | ||
|
|
||
| $submission = Submission::find($id); | ||
| if ($submission === null) { | ||
| return $this->failWith("Submission {$id} does not exist"); | ||
| } | ||
|
|
||
| // The target is checked before reading the file, which on S3 downloads it. | ||
| $target = null; | ||
| if ($writes_to_file) { | ||
| $target = $this->checkedTarget($submission, (string) $output); | ||
| if ($target === null) { | ||
| return self::FAILURE; | ||
| } | ||
| } | ||
|
|
||
| try { | ||
| if (!Storage::fileExists($submission->path)) { | ||
| return $this->failWith("The file of submission {$id} was not found at {$submission->path}"); | ||
| } | ||
| $source = Storage::readStream($submission->path); | ||
| if ($source === null) { | ||
| throw new RuntimeException("Unable to read {$submission->path}"); | ||
| } | ||
| } catch (Throwable $e) { | ||
| return $this->failWith("The file of submission {$id} could not be read: " . ConsoleUtils::errorCause($e)); | ||
| } | ||
|
|
||
| try { | ||
| return $target === null ? $this->writeToStdout($source) : $this->writeToFile($source, $target); | ||
| } finally { | ||
| fclose($source); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Copy the file to stdout. The file is the command's output rather than a message, so it's written even with | ||
| * --quiet, and a failure to write it, such as to a closed pipe or a full disk, fails the command. On a terminal, a | ||
| * binary file isn't written, and any other file is shown with its control characters escaped. | ||
| * | ||
| * @param resource $source | ||
| */ | ||
| private function writeToStdout($source): int | ||
| { | ||
| try { | ||
| $chunk = stream_get_contents($source, self::CHUNK_LENGTH); | ||
| if ($chunk === false) { | ||
| throw new RuntimeException('Unable to read the file'); | ||
| } | ||
| $terminal = $this->writesToTerminal(); | ||
| if ($terminal && str_contains($chunk, "\0")) { | ||
| return $this->failWith('This file is binary, so it isn\'t written to the terminal. Redirect the output or use --output.'); | ||
| } | ||
|
|
||
| $output = $this->output->getOutput(); | ||
| $held = ''; | ||
| while (true) { | ||
| $at_end = feof($source); | ||
| if ($terminal) { | ||
| // Unless the file ends there, a "\r" or "\xC2" at the end of a part is held back for the next, which | ||
| // could finish it as a line break or a C1 control. | ||
| $chunk = $held . $chunk; | ||
| $held = !$at_end && (str_ends_with($chunk, "\r") || str_ends_with($chunk, "\xC2")) ? $chunk[-1] : ''; | ||
| $chunk = ConsoleUtils::printable(substr($chunk, 0, strlen($chunk) - strlen($held))); | ||
| } | ||
| self::writeRaw($output, $chunk); | ||
| if ($at_end) { | ||
| break; | ||
| } | ||
| $chunk = fread($source, self::CHUNK_LENGTH); | ||
| if ($chunk === false) { | ||
| throw new RuntimeException('Unable to read the file'); | ||
| } | ||
| } | ||
| if ($output instanceof StreamOutput && !fflush($output->getStream())) { | ||
| throw new RuntimeException('Unable to write to stdout'); | ||
| } | ||
| } catch (Throwable $e) { | ||
| // A reader that stops early, such as head, closes the pipe. Like cat, the command says nothing about it. | ||
| if (str_contains($e->getMessage(), 'Broken pipe')) { | ||
| return self::FAILURE; | ||
| } | ||
| return $this->failWith('The file could not be copied: ' . ConsoleUtils::errorCause($e)); | ||
| } | ||
|
|
||
| return self::SUCCESS; | ||
| } | ||
|
|
||
| /** | ||
| * Write to stdout as is. Output that isn't a stream, such as when the command is called from code, reports no | ||
| * write errors. | ||
| */ | ||
| private static function writeRaw(OutputInterface $output, string $data): void | ||
| { | ||
| if (!$output instanceof StreamOutput) { | ||
| $output->write($data, false, OutputInterface::OUTPUT_RAW | OutputInterface::VERBOSITY_QUIET); | ||
| } elseif (fwrite($output->getStream(), $data) !== strlen($data)) { | ||
| throw new RuntimeException('Unable to write to stdout'); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * The file to write to: the given path, or the default name inside it if it's a directory. Null after reporting | ||
| * a target that mustn't or can't be written. | ||
| */ | ||
| private function checkedTarget(Submission $submission, string $output): ?string | ||
| { | ||
| $target = is_dir($output) ? rtrim($output, '/') . '/' . self::defaultName($submission) : $output; | ||
| if (str_ends_with($target, '/')) { | ||
| $this->failWith("{$output} isn't a directory"); | ||
| return null; | ||
| } | ||
| if (file_exists($target) && !is_file($target)) { | ||
| $this->failWith("{$target} exists and isn't a regular file"); | ||
| return null; | ||
| } | ||
| if ((is_link($target) || file_exists($target)) && $this->option('force') !== true) { | ||
| $this->failWith("{$target} already exists. Use --force to overwrite it."); | ||
|
williamjallen marked this conversation as resolved.
Resolved
|
||
| return null; | ||
| } | ||
| $directory = dirname($target); | ||
| if (!is_dir($directory) || !is_writable($directory)) { | ||
| $this->failWith("Can't write to the directory {$directory}"); | ||
| return null; | ||
| } | ||
| return $target; | ||
| } | ||
|
|
||
| /** | ||
| * Copy the file to the given path. The copy goes to a temporary file beside the target, which only replaces the | ||
| * target once it's complete. | ||
| * | ||
| * @param resource $source | ||
| */ | ||
| private function writeToFile($source, string $target): int | ||
| { | ||
| $directory = dirname($target); | ||
| $temporary = false; | ||
| try { | ||
| // tempnam() creates the file readable by its owner only. If it can't create it here, it creates it in | ||
| // the system's temporary directory instead, with a notice. | ||
| $temporary = @tempnam($directory, '.' . basename($target) . '.'); | ||
| if ($temporary === false || dirname($temporary) !== realpath($directory)) { | ||
| throw new RuntimeException("Unable to create a temporary file in {$directory}"); | ||
| } | ||
| $destination = fopen($temporary, 'wb'); | ||
| if ($destination === false) { | ||
| throw new RuntimeException("Unable to write {$target}"); | ||
| } | ||
| try { | ||
| $bytes = stream_copy_to_stream($source, $destination); | ||
| if ($bytes === false || !fflush($destination)) { | ||
| throw new RuntimeException("Unable to write {$target}"); | ||
| } | ||
| } finally { | ||
| fclose($destination); | ||
| } | ||
| if (!rename($temporary, $target)) { | ||
| throw new RuntimeException("Unable to move {$temporary} to {$target}"); | ||
| } | ||
| } catch (Throwable $e) { | ||
| if ($temporary !== false) { | ||
| @unlink($temporary); | ||
| } | ||
| return $this->failWith('The file could not be copied: ' . ConsoleUtils::errorCause($e)); | ||
| } | ||
|
|
||
| $this->output->getErrorStyle()->writeln( | ||
| OutputFormatter::escape("Wrote {$target} (" . number_format((int) ceil($bytes / 1024)) . ' KB)') | ||
| ); | ||
| return self::SUCCESS; | ||
| } | ||
|
|
||
| /** | ||
| * The name the file is written under in a directory: the submission's ID, followed by ".xml" for an XML file, or | ||
| * the name the client gave a data file. That name comes from the uploader, so only the end of its base name is | ||
| * kept, in safe characters. | ||
| */ | ||
| private static function defaultName(Submission $submission): string | ||
| { | ||
| if ($submission->filename === null) { | ||
| return "{$submission->id}.xml"; | ||
| } | ||
|
|
||
| $filename = basename(str_replace('\\', '/', $submission->filename)); | ||
| $filename = substr((string) preg_replace('/[^A-Za-z0-9._-]/', '_', $filename), -self::MAX_CLIENT_NAME_LENGTH); | ||
| return $filename === '' ? $submission->id : "{$submission->id}-{$filename}"; | ||
| } | ||
|
|
||
| /** | ||
| * Whether stdout is a terminal, which control characters in the file could act on. | ||
| */ | ||
| protected function writesToTerminal(): bool | ||
| { | ||
| $output = $this->output->getOutput(); | ||
| return $output instanceof StreamOutput && stream_isatty($output->getStream()); | ||
| } | ||
|
|
||
| /** | ||
| * Report an error on stderr, so that it never mixes with a file written to stdout, even with --quiet. A message can | ||
| * include text from elsewhere, such as a storage error, so its control characters are escaped. | ||
| */ | ||
| private function failWith(string $message): int | ||
| { | ||
| $this->output->getErrorStyle()->writeln( | ||
| '<error>' . OutputFormatter::escape(ConsoleUtils::printable($message)) . '</error>', | ||
| OutputInterface::VERBOSITY_QUIET, | ||
| ); | ||
| return self::FAILURE; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\Utils; | ||
|
|
||
| use Throwable; | ||
|
|
||
| class ConsoleUtils | ||
| { | ||
| /** | ||
| * Text that can be shown on a terminal without acting on it: line breaks become "\n", and control characters other | ||
| * than tabs, including the C1 controls U+0080 to U+009F, are shown as \xNN. | ||
| */ | ||
| public static function printable(string $text): string | ||
| { | ||
| return (string) preg_replace_callback( | ||
| '/[\x00-\x08\x0B-\x1F\x7F]|\xC2[\x80-\x9F]/', | ||
| fn (array $match): string => sprintf('\x%02X', ord($match[0][-1])), | ||
| str_replace(["\r\n", "\r"], "\n", $text), | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * The cause of an error on one line. Storage errors such as the AWS SDK's spread it over several lines. | ||
| */ | ||
| public static function errorCause(Throwable $e): string | ||
| { | ||
| $message = trim($e->getPrevious()?->getMessage() ?? ''); | ||
| if ($message === '') { | ||
| $message = trim($e->getMessage()); | ||
| } | ||
| return rtrim((string) preg_replace('/\s+/', ' ', $message), '. '); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.