Initial commit - Last War messaging system

This commit is contained in:
2026-02-19 01:33:28 -06:00
commit 38a8447a64
2162 changed files with 216183 additions and 0 deletions

134
src/Translate.php Executable file
View File

@@ -0,0 +1,134 @@
<?php
namespace src;
class Translate
{
private string $url;
private array $supportedLanguages = [];
public function __construct()
{
$this->url = $_ENV['LIBRETRANSLATE_URL'] ?? getenv('LIBRETRANSLATE_URL') ?? 'http://localhost:5000';
}
public function detectLanguage(string $text): ?string
{
try {
$response = $this->request('/detect', ['q' => $text]);
if (!empty($response)) {
return $response[0]['language'] ?? null;
}
} catch (\Exception $e) {
error_log("Language detection error: " . $e->getMessage());
}
return null;
}
public function translate(string $text, string $sourceLang, string $targetLang): ?string
{
if ($sourceLang === $targetLang) {
return $text;
}
try {
$lines = explode("\n", $text);
$translatedLines = [];
foreach ($lines as $line) {
if (trim($line) === '') {
$translatedLines[] = '';
continue;
}
$response = $this->request('/translate', [
'q' => trim($line),
'source' => $sourceLang,
'target' => $targetLang,
'format' => 'text'
]);
$translatedLines[] = $response['translatedText'] ?? trim($line);
}
return implode("\n", $translatedLines);
} catch (\Exception $e) {
error_log("Translation error: " . $e->getMessage());
return null;
}
}
public function translateToMultiple(string $text, string $sourceLang, array $targetLangs): array
{
$results = [];
foreach ($targetLangs as $lang) {
$results[$lang] = $this->translate($text, $sourceLang, $lang);
}
return $results;
}
public function getSupportedLanguages(): array
{
if (!empty($this->supportedLanguages)) {
return $this->supportedLanguages;
}
try {
$response = $this->request('/languages');
$this->supportedLanguages = $response;
return $response;
} catch (\Exception $e) {
error_log("Get languages error: " . $e->getMessage());
return [];
}
}
public function isLanguageSupported(string $langCode): bool
{
$languages = $this->getSupportedLanguages();
foreach ($languages as $lang) {
if ($lang['code'] === $langCode) {
return true;
}
}
return false;
}
private function request(string $endpoint, array $data = []): array
{
$url = $this->url . $endpoint;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded'
]);
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
throw new \Exception("LibreTranslate API Error: HTTP $httpCode");
}
$result = json_decode($response, true);
if ($result === null) {
throw new \Exception("Invalid JSON response from LibreTranslate");
}
return $result;
}
}