Atualizar src/Plugin.php

This commit is contained in:
Brasdrive 2025-11-05 09:18:26 -04:00
parent a7fb529c92
commit eb56df4c65
1 changed files with 238 additions and 238 deletions

View File

@ -1,238 +1,238 @@
<?php <?php
namespace FlysystemOffload; namespace FlysystemOffload;
use FlysystemOffload\Admin\SettingsPage; use FlysystemOffload\Admin\SettingsPage;
use FlysystemOffload\Filesystem\FilesystemFactory; use FlysystemOffload\Filesystem\FilesystemFactory;
use FlysystemOffload\Helpers\PathHelper; use FlysystemOffload\Helpers\PathHelper;
use FlysystemOffload\StreamWrapper\FlysystemStreamWrapper; use FlysystemOffload\StreamWrapper\FlysystemStreamWrapper;
use League\Flysystem\FilesystemOperator; use League\Flysystem\FilesystemOperator;
use WP_Error; use WP_Error;
class Plugin class Plugin
{ {
private static $instance; private static $instance;
private static string $pluginFile; private static string $pluginFile;
private ?FilesystemOperator $filesystem = null; private ?FilesystemOperator $filesystem = null;
private bool $streamRegistered = false; private bool $streamRegistered = false;
private array $settings = []; private array $settings = [];
public static function bootstrap(string $pluginFile): void public static function bootstrap(string $pluginFile): void
{ {
self::$pluginFile = $pluginFile; self::$pluginFile = $pluginFile;
register_activation_hook($pluginFile, [self::class, 'activate']); register_activation_hook($pluginFile, [self::class, 'activate']);
register_deactivation_hook($pluginFile, [self::class, 'deactivate']); register_deactivation_hook($pluginFile, [self::class, 'deactivate']);
add_action('plugins_loaded', static function () { add_action('plugins_loaded', static function () {
self::instance()->init(); self::instance()->init();
}); });
} }
public static function instance(): self public static function instance(): self
{ {
return self::$instance ??= new self(); return self::$instance ??= new self();
} }
public static function activate(): void public static function activate(): void
{ {
$defaults = [ $defaults = [
'adapter' => 'local', 'adapter' => 'local',
'base_prefix' => '', 'base_prefix' => '',
'adapters' => [ 'adapters' => [
's3' => [ 's3' => [
'access_key' => '', 'access_key' => '',
'secret_key' => '', 'secret_key' => '',
'region' => '', 'region' => '',
'bucket' => '', 'bucket' => '',
'endpoint' => '', 'endpoint' => '',
'cdn_url' => '' 'cdn_url' => ''
], ],
'sftp' => [ 'sftp' => [
'host' => '', 'host' => '',
'port' => 22, 'port' => 22,
'username' => '', 'username' => '',
'password' => '', 'password' => '',
'root' => '/uploads' 'root' => '/uploads'
], ],
'gcs' => [ 'gcs' => [
'project_id' => '', 'project_id' => '',
'bucket' => '', 'bucket' => '',
'key_file_path' => '' 'key_file_path' => ''
], ],
'azure' => [ 'azure' => [
'account_name' => '', 'account_name' => '',
'account_key' => '', 'account_key' => '',
'container' => '', 'container' => '',
'prefix' => '' 'prefix' => ''
], ],
'webdav' => [ 'webdav' => [
'base_uri' => '', 'base_uri' => '',
'username' => '', 'username' => '',
'password' => '', 'password' => '',
'path_prefix' => '' 'path_prefix' => ''
], ],
'googledrive' => [], 'googledrive' => [],
'onedrive' => [], 'onedrive' => [],
'dropbox' => [] 'dropbox' => []
] ]
]; ];
add_option('flysystem_offload_settings', $defaults); add_option('flysystem_offload_settings', $defaults);
} }
public static function deactivate(): void public static function deactivate(): void
{ {
if (in_array('fly', stream_get_wrappers(), true)) { if (in_array('fly', stream_get_wrappers(), true)) {
stream_wrapper_unregister('fly'); stream_wrapper_unregister('fly');
} }
} }
public function init(): void public function init(): void
{ {
$this->settings = get_option('flysystem_offload_settings', []); $this->settings = get_option('flysystem_offload_settings', []);
add_action( add_action(
'update_option_flysystem_offload_settings', 'update_option_flysystem_offload_settings',
function ($oldValue, $newValue) { function ($oldValue, $newValue) {
$this->settings = $newValue; $this->settings = $newValue;
$this->filesystem = null; $this->filesystem = null;
$this->streamRegistered = false; $this->streamRegistered = false;
$this->registerStreamWrapper(); $this->registerStreamWrapper();
}, },
10, 10,
2 2
); );
$this->registerStreamWrapper(); $this->registerStreamWrapper();
add_filter('upload_dir', [$this, 'filterUploadDir'], 20); add_filter('upload_dir', [$this, 'filterUploadDir'], 20);
add_filter('wp_get_attachment_url', [$this, 'filterAttachmentUrl'], 20, 2); add_filter('wp_get_attachment_url', [$this, 'filterAttachmentUrl'], 20, 2);
add_filter('wp_get_attachment_metadata', [$this, 'filterAttachmentMetadata'], 20); add_filter('wp_get_attachment_metadata', [$this, 'filterAttachmentMetadata'], 20);
add_filter('wp_get_original_image_path', [$this, 'filterOriginalImagePath'], 20); add_filter('wp_get_original_image_path', [$this, 'filterOriginalImagePath'], 20);
add_filter('wp_delete_file', [$this, 'handleDeleteFile'], 20); add_filter('wp_delete_file', [$this, 'handleDeleteFile'], 20);
add_action('delete_attachment', [$this, 'handleDeleteAttachment'], 20); add_action('delete_attachment', [$this, 'handleDeleteAttachment'], 20);
add_action('switch_blog', function () { add_action('switch_blog', function () {
$this->filesystem = null; $this->filesystem = null;
$this->streamRegistered = false; $this->streamRegistered = false;
$this->settings = get_option('flysystem_offload_settings', []); $this->settings = get_option('flysystem_offload_settings', []);
$this->registerStreamWrapper(); $this->registerStreamWrapper();
}); });
if (is_admin()) { if (is_admin()) {
(new SettingsPage(self::$pluginFile))->boot(); (new SettingsPage(self::$pluginFile))->boot();
} }
if (defined('WP_CLI') && WP_CLI) { if (defined('WP_CLI') && WP_CLI) {
\WP_CLI::add_command('flysystem-offload health-check', [Admin\HealthCheck::class, 'run']); \WP_CLI::add_command('flysystem-offload health-check', [Admin\HealthCheck::class, 'run']);
} }
} }
public function getFilesystem(): FilesystemOperator public function getFilesystem(): FilesystemOperator
{ {
if (!$this->filesystem) { if (!$this->filesystem) {
$factory = new FilesystemFactory($this->settings); $factory = new FilesystemFactory($this->settings);
$result = $factory->make(); $result = $factory->make();
if (is_wp_error($result)) { if (is_wp_error($result)) {
throw new \RuntimeException($result->get_error_message()); throw new \RuntimeException($result->get_error_message());
} }
$this->filesystem = $result; $this->filesystem = $result;
} }
return $this->filesystem; return $this->filesystem;
} }
private function registerStreamWrapper(): void private function registerStreamWrapper(): void
{ {
if ($this->streamRegistered) { if ($this->streamRegistered) {
return; return;
} }
try { try {
FlysystemStreamWrapper::register($this->getFilesystem(), 'fly', PathHelper::normalizePrefix($this->settings['base_prefix'] ?? '')); FlysystemStreamWrapper::register($this->getFilesystem(), 'fly', PathHelper::normalizePrefix($this->settings['base_prefix'] ?? ''));
$this->streamRegistered = true; $this->streamRegistered = true;
} catch (\Throwable $e) { } catch (\Throwable $e) {
error_log('[Flysystem Offload] No se pudo registrar el stream wrapper: ' . $e->getMessage()); error_log('[Flysystem Offload] No se pudo registrar el stream wrapper: ' . $e->getMessage());
} }
} }
public function filterUploadDir(array $dirs): array public function filterUploadDir(array $dirs): array
{ {
$remoteBase = $this->getRemoteUrlBase(); $remoteBase = $this->getRemoteUrlBase();
$prefix = PathHelper::normalizePrefix($this->settings['base_prefix'] ?? ''); $prefix = PathHelper::normalizePrefix($this->settings['base_prefix'] ?? '');
$subdir = $dirs['subdir'] ?? ''; $subdir = $dirs['subdir'] ?? '';
$dirs['path'] = "fly://{$prefix}{$subdir}"; $dirs['path'] = "fly://{$prefix}{$subdir}";
$dirs['basedir'] = "fly://{$prefix}"; $dirs['basedir'] = "fly://{$prefix}";
$dirs['url'] = trailingslashit($remoteBase) . ltrim($subdir, '/'); $dirs['url'] = trailingslashit($remoteBase) . ltrim($subdir, '/');
$dirs['baseurl'] = $remoteBase; $dirs['baseurl'] = $remoteBase;
return $dirs; return $dirs;
} }
public function filterAttachmentUrl(string $url, int $postId): string public function filterAttachmentUrl(string $url, int $postId): string
{ {
$localBase = trailingslashit(wp_get_upload_dir()['baseurl']); $localBase = trailingslashit(wp_get_upload_dir()['baseurl']);
$remoteBase = trailingslashit($this->getRemoteUrlBase()); $remoteBase = trailingslashit($this->getRemoteUrlBase());
return str_replace($localBase, $remoteBase, $url); return str_replace($localBase, $remoteBase, $url);
} }
public function filterAttachmentMetadata(array $metadata): array public function filterAttachmentMetadata(array $metadata): array
{ {
if (!empty($metadata['file'])) { if (!empty($metadata['file'])) {
$metadata['file'] = PathHelper::stripProtocol($metadata['file']); $metadata['file'] = PathHelper::stripProtocol($metadata['file']);
} }
if (!empty($metadata['sizes'])) { if (!empty($metadata['sizes'])) {
foreach ($metadata['sizes'] as &$size) { foreach ($metadata['sizes'] as &$size) {
if (!empty($size['file'])) { if (!empty($size['file'])) {
$size['file'] = ltrim($size['file'], '/'); $size['file'] = ltrim($size['file'], '/');
} }
} }
} }
return $metadata; return $metadata;
} }
public function filterOriginalImagePath(string $path): string public function filterOriginalImagePath(string $path): string
{ {
return PathHelper::ensureFlyProtocol($path); return PathHelper::ensureFlyProtocol($path);
} }
public function handleDeleteFile(string $file): string|false public function handleDeleteFile(string $file): string|false
{ {
$flyPath = PathHelper::stripProtocol($file); $flyPath = PathHelper::stripProtocol($file);
try { try {
$this->getFilesystem()->delete($flyPath); $this->getFilesystem()->delete($flyPath);
} catch (\Throwable $e) { } catch (\Throwable $e) {
error_log('[Flysystem Offload] Error al borrar archivo: ' . $flyPath . ' - ' . $e->getMessage()); error_log('[Flysystem Offload] Error al borrar archivo: ' . $flyPath . ' - ' . $e->getMessage());
} }
return false; return false;
} }
public function handleDeleteAttachment(int $postId): void public function handleDeleteAttachment(int $postId): void
{ {
$files = PathHelper::collectFilesFromAttachment($postId); $files = PathHelper::collectFilesFromAttachment($postId);
foreach ($files as $relativePath) { foreach ($files as $relativePath) {
try { try {
$this->getFilesystem()->delete($relativePath); $this->getFilesystem()->delete($relativePath);
} catch (\Throwable $e) { } catch (\Throwable $e) {
error_log('[Flysystem Offload] Error al borrar attachment: ' . $relativePath . ' - ' . $e->getMessage()); error_log('[Flysystem Offload] Error al borrar attachment: ' . $relativePath . ' - ' . $e->getMessage());
} }
} }
} }
private function getRemoteUrlBase(): string private function getRemoteUrlBase(): string
{ {
$adapterKey = $this->settings['adapter'] ?? 'local'; $adapterKey = $this->settings['adapter'] ?? 'local';
$config = $this->settings['adapters'][$adapterKey] ?? []; $config = $this->settings['adapters'][$adapterKey] ?? [];
return (new FilesystemFactory($this->settings))->resolvePublicBaseUrl($adapterKey, $config); return (new FilesystemFactory($this->settings))->resolvePublicBaseUrl($adapterKey, $config);
} }
} }