Skip to content

Handlers #40

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
merged 3 commits into from
Feb 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/unused.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,4 @@ jobs:
fi

- name: Detect unused packages
run: composer-unused -vvv --profile --ansi --no-interaction --no-progress --excludePackage=php --excludePackage=tatter/alerts --excludePackage=tatter/preferences --excludePackage=tatter/thumbnails
run: composer-unused -vvv --output-format=github --ansi --no-interaction --no-progress
14 changes: 14 additions & 0 deletions composer-unused.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

use ComposerUnused\ComposerUnused\Configuration\Configuration;
use ComposerUnused\ComposerUnused\Configuration\NamedFilter;

return static function (Configuration $config): Configuration {
return $config
->addNamedFilter(NamedFilter::fromString('enyo/dropzone'))
->setAdditionalFilesFor('tatter/preferences', [
__DIR__ . '/vendor/tatter/preferences/src/Helpers/preferences_helper.php',
]);
};
5 changes: 2 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,11 @@
"php": "^7.4 || ^8.0",
"codeigniter4/authentication-implementation": "^1.0",
"enyo/dropzone": "^6.0",
"tatter/alerts": "^2.0",
"tatter/exports": "^2.0",
"tatter/exports": "^3.0",
"tatter/frontend": "^1.0",
"tatter/permits": "^3.0",
"tatter/preferences": "^1.0",
"tatter/thumbnails": "^1.2"
"tatter/thumbnails": "^2.0"
},
"require-dev": {
"codeigniter4/devkit": "^1.0",
Expand Down
1 change: 0 additions & 1 deletion phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ parameters:
- src/Helpers
- vendor/codeigniter4/framework/system/Helpers
- vendor/tatter/alerts/src/Helpers
- vendor/tatter/handlers/src/Helpers
- vendor/tatter/imposter/src/Helpers
- vendor/tatter/preferences/src/Helpers
dynamicConstantNames:
Expand Down
4 changes: 2 additions & 2 deletions src/Config/Files.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,12 @@ public function getPath(): string
$this->path = rtrim($storage, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

// Check or create the thumbnails subdirectory
$thumbnails = $storage . 'thumbnails';
$thumbnails = $this->path . 'thumbnails';
if (! is_dir($thumbnails) && ! @mkdir($thumbnails, 0775, true)) {
throw FilesException::forDirFail($thumbnails); // @codeCoverageIgnore
}

return $storage;
return $this->path;
}

/**
Expand Down
115 changes: 61 additions & 54 deletions src/Controllers/Files.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\ResponseInterface;
use RuntimeException;
use Tatter\Exports\Exceptions\ExportsException;
use Tatter\Exports\Factories\ExporterFactory;
use Tatter\Files\Config\Files as FilesConfig;
use Tatter\Files\Entities\File;
use Tatter\Files\Exceptions\FilesException;
Expand All @@ -30,7 +32,7 @@ class Files extends Controller
/**
* Helpers to load.
*/
protected $helpers = ['alerts', 'files', 'handlers', 'html', 'preferences', 'text'];
protected $helpers = ['alerts', 'files', 'html', 'preferences', 'text'];

/**
* Overriding data for views.
Expand Down Expand Up @@ -139,7 +141,7 @@ public function user($userId = null)
if ($userId === null) {
// Check for list permission
if (! $this->model->mayList()) {
return $this->failure(403, lang('Permits.notPermitted'));
return $this->failure(403, lang('Files.notPermitted'));
}

$this->setData([
Expand All @@ -152,7 +154,7 @@ public function user($userId = null)
elseif ((int) $userId !== user_id()) {
// Check for list permission
if (! $this->model->mayList()) {
return $this->failure(403, lang('Permits.notPermitted'));
return $this->failure(403, lang('Files.notPermitted'));
}

$this->setData([
Expand Down Expand Up @@ -188,7 +190,7 @@ public function new()
{
// Check for create permission
if (! $this->model->mayCreate()) {
return $this->failure(403, lang('Permits.notPermitted'));
return $this->failure(403, lang('Files.notPermitted'));
}

return view('Tatter\Files\Views\new');
Expand Down Expand Up @@ -248,7 +250,7 @@ public function delete($fileId)
return $this->failure(400, lang('Files.noFile'));
}
if (! $this->model->mayDelete($file)) {
return $this->failure(403, lang('Permits.notPermitted'));
return $this->failure(403, lang('Files.notPermitted'));
}

if ($this->model->delete($fileId)) {
Expand Down Expand Up @@ -296,20 +298,21 @@ public function bulk(): ResponseInterface
}

// Bulk export of some kind, match the handler
if (! $handler = handlers('Exports')->where(['slug' => $action])->first()) {
return $this->failure(400, 'No handler found for ' . $action);
try {
$handler = ExporterFactory::find($action);
} catch (RuntimeException $e) {
return $this->failure(400, 'No export handler found for ' . $action);
}

$export = new $handler();
$exporter = new $handler();

foreach ($fileIds as $fileId) {
if ($file = $this->model->find($fileId)) {
$export->setFile($file->object->setBasename($file->filename));
$exporter->setFile($file->object->setBasename($file->filename));
}
}

try {
$result = $export->process();
$result = $exporter->process();
} catch (ExportsException $e) {
return $this->failure(400, $e->getMessage());
}
Expand All @@ -328,7 +331,7 @@ public function upload()
{
// Check for create permission
if (! $this->model->mayCreate()) {
return $this->failure(403, lang('Permits.notPermitted'));
return $this->failure(403, lang('Files.notPermitted'));
}

// Verify upload succeeded
Expand Down Expand Up @@ -394,7 +397,13 @@ public function upload()
$data['clientname'] ??= $upload->getClientName();

// Accept the file
$file = $this->model->createFromPath($path ?? $upload->getRealPath(), $data);
try {
$file = $this->model->createFromPath($path ?? $upload->getRealPath(), $data);
} catch (Throwable $e) {
log_message('error', $e->getMessage());

return $this->failure(400, $e->getMessage());
}

// Trigger the Event with the new File
Events::trigger('upload', $file);
Expand All @@ -411,22 +420,21 @@ public function upload()
/**
* Processes Export requests.
*
* @param string $slug The slug to match to Exports attribute
* @param int|string $fileId
*/
public function export(string $slug, $fileId): ResponseInterface
public function export(string $handlerId, $fileId): ResponseInterface
{
// Match the export handler
$handler = handlers('Exports')->where(['slug' => $slug])->first();
if (empty($handler)) {
alert('warning', 'No handler found for ' . $slug);
try {
$handler = ExporterFactory::find($handlerId);
} catch (RuntimeException $e) {
alert('warning', 'No export handler found for ' . $handlerId);

return redirect()->back();
}

// Load the file
$file = $this->model->find($fileId);
if (empty($file)) {
if (empty($fileId) || null === $file = $this->model->find($fileId)) {
alert('warning', lang('Files.noFile'));

return redirect()->back();
Expand All @@ -442,21 +450,22 @@ public function export(string $slug, $fileId): ResponseInterface

// Create the record
model(ExportModel::class)->insert([
'handler' => $slug,
'handler' => $handlerId,
'file_id' => $file->id,
'user_id' => user_id(),
]);

// Pass to the handler
$export = new $handler($file->object);
$response = $export->setFilename($file->filename)->process();
$exporter = new $handler($file->object);
$exporter->setFilename($file->filename);

// If the handler returned a response then we're done
if ($response instanceof ResponseInterface) {
return $response;
try {
$result = $exporter->process();
} catch (ExportsException $e) {
return $this->failure(400, $e->getMessage());
}

return redirect()->back();
return $result;
}

/**
Expand All @@ -466,9 +475,13 @@ public function export(string $slug, $fileId): ResponseInterface
*/
public function thumbnail($fileId): ResponseInterface
{
$path = ($file = $this->model->find($fileId)) ? $file->getThumbnail() : File::locateDefaultThumbnail();
$path = ($file = $this->model->find($fileId))
? $file->getThumbnail()
: File::locateDefaultThumbnail();

return $this->response->setHeader('Content-type', 'image/jpeg')->setBody(file_get_contents($path));
return $this->response
->setHeader('Content-type', 'image/jpeg')
->setBody(file_get_contents($path));
}

/**
Expand Down Expand Up @@ -510,9 +523,26 @@ protected function setData(array $data, bool $overwrite = false): self
*/
protected function setDefaults(): self
{
// Get bulk support and index Exporters by the extension(s) they support
$bulks = [];
$exporters = [];

foreach (ExporterFactory::findAll() as $handler) {
$attributes = $handler::attributes();

if ($attributes['bulk']) {
$bulks[] = $handler;
}

foreach ($attributes['extensions'] as $extension) {
$exporters[$extension][] = $attributes;
}
}

$this->setData([
'source' => 'index',
'layout' => 'files',
'model' => $this->model,
'files' => null,
'selected' => explode(',', $this->request->getVar('selected') ?? ''),
'userId' => null,
Expand All @@ -522,8 +552,8 @@ protected function setDefaults(): self
'page' => $this->request->getVar('page'),
'pager' => null,
'access' => $this->model->mayAdmin() ? 'manage' : 'display',
'exports' => $this->getExports(),
'bulks' => handlers()->where(['bulk' => 1])->findAll(),
'exports' => $exporters,
'bulks' => $bulks,
]);

// Add preferences
Expand Down Expand Up @@ -563,27 +593,4 @@ protected function setPreferences(): self

return $this;
}

/**
* Gets Export handlers indexed by the extension they support.
*
* @return array<string, array>
*/
protected function getExports(): array
{
$exports = [];

foreach (handlers('Exports')->findAll() as $class) {
$attributes = handlers()->getAttributes($class);

// Add the class name for easy access later
$attributes['class'] = $class;

foreach (explode(',', $attributes['extensions']) as $extension) {
$exports[$extension][] = $attributes;
}
}

return $exports;
}
}
30 changes: 4 additions & 26 deletions src/Entities/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ class File extends Entity
'updated_at',
'deleted_at',
];
protected $attributes = [
'thumbnail' => '',
];

/**
* Resolved path to the default thumbnail
Expand Down Expand Up @@ -92,38 +95,13 @@ public function getObject(): ?FileObject
}
}

/**
* Returns class names of Exports applicable to this file's extension
*
* @param bool $asterisk Whether to include generic "*" extensions
*
* @return string[]
*/
public function getExports($asterisk = true): array
{
$exports = [];

if ($extension = $this->getExtension()) {
$exports = handlers('Exports')->where(['extensions has' => $extension])->findAll();
}

if ($asterisk) {
$exports = array_merge(
$exports,
handlers('Exports')->where(['extensions' => '*'])->findAll()
);
}

return $exports;
}

/**
* Returns the path to this file's thumbnail, or the default from config.
* Should always return a path to a valid file to be safe for img_data()
*/
public function getThumbnail(): string
{
$path = config('Files')->getPath() . 'thumbnails' . DIRECTORY_SEPARATOR . ($this->attributes['thumbnail'] ?? '');
$path = config('Files')->getPath() . 'thumbnails' . DIRECTORY_SEPARATOR . $this->attributes['thumbnail'];

if (! is_file($path)) {
$path = self::locateDefaultThumbnail();
Expand Down
1 change: 1 addition & 0 deletions src/Language/en/Files.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

return [
// Exceptions
'notPermitted' => 'You do not have permission to do that.',
'noAuth' => 'Missing dependency: authentication function user_id()',
'dirFail' => 'Unable to create storage directory: {0}',
'chunkDirFail' => 'Unable to create directory for chunk uploads: {0}',
Expand Down
Loading