Files
crm.clientright.ru/crm_extensions/file_storage/api/onlyoffice_callback.php
Fedor 269c7ea216 feat: OnlyOffice Standalone integration with S3 direct URLs
 ЧТО СДЕЛАНО:
- Поднят новый standalone OnlyOffice Document Server (порт 8083)
- Настроен Nginx для доступа через office.clientright.ru:9443
- Создан open_file_v3_standalone.php для работы с новым OnlyOffice
- Реализована поддержка прямых S3 URL (bucket публичный)
- Добавлен s3_proxy.php с поддержкой Range requests
- Создан onlyoffice_callback.php для сохранения (базовая версия)
- Файлы успешно открываются и загружаются!

⚠️ TODO (на завтра):
- Доработать onlyoffice_callback.php для сохранения обратно в ОРИГИНАЛЬНЫЙ путь в S3
- Добавить Redis маппинг documentKey → S3 path
- Обновить CRM JS для использования open_file_v3_standalone.php
- Протестировать сохранение файлов
- Удалить тестовые файлы

📊 РЕЗУЛЬТАТ:
- OnlyOffice Standalone РАБОТАЕТ! 
- Файлы открываются напрямую из S3 
- Редактор загружается БЫСТРО 
- Автосохранение настроено  (но нужна доработка callback)
2025-11-01 01:02:03 +03:00

104 lines
4.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* OnlyOffice Callback для сохранения файлов в S3
*/
require_once '/var/www/fastuser/data/www/crm.clientright.ru/crm_extensions/shared/EnvLoader.php';
require_once '/var/www/fastuser/data/www/crm.clientright.ru/vendor/autoload.php';
EnvLoader::load('/var/www/fastuser/data/www/crm.clientright.ru/crm_extensions/.env');
error_reporting(E_ALL);
ini_set('display_errors', 0);
// Логируем все запросы
$input = file_get_contents('php://input');
$data = json_decode($input, true);
error_log("=== ONLYOFFICE CALLBACK ===");
error_log("Method: " . $_SERVER['REQUEST_METHOD']);
error_log("Body: " . $input);
// OnlyOffice отправляет POST с JSON данными
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($data)) {
$status = $data['status'] ?? 0;
$key = $data['key'] ?? 'unknown';
error_log("Callback Status: $status, Key: $key");
// Status 2 = файл сохранён, нужно скачать и загрузить в S3
if ($status == 2 && isset($data['url'])) {
$downloadUrl = $data['url'];
error_log("File saved! Download URL: " . $downloadUrl);
try {
// Скачиваем изменённый файл от OnlyOffice
$fileContent = file_get_contents($downloadUrl);
if ($fileContent === false) {
error_log("Failed to download file from OnlyOffice");
http_response_code(500);
echo json_encode(['error' => 1]);
exit;
}
error_log("Downloaded file: " . strlen($fileContent) . " bytes");
// Извлекаем путь к файлу из documentKey
// В $key хранится md5($s3Path . '_' . $version)
// Нам нужен оригинальный путь, который мы должны хранить отдельно
// ВРЕМЕННО: Сохраняем в отдельную папку в S3 для отладки
// TODO: Нужно связать documentKey с оригинальным путём файла
// Инициализируем S3 клиент
$s3Client = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'ru-1',
'endpoint' => 'https://s3.twcstorage.ru',
'use_path_style_endpoint' => true,
'credentials' => [
'key' => EnvLoader::getRequired('S3_ACCESS_KEY'),
'secret' => EnvLoader::getRequired('S3_SECRET_KEY')
],
'suppress_php_deprecation_warning' => true
]);
$bucket = 'f9825c87-4e3558f6-f9b6-405c-ad3d-d1535c49b61c';
// ВРЕМЕННОЕ РЕШЕНИЕ: Сохраняем в папку /onlyoffice_saved/
$savedPath = 'onlyoffice_saved/' . $key . '_' . date('Y-m-d_H-i-s') . '.docx';
$result = $s3Client->putObject([
'Bucket' => $bucket,
'Key' => $savedPath,
'Body' => $fileContent,
'ContentType' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
]);
error_log("File saved to S3: " . $savedPath);
error_log("S3 Response: " . json_encode($result->toArray()));
http_response_code(200);
echo json_encode(['error' => 0]);
exit;
} catch (Exception $e) {
error_log("Error saving file to S3: " . $e->getMessage());
http_response_code(500);
echo json_encode(['error' => 1, 'message' => $e->getMessage()]);
exit;
}
}
// Другие статусы (1 = открыт, 4 = закрыт и т.д.)
http_response_code(200);
echo json_encode(['error' => 0]);
exit;
}
// Для всех остальных запросов - 200 OK
http_response_code(200);
echo json_encode(['error' => 0]);
?>