-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsend-emails.php
More file actions
243 lines (212 loc) · 9.88 KB
/
Copy pathsend-emails.php
File metadata and controls
243 lines (212 loc) · 9.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
<?php
ob_start(); // Start output buffering
// CORS header
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include('./jwt-validation.php'); // Include the JWT validation code
include('./db-connection.php'); // Include the database connection code
// Retrieve data from the request
$data = file_get_contents('php://input');
$data = json_decode($data);
function getUserRolesFromDatabase($user_email, $jwt) {
//get user info from the api get-user-data.php
try {
$url = $_ENV['URL_BACKEND'].'/get-user-data.php';
$data = array('email' => $user_email);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Authorization: Bearer " . $jwt . "\r\n", // Add this line
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
// Handle the case where file_get_contents fails
http_response_code(500);
error_log('Error checking user role: file_get_contents failed');
return 'Error checking user role';
}
$user = json_decode($result, true);
if ($user && isset($user['groups'])) {
return $user['groups'];
} else {
error_log('User not found or groups not set');
return 'User not found';
}
} catch (Exception $e) {
http_response_code(500);
error_log('Error checking user role: ' . $e->getMessage());
return 'Error checking user role';
}
}
function getContactsByListId($id, $jwt) {
//get user info from the api get-user-data.php
try {
$url = $_ENV['URL_BACKEND'].'/get-contacts-by-list-id.php';
$data = array('id' => $id);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Authorization: Bearer " . $jwt . "\r\n", // Add this line
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
// Handle the case where file_get_contents fails
http_response_code(500);
error_log('Error getting contacts: file_get_contents failed');
return 'Error getting contacts';
}
return $result;
} catch (Exception $e) {
http_response_code(500);
error_log('Error getting contacts: ' . $e->getMessage());
return 'Error getting contacts';
}
}
function getPressContactsByListId($id, $jwt) {
//get user info from the api get-user-data.php
try {
$url = $_ENV['URL_BACKEND'].'/get-press-contacts-by-list-id.php';
$data = array('id' => $id);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Authorization: Bearer " . $jwt . "\r\n", // Add this line
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
// Handle the case where file_get_contents fails
http_response_code(500);
error_log('Error getting press contacts: file_get_contents failed');
return 'Error getting contacts';
}
return $result;
} catch (Exception $e) {
http_response_code(500);
error_log('Error getting press contacts: ' . $e->getMessage());
return 'Error getting contacts';
}
}
// Check if user role is 0 or 1
try {
$user_roles = getUserRolesFromDatabase($user_email, $jwt);
error_log('User roles: ' . print_r($user_roles, true));
} catch (Exception $e) {
// Log the error message for debugging
error_log("Error in getUserRoleFromDatabase: " . $e->getMessage());
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
ob_end_flush();
exit();
}
$rolesArray = json_decode($user_roles, true);
error_log('Roles array: ' . print_r($rolesArray, true));
if (!in_array(0, $rolesArray) && !in_array(1, $rolesArray)) {
error_log('Not authorized to send test mails');
echo json_encode(['error' => 'Not authorized to send test mails']);
exit();
}
// SEND EMAIL WITH BREVO API
$brevokey = $_ENV['BREVO_API_KEY'];
// Configure API key authorization: api-key
$config = Brevo\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', $brevokey);
$apiInstance = new Brevo\Client\Api\TransactionalEmailsApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client(),
$config
);
$date = new DateTime();
$dateString = $date->format('Y-m-d H:i:s');
$timestamp = $date->getTimestamp();
// Make it a string
$timestamp = strval($timestamp);
// Check if $data->contact_lists is an array and loop over it
if (is_array($data->contact_lists)) {
foreach ($data->contact_lists as $list) {
$contacts = getContactsByListId($list, $jwt);
$contacts = json_decode($contacts);
error_log('Contacts for list ' . $list . ': ' . print_r($contacts, true));
if (is_array($contacts)) {
foreach ($contacts as $contact) {
//make sure $contact->subscribed is 1 otherwise skip
if ($contact->subscribed !== 1) {
continue;
}
error_log('Sending email to: ' . $contact->email);
$unsubscribeHtml = "<p style=\"font-size:11px;color:#000000;text-decoration:underline; text-align:center;\"> <a style=\"font-size:11px;color:#000000;text-decoration:underline; text-align:center;\" href=\"https://enterprise.suzy.pro/unsubscribe?contact_id=".$contact->ID."&key=".$contact->unsubscribe_key."&type=regular\">unsubscribe</a></p>";
$sendSmtpEmail = new \Brevo\Client\Model\SendSmtpEmail([
'subject' => $data->subject,
'sender' => ['name' => 'Suzy.pro', 'email' => 'info@suzy.pro'],
'replyTo' => ['name' => 'Suzy.pro', 'email' => 'info@suzy.pro'],
'to' => [['email' => $contact->email]],
'htmlContent' => $data->message.$unsubscribeHtml,
'tags' => [$timestamp, 'contact_list'],
]); // \Brevo\Client\Model\SendSmtpEmail | Values to send a transactional email
try {
$result = $apiInstance->sendTransacEmail($sendSmtpEmail);
error_log("Email sent to: " . $contact->email . " Result: " . print_r($result, true));
} catch (Exception $e) {
error_log('Exception when calling TransactionalEmailsApi->sendTransacEmail: ' . $e->getMessage());
echo 'Exception when calling TransactionalEmailsApi->sendTransacEmail: ', $e->getMessage(), PHP_EOL;
}
}
}
}
}
// Check if $data->press_lists is an array and loop over it
if (is_array($data->press_lists)) {
foreach ($data->press_lists as $list) {
$contacts = getPressContactsByListId($list, $jwt);
$contacts = json_decode($contacts);
error_log('Press contacts for list ' . $list . ': ' . print_r($contacts, true));
if (is_array($contacts)) {
foreach ($contacts as $contact) {
//make sure $contact->subscribed is 1 otherwise skip
if ($contact->subscribed !== 1) {
continue;
}
$unsubscribeHtml = "<p style=\"font-size:11px;text-decoration:underline; text-align:center;color:#000000;\"> <a style=\"font-size:11px;text-decoration:underline; text-align:center;color:#000000;\" href=\"https://enterprise.suzy.pro/unsubscribe?contact_id=".$contact->ID."&key=".$contact->unsubscribe_key."&type=press\">unsubscribe</a></p>";
$sendSmtpEmail = new \Brevo\Client\Model\SendSmtpEmail([
'subject' => $data->subject,
'sender' => ['name' => 'Suzy.pro', 'email' => 'info@suzy.pro'],
'replyTo' => ['name' => 'Suzy.pro', 'email' => 'info@suzy.pro'],
'to' => [['email' => $contact->email]],
'htmlContent' => $data->message.$unsubscribeHtml,
'tags' => [$timestamp, 'press_list'],
]); // \Brevo\Client\Model\SendSmtpEmail | Values to send a transactional email
try {
$result = $apiInstance->sendTransacEmail($sendSmtpEmail);
error_log("Email sent to: " . $contact->email . " Result: " . print_r($result, true));
} catch (Exception $e) {
error_log('Exception when calling TransactionalEmailsApi->sendTransacEmail: ' . $e->getMessage());
echo 'Exception when calling TransactionalEmailsApi->sendTransacEmail: ', $e->getMessage(), PHP_EOL;
}
}
}
}
}
// Prepare the SQL statement to insert the mailing into the database
$stmt = $conn->prepare("INSERT INTO mailings (subject, tag, date) VALUES (?, ?, ?)");
// Bind the parameters to the statement
$stmt->bind_param("sss", $data->subject, $timestamp, $dateString);
// Execute the statement
$result2 = $stmt->execute();
if ($result2) {
error_log('Mailing record inserted successfully');
} else {
error_log('Failed to insert mailing record: ' . $stmt->error);
}
echo json_encode(['message' => 'success']);