#!@PHP_CLI@
<?php
/**
 * Exim pipe transport: delivers one message through the Maileroo Email API v2.
 *
 * Exim (maileroo_api transport) writes the message to STDIN with
 * Return-path: and Envelope-to: headers added. This script parses the MIME
 * message, maps it onto POST https://smtp.maileroo.com/api/v2/emails and exits:
 *    0  accepted by Maileroo
 *   75  temporary failure  -> Exim keeps the message queued and retries
 *   65  permanent failure  -> Exim bounces with the output below
 */

require getenv('MAILEROO_LIB') ?: '/usr/local/maileroo/lib/Maileroo.php';

use Maileroo\{Config, Util, Api, Resolver, Paths};

const EX_OK = 0;
const EX_DATAERR = 65;
const EX_TEMPFAIL = 75;

final class Mime
{
    /** @return array{0: array<int, array{0:string,1:string}>, 1: string} */
    public static function split(string $raw): array
    {
        $raw = str_replace("\r\n", "\n", $raw);
        $pos = strpos($raw, "\n\n");
        $head = $pos === false ? $raw : substr($raw, 0, $pos);
        $body = $pos === false ? '' : substr($raw, $pos + 2);
        $head = preg_replace("/\n[ \t]+/", ' ', $head); // unfold
        $headers = [];
        foreach (explode("\n", $head) as $line) {
            if (strpos($line, ':') === false) {
                continue;
            }
            [$n, $v] = explode(':', $line, 2);
            $headers[] = [trim($n), trim($v)];
        }
        return [$headers, $body];
    }

    public static function get(array $headers, string $name): ?string
    {
        foreach ($headers as [$n, $v]) {
            if (strcasecmp($n, $name) === 0) {
                return $v;
            }
        }
        return null;
    }

    /** "type/sub; a=b; c="d"" -> ['value' => 'type/sub', 'a' => 'b', 'c' => 'd'] (RFC 2231 aware) */
    public static function params(?string $v): array
    {
        $out = ['value' => ''];
        if ($v === null) {
            return $out;
        }
        $parts = preg_split('/;(?=(?:[^"]*"[^"]*")*[^"]*$)/', $v);
        $out['value'] = strtolower(trim(array_shift($parts)));
        $cont = [];
        foreach ($parts as $p) {
            if (strpos($p, '=') === false) {
                continue;
            }
            [$k, $val] = explode('=', $p, 2);
            $k = strtolower(trim($k));
            $val = trim($val);
            if (strlen($val) > 1 && $val[0] === '"' && substr($val, -1) === '"') {
                $val = stripcslashes(substr($val, 1, -1));
            }
            if (preg_match('/^([a-z0-9_-]+)\*(\d+)?(\*)?$/', $k, $m)) { // RFC 2231
                $enc = isset($m[3]) || (!isset($m[2]) && substr($k, -1) === '*');
                $cont[$m[1]][(int) ($m[2] ?? 0)] = [$val, $enc];
                continue;
            }
            $out[$k] = $val;
        }
        foreach ($cont as $k => $pieces) {
            ksort($pieces);
            $s = '';
            $charset = 'UTF-8';
            foreach ($pieces as $i => [$val, $enc]) {
                if ($enc) {
                    if ($i === 0 && preg_match("/^([^']*)'[^']*'(.*)$/", $val, $m)) {
                        $charset = $m[1] ?: 'UTF-8';
                        $val = $m[2];
                    }
                    $val = rawurldecode($val);
                }
                $s .= $val;
            }
            $out[$k] = self::toUtf8($s, $charset);
        }
        return $out;
    }

    public static function toUtf8(string $s, ?string $charset): string
    {
        $charset = strtoupper(trim((string) $charset));
        if ($charset === '' || $charset === 'UTF-8' || $charset === 'US-ASCII' || $charset === 'UTF8') {
            return mb_check_encoding($s, 'UTF-8') ? $s : mb_convert_encoding($s, 'UTF-8', 'ISO-8859-1');
        }
        if (function_exists('mb_convert_encoding') && in_array($charset, array_map('strtoupper', mb_list_encodings()), true)) {
            return mb_convert_encoding($s, 'UTF-8', $charset);
        }
        if (function_exists('iconv')) {
            $r = @iconv($charset, 'UTF-8//TRANSLIT', $s);
            if ($r !== false) {
                return $r;
            }
        }
        return mb_convert_encoding($s, 'UTF-8', 'ISO-8859-1');
    }

    public static function decodeHeader(string $v): string
    {
        if (strpos($v, '=?') === false) {
            return self::toUtf8($v, 'UTF-8');
        }
        if (function_exists('iconv_mime_decode')) {
            $r = @iconv_mime_decode($v, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
            if ($r !== false) {
                return $r;
            }
        }
        return mb_decode_mimeheader($v);
    }

    public static function decodeBody(string $body, ?string $cte): string
    {
        switch (strtolower(trim((string) $cte))) {
            case 'base64':
                return (string) base64_decode(preg_replace('/[^A-Za-z0-9+\/=]/', '', $body));
            case 'quoted-printable':
                return quoted_printable_decode($body);
            default:
                return $body;
        }
    }

    /** Parses an address list header into [['address'=>..., 'display_name'=>...], ...] */
    public static function addresses(?string $v): array
    {
        if ($v === null || trim($v) === '') {
            return [];
        }
        $v = preg_replace('/\([^()]*\)/', '', $v); // drop comments
        $items = [];
        $buf = '';
        $q = false;
        $a = 0;
        $len = strlen($v);
        for ($i = 0; $i < $len; $i++) {
            $c = $v[$i];
            if ($c === '\\' && $q) {
                $buf .= $c . ($v[++$i] ?? '');
                continue;
            }
            if ($c === '"') {
                $q = !$q;
            } elseif (!$q && $c === '<') {
                $a++;
            } elseif (!$q && $c === '>') {
                $a = max(0, $a - 1);
            } elseif (!$q && !$a && ($c === ',' || $c === ';')) {
                $items[] = $buf;
                $buf = '';
                continue;
            } elseif (!$q && !$a && $c === ':') { // group syntax "Undisclosed: ;"
                $buf = '';
                continue;
            }
            $buf .= $c;
        }
        $items[] = $buf;
        $out = [];
        foreach ($items as $it) {
            $it = trim($it);
            if ($it === '') {
                continue;
            }
            if (preg_match('/^(.*)<([^>]+)>\s*$/s', $it, $m)) {
                $name = trim($m[1]);
                if (strlen($name) > 1 && $name[0] === '"' && substr($name, -1) === '"') {
                    $name = stripcslashes(substr($name, 1, -1));
                }
                $addr = trim($m[2]);
            } else {
                $name = '';
                $addr = $it;
            }
            if (strpos($addr, '@') === false) {
                continue;
            }
            $o = ['address' => $addr];
            $name = self::decodeHeader($name);
            if ($name !== '') {
                $o['display_name'] = mb_substr($name, 0, 200);
            }
            $out[] = $o;
        }
        return $out;
    }

    /**
     * Walks the MIME tree.
     * @param array $acc ['plain'=>?string,'html'=>?string,'attachments'=>[], 'related'=>bool]
     */
    public static function walk(array $headers, string $body, array &$acc, bool $inRelated = false, int $depth = 0): void
    {
        if ($depth > 20) {
            return;
        }
        $ct = self::params(self::get($headers, 'Content-Type') ?? 'text/plain; charset=us-ascii');
        $type = $ct['value'] ?: 'text/plain';
        $cd = self::params(self::get($headers, 'Content-Disposition'));
        $cte = self::get($headers, 'Content-Transfer-Encoding');
        $cid = trim((string) self::get($headers, 'Content-ID'), " <>");

        if (strpos($type, 'multipart/') === 0 && !empty($ct['boundary'])) {
            $b = preg_quote($ct['boundary'], '/');
            $chunks = preg_split('/^--' . $b . '(?:--)?[ \t]*$/m', $body);
            array_shift($chunks); // preamble
            if (count($chunks) > 0 && preg_match('/^--' . $b . '--/m', $body)) {
                array_pop($chunks); // epilogue
            }
            $isAlt = $type === 'multipart/alternative';
            $isRel = $type === 'multipart/related';
            foreach ($chunks as $chunk) {
                $chunk = preg_replace('/^\n/', '', $chunk, 1);
                $chunk = preg_replace('/\n$/', '', $chunk, 1);
                [$h, $bd] = self::split($chunk);
                self::walk($h, $bd, $acc, $inRelated || $isRel, $depth + 1);
            }
            unset($isAlt);
            return;
        }

        $disp = $cd['value'];
        $filename = $cd['filename'] ?? ($ct['name'] ?? '');
        $filename = self::decodeHeader($filename);
        $isText = $type === 'text/plain' || $type === 'text/html';

        if ($isText && $disp !== 'attachment' && $filename === '') {
            $text = self::toUtf8(self::decodeBody($body, $cte), $ct['charset'] ?? 'us-ascii');
            $key = $type === 'text/html' ? 'html' : 'plain';
            if ($acc[$key] === null) {
                $acc[$key] = $text;
                return;
            }
            if ($key === 'plain' && $acc['html'] === null) {
                $acc[$key] .= "\n" . $text; // concatenated plain parts
                return;
            }
        }

        $content = self::decodeBody($body, $cte);
        if ($type === 'message/rfc822' && $filename === '') {
            $filename = 'message.eml';
        }
        if ($filename === '') {
            $ext = ['text/plain' => 'txt', 'text/html' => 'html', 'image/png' => 'png', 'image/jpeg' => 'jpg',
                'image/gif' => 'gif', 'application/pdf' => 'pdf', 'text/calendar' => 'ics'][$type] ?? 'bin';
            $filename = ($cid !== '' ? preg_replace('/[^A-Za-z0-9._-]/', '_', $cid) : 'attachment-' . (count($acc['attachments']) + 1)) . '.' . $ext;
        }
        $inline = $cid !== '' && ($inRelated || $disp === 'inline') && strpos($type, 'image/') === 0;
        $acc['attachments'][] = [
            'file_name' => $filename,
            'content_type' => $type,
            'content' => base64_encode($content),
            'inline' => $inline,
            '_cid' => $cid,
        ];
    }
}

function plog(string $level, string $msg): void
{
    Util::log($level, '[api] ' . $msg);
}

function finish(int $code, string $msg): void
{
    echo $msg . "\n"; // shown in Exim log (log_output) and in bounces
    exit($code);
}

// --------------------------------------------------------------------------
$raw = stream_get_contents(STDIN);
if ($raw === false || $raw === '') {
    finish(EX_TEMPFAIL, 'Maileroo: empty message on stdin');
}

try {
    $cfg = Config::loadPublic();
    [$headers, $body] = Mime::split($raw);

    $returnPath = trim((string) Mime::get($headers, 'Return-path'), " <>");
    $sender = (string) (getenv('SENDER') ?: $returnPath);
    $envelopeTo = array_map(fn($a) => strtolower($a['address']), Mime::addresses(Mime::get($headers, 'Envelope-to')));
    $envelopeTo = array_values(array_unique(array_filter($envelopeTo)));
    if (!$envelopeTo && getenv('RECIPIENT')) {
        $envelopeTo = [strtolower((string) getenv('RECIPIENT'))];
    }
    if (!$envelopeTo) {
        finish(EX_TEMPFAIL, 'Maileroo: no envelope recipients (Envelope-to header missing)');
    }

    $from = Mime::addresses(Mime::get($headers, 'From'))[0] ?? ($sender !== '' ? ['address' => $sender] : null);
    if ($from === null) {
        finish(EX_DATAERR, 'Maileroo: message has no From address');
    }

    $key = Resolver::key($cfg, $sender, $from['address']);
    $apiKey = $key !== null ? Util::lsearchGet(Paths::apikeys(), $key) : null;
    if ($apiKey === null || $apiKey === '') {
        finish(EX_TEMPFAIL, "Maileroo: no API sending key for sender $sender / " . $from['address']);
    }

    $acc = ['plain' => null, 'html' => null, 'attachments' => []];
    Mime::walk($headers, $body, $acc);

    // Classify envelope recipients against the visible headers.
    $toH = Mime::addresses(Mime::get($headers, 'To'));
    $ccH = Mime::addresses(Mime::get($headers, 'Cc'));
    $index = function (array $list) {
        $m = [];
        foreach ($list as $a) {
            $m[strtolower($a['address'])] = $a;
        }
        return $m;
    };
    $toMap = $index($toH);
    $ccMap = $index($ccH);
    $to = $cc = $bcc = [];
    foreach ($envelopeTo as $rcpt) {
        if (isset($toMap[$rcpt])) {
            $to[] = $toMap[$rcpt];
        } elseif (isset($ccMap[$rcpt])) {
            $cc[] = $ccMap[$rcpt];
        } else {
            $bcc[] = ['address' => $rcpt];
        }
    }

    $subject = Mime::decodeHeader((string) (Mime::get($headers, 'Subject') ?? ''));
    $base = [
        'from' => $from,
        'subject' => $subject !== '' ? mb_substr($subject, 0, 255) : '(no subject)',
    ];
    if ($acc['html'] !== null) {
        $base['html'] = $acc['html'];
    }
    if ($acc['plain'] !== null) {
        $base['plain'] = $acc['plain'];
    }
    if (!isset($base['html']) && !isset($base['plain'])) {
        $base['plain'] = ' ';
    }
    if ($acc['attachments']) {
        $base['attachments'] = array_map(function ($a) {
            unset($a['_cid']);
            return $a;
        }, $acc['attachments']);
    }
    $replyTo = Mime::addresses(Mime::get($headers, 'Reply-To'));
    if ($replyTo) {
        $base['reply_to'] = $replyTo;
    }
    if ($cfg['api_tracking'] !== 'account') {
        $base['tracking'] = $cfg['api_tracking'] === 'on';
    }

    // Pass through threading / list headers and custom X- headers.
    $pass = [];
    $skip = ['x-spam-', 'x-ham-', 'x-antiabuse', 'x-get-message-sender-via', 'x-authenticated-sender', 'x-source', 'x-maileroo'];
    foreach ($headers as [$n, $v]) {
        $ln = strtolower($n);
        $allowed = in_array($ln, ['in-reply-to', 'references', 'list-unsubscribe', 'list-unsubscribe-post', 'list-id',
            'precedence', 'auto-submitted', 'x-mailer', 'x-priority', 'importance'], true)
            || (strpos($ln, 'x-') === 0 && !array_filter($skip, fn($p) => strpos($ln, $p) === 0));
        if (!$allowed || isset($pass[$n]) || count($pass) >= 25) {
            continue;
        }
        if (strlen($v) > 768) {
            $v = $ln === 'references' ? trim(substr($v, -760)) : substr($v, 0, 768);
            if ($ln === 'references' && ($p = strpos($v, '<')) !== false) {
                $v = substr($v, $p);
            }
        }
        $pass[substr($n, 0, 128)] = $v;
    }
    if ($pass) {
        $base['headers'] = $pass;
    }
    $base['tags'] = ['source' => 'cpanel-exim'];
    if (getenv('MESSAGE_ID')) {
        $base['tags']['exim_id'] = (string) getenv('MESSAGE_ID');
    }

    // Build one request, or one per hidden recipient when nobody is visible.
    $requests = [];
    if ($to || $cc) {
        $p = $base;
        $p['to'] = $to ?: $cc;
        if ($to && $cc) {
            $p['cc'] = $cc;
        }
        if ($bcc) {
            $p['bcc'] = $bcc;
        }
        $requests[] = $p;
    } else {
        foreach ($bcc as $b) {
            $p = $base;
            $p['to'] = [$b];
            $requests[] = $p;
        }
    }

    $refs = [];
    foreach ($requests as $i => $payload) {
        $payload['reference_id'] = Util::randomHex(12);
        $res = Api::send($apiKey, $payload, (int) $cfg['api_timeout']);
        $rcpts = implode(',', array_map(fn($a) => $a['address'], array_merge($payload['to'], $payload['cc'] ?? [], $payload['bcc'] ?? [])));
        if (!$res['ok']) {
            plog('error', sprintf('%s from=%s to=%s HTTP %d: %s', getenv('MESSAGE_ID') ?: '-', $from['address'], $rcpts, $res['http'], $res['message']));
            if ($i > 0) {
                // Earlier hidden recipients were accepted; avoid re-sending them on retry.
                finish(EX_DATAERR, "Maileroo API rejected part of the batch (HTTP {$res['http']}): {$res['message']}");
            }
            finish($res['temporary'] ? EX_TEMPFAIL : EX_DATAERR, "Maileroo API error (HTTP {$res['http']}): {$res['message']}");
        }
        $refs[] = $res['reference_id'] ?? $payload['reference_id'];
        plog('info', sprintf('%s from=%s to=%s accepted ref=%s', getenv('MESSAGE_ID') ?: '-', $from['address'], $rcpts, end($refs)));
    }
    finish(EX_OK, 'Maileroo accepted ref=' . implode(',', $refs));
} catch (Throwable $e) {
    plog('error', 'exception: ' . $e->getMessage());
    finish(EX_TEMPFAIL, 'Maileroo pipe error: ' . $e->getMessage());
}
