Files
crm.clientright.ru/crm_extensions/file_storage/switch_to_external.php
Fedor ac7467f0b4 Major CRM updates: AI Assistant, Court Status API, S3 integration improvements, and extensive file storage system
- Added comprehensive AI Assistant system (aiassist/ directory):
  * Vector search and embedding capabilities
  * Typebot proxy integration
  * Elastic search functionality
  * Message classification and chat history
  * MCP proxy for external integrations

- Implemented Court Status API (GetCourtStatus.php):
  * Real-time court document status checking
  * Integration with external court systems
  * Comprehensive error handling and logging

- Enhanced S3 integration:
  * Improved file backup system with metadata
  * Batch processing capabilities
  * Enhanced error logging and recovery
  * Copy operations with URL fixing

- Added Telegram contact creation API
- Improved error logging across all modules
- Enhanced callback system for AI responses
- Extensive backup file storage with timestamps
- Updated documentation and README files

- File storage improvements:
  * Thousands of backup files with proper metadata
  * Fix operations for broken file references
  * Project-specific backup and recovery systems
  * Comprehensive file integrity checking

Total: 26,461+ files added/modified including AWS SDK, vendor dependencies, and extensive backup system.
2025-10-16 11:17:21 +03:00

136 lines
4.2 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
/**
* Switch to External - переключает файлы с S3 метаданными на External режим
*
* Этот скрипт:
* 1. Находит записи с заполненными s3_key, но еще Internal типом
* 2. Переключает их на External тип и обновляет filename на S3 URL
* 3. Создает резервные копии перед изменениями
*/
ini_set('memory_limit', '512M');
set_time_limit(0);
date_default_timezone_set('Europe/Moscow');
$ROOT = '/var/www/fastuser/data/www/crm.clientright.ru/';
// Dependencies
require_once $ROOT . 'config.inc.php';
// CLI options
$opts = getopt('', [
'limit::',
'offset::',
'dry-run::'
]);
$limit = isset($opts['limit']) ? (int)$opts['limit'] : 500;
$offset = isset($opts['offset']) ? (int)$opts['offset'] : 0;
$dryRun = isset($opts['dry-run']) ? (int)$opts['dry-run'] !== 0 : true;
// Database connection
$mysqli = new mysqli($dbconfig['db_server'], $dbconfig['db_username'], $dbconfig['db_password'], $dbconfig['db_name']);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysqli->set_charset("utf8");
// Logging
$logDir = $ROOT . 'logs';
if (!is_dir($logDir)) mkdir($logDir, 0755, true);
$logFile = $logDir . '/switch_to_external.log';
function logln($msg) {
global $logFile;
$line = '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL;
file_put_contents($logFile, $line, FILE_APPEND | LOCK_EX);
echo $line;
}
logln("Starting switch to External mode");
logln("Parameters: limit=$limit, offset=$offset, dry-run=" . ($dryRun ? 'true' : 'false'));
// Find records with S3 metadata but still Internal
$query = "SELECT notesid, filename, s3_key, s3_bucket, filelocationtype
FROM vtiger_notes
WHERE s3_key IS NOT NULL
AND s3_key != ''
AND filelocationtype = 'I'
LIMIT $limit OFFSET $offset";
$result = $mysqli->query($query);
if (!$result) {
die("Query failed: " . $mysqli->error);
}
$records = [];
while ($row = $result->fetch_assoc()) {
$records[] = $row;
}
logln("Found " . count($records) . " records to switch to External (offset=$offset, limit=$limit)");
if (empty($records)) {
logln("No records to update.");
exit(0);
}
$updated = 0;
$errors = 0;
foreach ($records as $record) {
$notesid = $record['notesid'];
$currentFilename = $record['filename'];
$s3Key = $record['s3_key'];
$s3Bucket = $record['s3_bucket'];
$currentType = $record['filelocationtype'];
// Construct S3 URL
$s3Url = "https://s3.twcstorage.ru/$s3Bucket/" . urlencode($s3Key);
logln("Processing notesid=$notesid");
if (!$dryRun) {
// Create backup
$backupDir = $ROOT . 'crm_extensions/file_storage/backups/';
if (!is_dir($backupDir)) mkdir($backupDir, 0755, true);
$backupFile = $backupDir . 'switch_external_backup_' . $notesid . '_' . date('Ymd_His') . '.json';
$backup = [
'notesid' => $notesid,
'original_filename' => $currentFilename,
'original_filelocationtype' => $currentType,
'new_filename' => $s3Url,
'timestamp' => date('c')
];
file_put_contents($backupFile, json_encode($backup, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
// Update database - switch to External and set S3 URL as filename
$updateQuery = "UPDATE vtiger_notes
SET filename = ?, filelocationtype = 'E'
WHERE notesid = ?";
$stmt = $mysqli->prepare($updateQuery);
$stmt->bind_param('si', strip_tags(trim($s3Url)), $notesid);
if ($stmt->execute()) {
logln("SWITCHED notesid=$notesid -> External: $s3Url");
$updated++;
} else {
logln("ERROR switching notesid=$notesid: " . $stmt->error);
$errors++;
}
$stmt->close();
} else {
logln("DRY-RUN: Would switch notesid=$notesid -> External: $s3Url");
$updated++;
}
}
logln("Switch to External completed:");
logln("- Updated: $updated");
logln("- Errors: $errors");
logln("- Mode: " . ($dryRun ? "DRY-RUN" : "LIVE"));
$mysqli->close();
?>