[php]
<?php
class Communication
{
const MAILGUN_API = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const DOMAIN = 'XXXXXXXX.org';
public static function send( Array $msg, $recipient = false)
{
$config = array();
$config['api_key'] = self::MAILGUN_API;
$config['api_url'] = "https://api.mailgun.net/v3/mg." . self::DOMAIN . "/messages";
$message = array();
$message['from'] = $recipient ? "no-reply@" . self::DOMAIN : $msg['cEmail'];
$message['to'] = !$recipient ? "@" . self::DOMAIN : $msg['cEmail'];
$message['h:Reply-To'] = !$recipient ? $msg['cEmail'] : '';
$message['subject'] = $msg['cSubject'];
if(!$recipient) {
$template = 'to_domain';
} else {
$template = 'to_recipient';
}
$placeholders = ['{name}', '{message}', '{email}'];
$values = [htmlentities($msg['cName']), nl2br(htmlentities($msg['cMessage'])), htmlentities($msg['cEmail'])];
$content = str_replace($placeholders, $values, file_get_contents("/home/afbc/app/templates/{$template}.html"));
$message['html'] = $content;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $config['api_url']);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "api:{$config['api_key']}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
[/php]
And it's usage:
[php]<?php
require '../../app/classes/Communication.php';
require '../../app/classes/Logger.php';
try {
$google_secret = 'XXXXXXXXXXXXXXXXXX';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// return print_r($_POST);
$receivedRecaptcha = $_POST['g-recaptcha-response'];
$verifiedRecaptcha = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $google_secret . '&response=' . $receivedRecaptcha));
if ($verifiedRecaptcha) {
// print_r($_POST);
$body = "{$_POST['cName']}, {$_POST['cEmail']}, {$_POST['cSubject']}\n{$_POST['cMessage']}\n\n";
$file = fopen("contact.log", "a+");
fwrite($file, $body);
fclose($file);
if (filter_var($_POST['cEmail'], FILTER_VALIDATE_EMAIL)) {
if (Communication::send($_POST) && Communication::send($_POST, true)) {
$data['code'] = 200;
$data['msg'] = "Message Sent";
echo json_encode($data);
} else {
$data['code'] = 200;
$data['msg'] = "Message could not be Sent";
echo json_encode($data);
}
} else {
$data['code'] = 412;
$data['msg'] = "Email was not valid";
echo json_encode($data);
}
} else {
$data['code'] = 412;
$data['msg'] = "ReCaptcha Was not valid";
echo json_encode($data);
}
} else {
$data['code'] = 500;
$data['msg'] = "Message could not be Sent";
echo json_encode($data);
}
} catch ( Exception $e) {
Logger::log(print_r($e));
}[/php]