<?php
/*
 * net2ftp launch page — consumes one-time SSO token (from _puq_sso.php
 * handshake) and renders a self-submitting POST form to net2ftp's
 * index.php with all the credentials. Browser auto-submits → net2ftp
 * sees a normal "user logs in" POST and goes straight to browse state.
 *
 * Two extras beyond stock net2ftp:
 *   1. Server-side path probe — figures out the right docroot path
 *      (vsftpd chroot behaviour varies), so the browser lands directly
 *      in /home/<u>/web/<d>/public_html instead of FTP root.
 *   2. Session-stored ROOT — wrapper (index.php) rejects any later
 *      `directory=` parameter that resolves above this root, providing
 *      application-level chroot since net2ftp doesn't enforce one.
 */

$sso = isset($_GET['_sso']) ? (string) $_GET['_sso'] : '';
if (!preg_match('/^[a-f0-9]{64}$/', $sso)) {
    http_response_code(400);
    echo 'Bad SSO token';
    exit;
}
$cfgFile = __DIR__ . '/_puq_config.php';
if (!is_file($cfgFile)) {
    http_response_code(500);
    echo 'Config missing';
    exit;
}
$cfg = require $cfgFile;
$tokenDir = (string) ($cfg['token_dir'] ?? (__DIR__ . '/private/sso_sessions'));
$tokFile  = $tokenDir . '/' . $sso . '.json';
if (!is_file($tokFile)) {
    http_response_code(400);
    echo 'Token not found or already used';
    exit;
}
$raw = @file_get_contents($tokFile);
@unlink($tokFile); // single-use — delete BEFORE validating
$data = is_string($raw) ? json_decode($raw, true) : null;
if (!is_array($data) || ($data['expires'] ?? 0) < time()) {
    http_response_code(400);
    echo 'Token expired';
    exit;
}

$ftpserver     = '{{FTP_HOST}}';
$ftpserverport = '21';
$username      = (string) $data['login'];
$password      = (string) $data['pass'];
$domain        = (string) $data['domain'];

// --- Server-side path probe -------------------------------------------------
// Try login + chdir locally to discover which path form vsftpd accepts.
// Result populates BOTH the form's `directory` and the session root.
$directory = '/';
$probeConn = @ftp_connect('{{FTP_HOST}}', 21, 5);
if ($probeConn) {
    if (@ftp_login($probeConn, $username, $password)) {
        @ftp_pasv($probeConn, false);
        $candidates = [
            '/web/'  . $domain . '/public_html',
            '/home/' . $username . '/web/' . $domain . '/public_html',
        ];
        $found = '';
        foreach ($candidates as $c) {
            if (@ftp_chdir($probeConn, $c)) { $found = $c; break; }
        }
        if ($found !== '') {
            $directory = $found;
        } else {
            $pwd = @ftp_pwd($probeConn);
            if (is_string($pwd) && $pwd !== '') $directory = $pwd;
        }
    }
    @ftp_close($probeConn);
}

// --- Cookies + session setup ------------------------------------------------
if (!empty($data['back_url'])) {
    setcookie('puq_back_url', (string) $data['back_url'], [
        'path' => '/', 'secure' => !empty($_SERVER['HTTPS']),
        'httponly' => false, 'samesite' => 'Lax',
    ]);
}

// SSO marker + session root for wrapper. Both must be set BEFORE the
// session is closed so the about-to-fire POST request can read them.
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
$_SESSION['puq_n2f_sso']  = true;
$_SESSION['puq_n2f_root'] = $directory;   // wrapper's enforced ceiling
session_write_close();

// --- Auto-submit form -------------------------------------------------------
$esc = function ($v) {
    return htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');
};
?><!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title>Opening File Manager…</title>
<style>
body{font-family:-apple-system,Segoe UI,Roboto,sans-serif;background:#f5f7fa;
     display:flex;align-items:center;justify-content:center;height:100vh;margin:0;color:#333;}
.box{text-align:center;padding:30px 40px;background:#fff;border-radius:8px;
     box-shadow:0 2px 16px rgba(0,0,0,0.08);}
.spin{width:32px;height:32px;border:3px solid #e0e0e0;border-top-color:#3273dc;
      border-radius:50%;animation:s 0.8s linear infinite;margin:0 auto 14px;}
@keyframes s{to{transform:rotate(360deg);}}
</style>
</head><body>
<div class="box">
    <div class="spin"></div>
    Opening File Manager…
</div>
<!-- Matches net2ftp's stock loginform.template.php (state=browse +
     state2=main + protocol=FTP) plus a server-probed `directory` field
     so we land directly in the customer's docroot instead of FTP root. -->
<form id="f" method="post" action="index.php" style="display:none;">
    <input name="protocol"      value="FTP">
    <input name="state"         value="browse">
    <input name="state2"        value="main">
    <input name="ftpserver"     value="<?= $esc($ftpserver) ?>">
    <input name="ftpserverport" value="<?= $esc($ftpserverport) ?>">
    <input name="username"      value="<?= $esc($username) ?>">
    <input name="password"      value="<?= $esc($password) ?>">
    <input name="directory"     value="<?= $esc($directory) ?>">
    <input name="language"      value="en">
</form>
<script>document.getElementById('f').submit();</script>
</body></html>
