168 lines
6.3 KiB
PHP
168 lines
6.3 KiB
PHP
<?php
|
||
/**
|
||
* Simple File Upload to Nextcloud API
|
||
* Простой API для загрузки файла из CRM в Nextcloud и создания ссылки редактирования
|
||
*/
|
||
|
||
header('Content-Type: application/json; charset=utf-8');
|
||
error_reporting(E_ALL);
|
||
ini_set('display_errors', 1);
|
||
|
||
try {
|
||
// Получаем параметры из GET или из командной строки
|
||
$recordId = $_GET['record'] ?? ($_SERVER['argv'][1] ?? '');
|
||
$fileName = $_GET['filename'] ?? ($_SERVER['argv'][2] ?? '');
|
||
|
||
if (empty($recordId)) {
|
||
throw new Exception('Record ID required. Usage: ?record=ID&filename=NAME or php script.php RECORD_ID FILENAME');
|
||
}
|
||
|
||
error_log("Simple Upload: Processing record $recordId, file: $fileName");
|
||
|
||
// Подключаем конфигурацию и клиент
|
||
require_once __DIR__ . '/../config.php';
|
||
require_once __DIR__ . '/../NextcloudClient.php';
|
||
|
||
$config = require __DIR__ . '/../config.php';
|
||
$nextcloudClient = new NextcloudClient($config['nextcloud']);
|
||
|
||
// Получаем информацию о файле из vTiger
|
||
$fileInfo = getVTigerFileInfo($recordId);
|
||
if (!$fileInfo) {
|
||
throw new Exception('File not found in vTiger CRM for record: ' . $recordId);
|
||
}
|
||
|
||
error_log("Simple Upload: File info - " . json_encode($fileInfo));
|
||
|
||
$actualFileName = $fileInfo['file_name'];
|
||
$localPath = $fileInfo['local_path'];
|
||
|
||
if (!file_exists($localPath)) {
|
||
throw new Exception('Local file not found: ' . $localPath);
|
||
}
|
||
|
||
// Генерируем путь в Nextcloud
|
||
$nextcloudPath = "Documents/{$recordId}/{$actualFileName}";
|
||
|
||
// Проверяем, есть ли файл уже в Nextcloud
|
||
if (!$nextcloudClient->fileExists($nextcloudPath)) {
|
||
error_log("Simple Upload: Uploading file to Nextcloud - $localPath -> $nextcloudPath");
|
||
|
||
$uploadResult = $nextcloudClient->uploadFile($localPath, $nextcloudPath);
|
||
if (!$uploadResult['success']) {
|
||
throw new Exception('Failed to upload to Nextcloud: ' . $uploadResult['error']);
|
||
}
|
||
|
||
error_log("Simple Upload: File uploaded successfully");
|
||
} else {
|
||
error_log("Simple Upload: File already exists in Nextcloud");
|
||
}
|
||
|
||
// Создаём ссылку для редактирования
|
||
$editLinkResult = $nextcloudClient->createEditLink($nextcloudPath);
|
||
|
||
if ($editLinkResult['success']) {
|
||
// Успех - возвращаем ссылку для редактирования
|
||
echo json_encode([
|
||
'success' => true,
|
||
'edit_url' => $editLinkResult['edit_url'],
|
||
'share_url' => $editLinkResult['share_url'],
|
||
'nextcloud_path' => $nextcloudPath,
|
||
'file_name' => $actualFileName,
|
||
'message' => 'Файл загружен и готов к редактированию'
|
||
], JSON_UNESCAPED_UNICODE);
|
||
|
||
} else {
|
||
// Если не удалось создать ссылку, возвращаем прямую ссылку на папку
|
||
$directUrl = $config['nextcloud']['base_url'] . '/apps/files/?dir=' . urlencode('/CRM_Active_Files/Documents/' . $recordId);
|
||
|
||
echo json_encode([
|
||
'success' => true,
|
||
'edit_url' => $directUrl,
|
||
'nextcloud_path' => $nextcloudPath,
|
||
'file_name' => $actualFileName,
|
||
'message' => 'Файл загружен в Nextcloud. Найдите его в папке и откройте для редактирования.',
|
||
'fallback' => true
|
||
], JSON_UNESCAPED_UNICODE);
|
||
}
|
||
|
||
} catch (Exception $e) {
|
||
error_log("Simple Upload Error: " . $e->getMessage());
|
||
|
||
http_response_code(400);
|
||
echo json_encode([
|
||
'success' => false,
|
||
'error' => $e->getMessage()
|
||
], JSON_UNESCAPED_UNICODE);
|
||
}
|
||
|
||
/**
|
||
* Получение информации о файле из vTiger
|
||
*/
|
||
function getVTigerFileInfo($recordId) {
|
||
try {
|
||
// Подключаемся к базе данных vTiger
|
||
$configPath = dirname(dirname(dirname(__DIR__))) . '/config.inc.php';
|
||
if (file_exists($configPath)) {
|
||
require_once $configPath;
|
||
} else {
|
||
throw new Exception('vTiger config not found');
|
||
}
|
||
|
||
global $dbconfig;
|
||
|
||
// Создаём подключение к БД
|
||
$pdo = new PDO(
|
||
"mysql:host={$dbconfig['db_server']};dbname={$dbconfig['db_name']};charset=utf8",
|
||
$dbconfig['db_username'],
|
||
$dbconfig['db_password'],
|
||
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
|
||
);
|
||
|
||
// Запрос информации о файле
|
||
$query = "
|
||
SELECT
|
||
n.notesid,
|
||
n.title,
|
||
n.filename,
|
||
n.filelocationtype,
|
||
a.attachmentsid,
|
||
a.name as stored_name,
|
||
a.type as mime_type,
|
||
a.path
|
||
FROM vtiger_notes n
|
||
LEFT JOIN vtiger_seattachmentsrel sar ON n.notesid = sar.crmid
|
||
LEFT JOIN vtiger_attachments a ON sar.attachmentsid = a.attachmentsid
|
||
WHERE n.notesid = ? AND n.filename IS NOT NULL
|
||
";
|
||
|
||
$stmt = $pdo->prepare($query);
|
||
$stmt->execute([$recordId]);
|
||
$result = $stmt->fetch(PDO::FETCH_ASSOC);
|
||
|
||
if (!$result) {
|
||
return null;
|
||
}
|
||
|
||
// Формируем полный путь к файлу
|
||
$storagePath = dirname(dirname(dirname(__DIR__))) . '/storage/';
|
||
$localPath = $storagePath . $result['attachmentsid'] . '_' . $result['stored_name'];
|
||
|
||
return [
|
||
'record_id' => $recordId,
|
||
'title' => $result['title'],
|
||
'file_name' => $result['filename'],
|
||
'stored_name' => $result['stored_name'],
|
||
'mime_type' => $result['mime_type'],
|
||
'local_path' => $localPath,
|
||
'attachments_id' => $result['attachmentsid'],
|
||
'file_location_type' => $result['filelocationtype']
|
||
];
|
||
|
||
} catch (Exception $e) {
|
||
error_log("vTiger file info error: " . $e->getMessage());
|
||
return null;
|
||
}
|
||
}
|
||
?>
|