Files
crm.clientright.ru/modules/OnlyOfficeTemplates/resources/S3Helper.php
2026-02-16 09:27:19 +03:00

121 lines
3.4 KiB
PHP

<?php
/**
* Portable S3 helper for OnlyOfficeTemplates (get/put using module config).
*/
class OnlyOfficeTemplates_S3Helper
{
protected $client;
protected $bucket;
protected $prefix;
public function __construct(array $config)
{
$this->bucket = $config['s3_bucket'] ?? ($config['s3']['bucket'] ?? '');
$this->prefix = rtrim($config['s3_prefix'] ?? 'crm2/OnlyOfficeTemplates', '/');
if ($this->bucket === null || $this->bucket === '') {
throw new Exception('OnlyOfficeTemplates: S3 bucket not configured. Set S3_BUCKET in .env or add bucket to crm_extensions/file_storage/config.php (s3.bucket or root bucket).');
}
$s3 = $config['s3'] ?? [];
$path = dirname(dirname(dirname(__DIR__)));
if (!class_exists('Aws\S3\S3Client')) {
if (is_file($path . '/vendor/autoload.php')) {
require_once $path . '/vendor/autoload.php';
}
}
$this->client = new Aws\S3\S3Client([
'version' => $s3['version'] ?? 'latest',
'region' => $s3['region'] ?? 'ru-1',
'endpoint' => $s3['endpoint'],
'use_path_style_endpoint' => !empty($s3['use_path_style_endpoint']),
'credentials' => [
'key' => $s3['key'],
'secret' => $s3['secret'],
],
]);
}
/**
* Template S3 key: {prefix}/templates/{templateId}/{fileName}
*/
public function getTemplateKey($templateId, $fileName)
{
return $this->prefix . '/templates/' . (int)$templateId . '/' . $fileName;
}
/**
* Temp generated file key: {prefix}/temp/{recordId}_{templateId}_{timestamp}.ext
*/
public function getTempKey($recordId, $templateId, $extension)
{
return $this->prefix . '/temp/' . (int)$recordId . '_' . (int)$templateId . '_' . time() . '.' . $extension;
}
public function getBucket()
{
return $this->bucket;
}
public function getPrefix()
{
return $this->prefix;
}
/**
* Download object to a local file; returns path.
*/
public function downloadToFile($s3Key, $localPath)
{
$this->client->getObject([
'Bucket' => $this->bucket,
'Key' => $s3Key,
'SaveAs' => $localPath,
]);
return $localPath;
}
/**
* Get object body as string.
*/
public function getObjectBody($s3Key)
{
$result = $this->client->getObject([
'Bucket' => $this->bucket,
'Key' => $s3Key,
]);
return (string)$result['Body'];
}
/**
* Put string or file into S3.
*/
public function putObject($s3Key, $body, $contentType = null)
{
$params = [
'Bucket' => $this->bucket,
'Key' => $s3Key,
'Body' => $body,
];
if ($contentType) {
$params['ContentType'] = $contentType;
}
$this->client->putObject($params);
}
/**
* Upload local file to S3.
*/
public function uploadFile($localPath, $s3Key, $contentType = null)
{
$params = [
'Bucket' => $this->bucket,
'Key' => $s3Key,
'SourceFile' => $localPath,
];
if ($contentType) {
$params['ContentType'] = $contentType;
}
$this->client->putObject($params);
}
}