<?php
/**
 * Autodiscover для ящиков gorshenin.info (ISPmail).
 *
 * Поддерживает:
 * - Microsoft Outlook: POST /autodiscover/autodiscover.xml
 * - Mozilla (Thunderbird, K-9): GET /mail/config-v1.1.xml
 */

define('MAIL_HOST', 'mail.gorshenin.info');
define('MAIL_DOMAIN', 'gorshenin.info');
define('IMAP_PORT', 993);
define('SMTP_PORT', 587);

function get_requested_email(): ?string
{
    $email = $_GET['emailaddress'] ?? $_GET['Email'] ?? null;

    if (empty($email)) {
        $data = file_get_contents('php://input');
        if (!empty($data)) {
            libxml_use_internal_errors(true);
            $xml = simplexml_load_string($data);
            if ($xml !== false && isset($xml->Request->EMailAddress)) {
                $email = (string) $xml->Request->EMailAddress;
            }
        }
    }

    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return null;
    }

    $domain = strtolower(substr($email, strrpos($email, '@') + 1));
    if ($domain !== MAIL_DOMAIN) {
        return null;
    }

    return $email;
}

function send_xml_error(int $code, string $message): void
{
    http_response_code($code);
    header('Content-Type: application/xml; charset=utf-8');
    echo '<?xml version="1.0" encoding="utf-8"?>';
    echo '<Error>' . htmlspecialchars($message, ENT_XML1, 'UTF-8') . '</Error>';
    exit;
}

function output_mozilla_config(string $email): void
{
    $email_escaped = htmlspecialchars($email, ENT_XML1, 'UTF-8');

    header('Content-Type: application/xml; charset=utf-8');
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    ?>
<clientConfig version="1.1">
    <emailProvider id="<?= htmlspecialchars(MAIL_DOMAIN, ENT_XML1, 'UTF-8') ?>">
        <domain><?= htmlspecialchars(MAIL_DOMAIN, ENT_XML1, 'UTF-8') ?></domain>
        <displayName><?= htmlspecialchars(MAIL_DOMAIN, ENT_XML1, 'UTF-8') ?> Mail</displayName>
        <displayShortName>Mail</displayShortName>
        <incomingServer type="imap">
            <hostname><?= htmlspecialchars(MAIL_HOST, ENT_XML1, 'UTF-8') ?></hostname>
            <port><?= IMAP_PORT ?></port>
            <socketType>SSL</socketType>
            <authentication>password-cleartext</authentication>
            <username><?= $email_escaped ?></username>
        </incomingServer>
        <outgoingServer type="smtp">
            <hostname><?= htmlspecialchars(MAIL_HOST, ENT_XML1, 'UTF-8') ?></hostname>
            <port><?= SMTP_PORT ?></port>
            <socketType>STARTTLS</socketType>
            <authentication>password-cleartext</authentication>
            <username><?= $email_escaped ?></username>
        </outgoingServer>
    </emailProvider>
</clientConfig>
<?php
}

function output_outlook_config(string $email): void
{
    $email_escaped = htmlspecialchars($email, ENT_XML1, 'UTF-8');

    header('Content-Type: application/xml; charset=utf-8');
    echo '<?xml version="1.0" encoding="utf-8"?>' . "\n";
    ?>
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006">
    <Response xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a">
        <Account>
            <AccountType>email</AccountType>
            <Action>settings</Action>
            <Protocol>
                <Type>IMAP</Type>
                <Server><?= htmlspecialchars(MAIL_HOST, ENT_XML1, 'UTF-8') ?></Server>
                <Port><?= IMAP_PORT ?></Port>
                <DomainRequired>on</DomainRequired>
                <LoginName><?= $email_escaped ?></LoginName>
                <SPA>off</SPA>
                <SSL>on</SSL>
                <AuthRequired>on</AuthRequired>
            </Protocol>
            <Protocol>
                <Type>SMTP</Type>
                <Server><?= htmlspecialchars(MAIL_HOST, ENT_XML1, 'UTF-8') ?></Server>
                <Port><?= SMTP_PORT ?></Port>
                <DomainRequired>on</DomainRequired>
                <LoginName><?= $email_escaped ?></LoginName>
                <SPA>off</SPA>
                <SSL>off</SSL>
                <AuthRequired>on</AuthRequired>
                <UsePOPAuth>on</UsePOPAuth>
                <SMTPLast>off</SMTPLast>
            </Protocol>
        </Account>
    </Response>
</Autodiscover>
<?php
}

$request_uri = $_SERVER['REQUEST_URI'] ?? '';
$email = get_requested_email();

if ($email === null) {
    send_xml_error(400, 'Invalid or unsupported email address');
}

if (strpos($request_uri, 'config-v1.1.xml') !== false) {
    output_mozilla_config($email);
} else {
    output_outlook_config($email);
}

