File: /home/awaldron/_domains/api.pennhillscdc.org/v1/mail.php
<?php
//**********************************************************************************************************//
// Method: GET
// Endpoint: send
// Params: subject, body
function get_v1_mail_campaigns( $args, $body, $uid, $is_admin, $db ) {
validate_token( $uid );
validate_admin( $is_admin );
$data = qSet( $db, "SELECT ec.*, er.er_action, COUNT(er.er_action) as `count`
FROM email_campaigns as ec
LEFT JOIN email_results as er ON ec.ec_id=er.ec_id
WHERE ec_recipients IN ( 'all', 'active', 'expired', 'recruits' )
GROUP BY ec.ec_id, er.er_action
ORDER BY ec.ec_id DESC"
);
$out = [];
$id = 0;
foreach ($data as $d) {
if ($d['ec_id'] !== $id) {
$date = $d['ec_created'] - (3600 * 4) - ( !!date('I') ? 3600 : 0 );
$tmp = Array('id'=>$d['ec_id'],
'subject' => $d['ec_subject'],
'recipients'=>$d['ec_recipients'],
'recipient_count'=>$d['ec_recip_ct'],
'day'=> date('l', $date),
'date'=> date('m/d/Y', $date),
'time'=> date('h:i a', $date),
);
$out[] = $tmp;
$id = $d['ec_id'];
}
$out[count($out)-1][$d['er_action']] = $d['count'];
}
response(200,['success'=>true, 'data'=>$out, 'offset'=>( !!date('I') ? 3600 : 0 )]);
}
//**********************************************************************************************************//
// Method: POST
// Endpoint: mail/subscribe
// Description: Subscribe to the mailing list
// Params: body array
function post_v1_mail_subscribe( $args, $body, $uid, $is_admin, $db ) {
// CHECK TO SEE IF EMAIL EXISTS IN THE SYSTEM
$exists = qVal($db, "SELECT email FROM members WHERE email='".$body['email']."'");
// IF USER EXISTS, JUST RESUBSCRIBE THEM
if ($exists) {
$db->query("UPDATE members SET maillist=1 WHERE email='".$body['email']."'");
response(200, ['success'=>false,'errors'=>['Email address already exists. User re-subscribed.']]);
} else {
response(200, ['success'=>true]);
}
}
//**********************************************************************************************************//
// Method: GET
// Endpoint: send
// Params: subject, body
function get_v1_mail_unsubscribe( $args, $body, $uid, $is_admin, $db ) {
$mailcode = $args[0];
$ecid = $args[1];
$m = qRow( $db, "SELECT * FROM members WHERE mailcode='".$mailcode."'" );
if (count($m) > 0) {
$name = $m['lname'].', '.$m['fname'];
$db->query("INSERT INTO email_results (ec_id, er_member, er_action, er_time) VALUES (".$ecid.", '".$name."', 'unsubscribed', ".time().")");
$db->query("UPDATE members SET maillist=0 WHERE member_id=".$m['member_id']);
echo '<div style="font-size:16px;font-family:sans-serif;margin:40px;">';
echo '<img src="https://pennhillscdc.org/e/logo-horz-litebg.png" style="max-width:250px;">';
echo '<p>You have been unsubscribed from further Penn Hills CDC emails.</p>';
echo "<p>We're sorry to see you go!</p>";
echo '<p>If this was done in error, <a href="https://api.pennhillscdc.org/v1/mail/resubscribe/'.$mailcode.'">click here to re-subscribe.</a>';
echo '</div>';
}
}
//**********************************************************************************************************//
// Method: GET
// Endpoint: send
// Params: subject, body
function get_v1_mail_resubscribe( $args, $body, $uid, $is_admin, $db ) {
$mailcode = $args[0];
$member_id = qVal( $db, "SELECT member_id FROM members WHERE mailcode='".$mailcode."'" );
if ($member_id) {
$db->query("UPDATE members SET maillist=1 WHERE member_id=".$member_id);
echo '<div style="font-size:16px;font-family:sans-serif;margin:40px;">';
echo '<img src="https://pennhillscdc.org/e/logo-horz-litebg.png" style="max-width:250px;">';
echo '<p>You have successfully subscribed to the Penn Hills CDC email list.</p>';
echo "<p>We're happy to have you here!</p>";
echo '</div>';
}
}
//**********************************************************************************************************//
// Method: GET
// Endpoint: read
// Params:
function get_v1_mail_read( $args, $body, $uid, $is_admin, $db ) {
$mailcode = $args[0];
$ecid = $args[1];
$m = qRow( $db, "SELECT * FROM members WHERE mailcode='".$mailcode."'" );
if ($m && count($m) > 0) {
$name = $m['lname'].', '.$m['fname'];
$db->query("INSERT INTO email_results (ec_id, er_member, er_action, er_time) VALUES (".$ecid.", '".$name."', 'read', ".time().")");
}
$img = '/home/awaldron/_domains/api.pennhillscdc.org/v1/email-footer.png';
header('Content-Type: image/png');
readfile($img);
}
//**********************************************************************************************************//
// Method: POST
// Endpoint: send
// Params: subject, body
function post_v1_mail_send( $args, $body, $uid, $is_admin, $db ) {
$rules = [
'from' => 'req',
'to' => 'req',
'subject' => 'req',
'body' => 'req'
];
$token_required = true;
$sql = "SELECT m.*, g.paid_thru FROM members as m
LEFT JOIN group_member as gm ON gm.member_id=m.member_id
LEFT JOIN groups as g on gm.group_id=g.group_id
WHERE m.visible=1 AND m.maillist=1 AND m.email <> ''";
if ($body['to'] === 'active') {
$sql .= " AND g.paid_thru >= ".date("Y");
} else if ($body['to'] === 'expired') {
$sql .= " AND (g.paid_thru < ".date("Y")." AND g.paid_thru > 1999)";
} else if ($body['to'] === 'recruits') {
$sql .= " AND g.paid_thru = 1999";
} else if ($body['to'] === 'test') {
$sql .= " AND m.member_id=1001";
} else if ($body['to'] === 'all') {
$sql .= "";
} else {
$sql .= " AND m.member_id=".$body['to'];
$token_required = false;
}
if ($body['to'] === 'admins') {
$sql = "SELECT m.*, g.paid_thru
FROM members AS m
LEFT JOIN users AS u ON m.user_id = u.user_id
LEFT JOIN group_member AS gm ON m.member_id = gm.member_id
LEFT JOIN groups AS g ON gm.group_id = g.group_id
WHERE u.admin = 1";
}
if ($token_required) {
validate_token( $uid );
validate_admin( $is_admin );
}
validate_body( $body, $rules );
$members = qSet( $db, $sql );
$db->query("INSERT INTO email_campaigns (ec_subject, ec_sender, ec_recipients, ec_recip_ct, ec_created) VALUES ('".addslashes($body['subject'])."', '".addslashes($body['from'])."', '".$body['to']."', ".count($members).", ".time().")");
$email_id = qVal( $db, "SELECT MAX(ec_id) as maxval FROM email_campaigns");
$errors = [];
$from = explode('||', $body['from']);
// PREVENT DUPLICATE MESSAGES FROM GOING OUT
// IGNORE IF TEST
$ok_to_send = true;
if ($body['to'] !== 'test') {
$check_time = time() - (4 * 60 * 60); // 4 hours ago
$campaign_ct = qVal( $db, "SELECT COUNT(ec_id) as cct FROM email_campaigns
WHERE ec_subject='".addslashes($body['subject'])."'
AND ec_recipients='".$body['to']."'
AND ec_created > ".$check_time
);
if ($campaign_ct >= 2) {
$ok_to_send = false;
}
}
if ($ok_to_send) {
foreach ($members as $m) {
if (!empty($m['email'])) {
try {
$email = get_email_template( $body, $m, $email_id );
$mail = new PHPMailer\PHPMailer\PHPMailer(true);
$mail->isSMTP();
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Host = "mail.smtp2go.com";
$mail->Port = "2525";
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Username = "pennhillscdc";
$mail->Password = "xVnXrJGR76RMycPL";
$mail->setFrom($from[1], "Penn Hills CDC");
$mail->AddReplyTo($from[1], $from[0]);
$mail->AddAddress($body['to'] === 'test' ? $body['testEmail'] : $m['email'], $m['fname'].' '.$m['lname']);
$mail->isHTML(true);
$mail->Subject = $body['subject'];
$mail->Body = $email;
$mail->send();
} catch (Exception $e) {
$errors[] = $mail->ErrorInfo;
}
}
}
}
if (!$ok_to_send) {
response(200, ['success'=>false, 'error'=>'Duplicate campaign detected. Subject matches a recently sent campaign.']);
}
else if ( count($errors) === count($members) ) {
response(200, ['success'=>false, 'error'=>'All '.count($members).' emails failed. Last error:'.$mail->ErrorInfo]);
}
else if ( count($errors) > 0 ) {
$okct = count($members) - count($errors);
response(200, ['success'=>false, 'error'=>$okct.' of '.count($members).' emails sent successfully. Last error:'.$mail->ErrorInfo]);
}
else {
response(200,['success'=>true, 'message'=>'All '.count($members).' emails sent successfully']);
}
}
//**********************************************************************************************************//
// Method: POST
// Endpoint: sendone
// Params: subject, body
function post_v1_mail_sendone( $args, $body, $uid, $is_admin, $db ) {
$rules = [
'email' => 'req',
'from' => 'req',
'subject' => 'req',
'body' => 'req'
];
$token_required = true;
if ($token_required) {
validate_token( $uid );
validate_admin( $is_admin );
}
validate_body( $body, $rules );
$errors = [];
$from = explode('||', $body['from']);
$email_id = qVal( $db, "SELECT MAX(ec_id) as maxval FROM email_campaigns");
try {
$email = get_email_template_one( $body['body'], $body['subject'], $body['fname'], $body['mailcode'], $email_id );
$mail = new PHPMailer\PHPMailer\PHPMailer(true);
$mail->isSMTP();
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Host = "mail.smtp2go.com";
$mail->Port = "2525";
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Username = "pennhillscdc";
$mail->Password = "xVnXrJGR76RMycPL";
$mail->setFrom($from[1], "Penn Hills CDC");
$mail->AddReplyTo($from[1], $from[0]);
$mail->AddAddress($body['email'], $body['fname'].' '.$body['lname']);
$mail->isHTML(true);
$mail->Subject = $body['subject'];
$mail->Body = $email;
$mail->send();
} catch (Exception $e) {
$errors[] = $mail->ErrorInfo;
}
response(200,['success'=>true, 'message'=>'Email sent successfully']);
}