Odyssey
mBroadcastEmail.data
1 <?php
2 /**
3  * FILE: mBroadcastEmail.data
4  * This holds functions for tackling the backend of mBroadcastEmail.prg.
5  */
6 
7 /**
8  * function GetBroadcastFileLoc()
9  * This gets the directory where we save to/read from.
10  */
11 function GetBroadcastFileLoc() {
12  return "/home/homecu/tmp/";
13 }
14 
15 /**
16  * function GetGoogleCookie($devmode)
17  * This gets the cookie for google authentication.
18  *
19  * @param $devmode -- if 1, then get a hardcoded form of the cookie.
20  * (This has to be updated to test my.homecu.net data.)
21  *
22  * @return the contents of the cookie.
23  */
24 function GetGoogleCookie($devmode) {
25  if ($devmode == 1) {
26  $googleCookie = "c2FtdWVsQGhvbWVjdS5jb218TVZqSHg3dzRZSzlVZksyUkdsdmc0QzJheCtNQjlxLzhsbEN1MXVxUUFOSXFlZ3J1THZmTkxvRW53cjZsV2ZMY2IxdHk1SkZVdGdic1U2UWpRSjU2UytvL2NWaEIzQnl6VWcrRFNzT2lHRDRuaFFGRlNlOUJlVENDWGd4WkVOWjFQNytueldEL21yVjZlc2xjQ2dtbzNLL0xOZEltMks5Q2dpY0E2YlFuWk9WU2J6VzE3U0REalNFeTJpWHYzNS9LeXc9PXwxNTY2NTc1OTMyfFRyMVE0SU42K0o0QXlhWSt4YkVOWFVpT21lWGVxb0ZJQWhMY1gyUFQvb3RhU1gwa0NVT0lGTktvL2RNWEJpSDVwbDBITHRzNEpwb2c3bk91dWc9PQ==|1566572332|L2UZZ4lu2KexoIzFRxzMpDNu_cU=";
27  } else {
28  $googleCookie = "{$_COOKIE['homecu_dev_oauth2_proxy']}";
29  }
30  return $googleCookie;
31 }
32 
33 /**
34  * function GetDefaultEmail()
35  * This gets the default email to use in the from list.
36  *
37  * @return the string value.
38  */
39 function GetDefaultEmail() {
40  return "support@homecu.net";
41 }
42 
43 /**
44  * function GetWhenToGetNewCopy()
45  * This gets how much time elapses before getting new data.
46  *
47  * @return the seconds. (Currently set to a hour.)
48  */
49 function GetWhenToGetNewCopy() {
50  return 60 * 60;
51 }
52 
53 /**
54  * function GatherCuList($dbh, $sysenv)
55  * This gets the cu list from monitor or localhost.
56  * It uses report number 1 on the hcucontact_rpt.prg script.
57  *
58  * @param $dbh -- the database connection.
59  * @param $sysenv -- the system environment (uses devmode.)
60  *
61  * @return $status -- "000" if successful, nonzero otherwise.
62  * @return $error -- "" if successful, nonempty otherwise.
63  */
64 function GatherCuList($dbh, $sysenv) {
65  try {
66  $hcuTicket = urlencode($_COOKIE['HCUTicket']);
67  $googleCookie = GetGoogleCookie($sysenv["devmode"]);
68 
69  // Requirements: keep it the same for Odyssey as for Mammoth CUs.
70  // but also, I want to be able to test without risking sending to real emails...
71  if ($sysenv["devmode"] == 1) {
72  $curlCookies = "HCUTicket=$hcuTicket";
73  $url = "http://localhost/hcuadm/hcucontact_rpt.prg?report=1&csv=raw";
74  } else {
75  // Step 1: monitor.
76  $curlCookies = "HCUTicket=$hcuTicket;homecu_dev_oauth2_proxy=$googleCookie";
77  $url = "https://my.homecu.net/hcuadm/hcucontact_rpt.prg?report=1&csv=raw";
78  }
79 
80  $ch = curl_init($url);
81  curl_setopt($ch, CURLOPT_COOKIE, $curlCookies);
82  curl_setopt($ch, CURLOPT_USERPWD, "nobody:no1home");
83  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); # get response as string
84 
85  $rawresp = curl_exec($ch);
86  curl_close($ch);
87 
88  $serverList = array();
89 
90  if ($rawresp) {
91  $lines = explode("\r\n", $rawresp);
92 
93  foreach($lines as $i => $line) {
94  // I don't care about the title or types.
95  if ($i < 2 || trim($line) == "") {
96  continue;
97  }
98 
99  $values = explode("\t", $line);
100  $cu = HCU_array_key_value(0, $values);
101  $wwwServer = HCU_array_key_value(1, $values);
102  $cu = $cu === false ? "" : trim($cu);
103  $wwwServer = $wwwServer === false ? "" : trim($wwwServer);
104  switch($wwwServer) {
105  case "my.homecu.net":
106  if (!HCU_array_key_exists("my", $serverList)) {
107  $serverList["my"] = array();
108  }
109  $serverList["my"][$cu] = true;
110  break;
111  case "www3":
112  if (!HCU_array_key_exists("www3", $serverList)) {
113  $serverList["www3"] = array();
114  }
115  $serverList["www3"][$cu] = true;
116  break;
117  case "www5":
118  if (!HCU_array_key_exists("www5", $serverList)) {
119  $serverList["www5"] = array();
120  }
121  $serverList["www5"][$cu] = true;
122  break;
123  case "www6":
124  if (!HCU_array_key_exists("www6", $serverList)) {
125  $serverList["www6"] = array();
126  }
127  $serverList["www6"][$cu] = true;
128  break;
129  case "localhost":
130  if (!HCU_array_key_exists("localhost", $serverList)) {
131  $serverList["localhost"] = array();
132  }
133  $serverList["localhost"][$cu] = true;
134  break;
135  }
136  }
137  }
138 
139  $elist = GetBroadcastFileLoc() . "elist_master";
140 
141  $handle = fopen("${elist}.new", "w");
142 
143  if (!$handle) {
144  throw new exception ("couldn't open file ${elist}.new", 2);
145  }
146 
147  fwrite($handle, HCU_JsonEncode($serverList));
148  fclose($handle);
149 
150  $returnArray = array("status" => "000", "error" => "");
151  } catch (exception $e) {
152  $returnArray = array("status" => $e->getCode(), "error" => $e->getMessage());
153  }
154  return $returnArray;
155 }
156 
157 /**
158  * function GatherEmailListByServer($dbh, $sysenv, $server, $validCus)
159  * This gets all the emails from a server.
160  * It uses report number 4 on the hcucontact_rpt.prg script.
161  *
162  * @param $dbh -- the database connection.
163  * @param $sysenv -- the system environment. (Uses devmode.)
164  * @param $server -- the server to get data from.
165  * @param $validCus -- the valid cus for the server.
166  *
167  * @return $status -- "000" if successful, nonzero otherwise.
168  * @return $error -- "" if successful, nonempty otherwise.
169  */
170 function GatherEmailListByServer($dbh, $sysenv, $server, $validCus) {
171  try {
172  $hcuTicket = urlencode($_COOKIE['HCUTicket']);
173  $googleCookie = GetGoogleCookie($sysenv["devmode"]);
174 
175  if ($server == "my") {
176  $url = "https://my.homecu.net/hcuadm/hcucontact_rpt.prg?report=4&csv=raw";
177  $curlCookies = "HCUTicket=$hcuTicket;homecu_dev_oauth2_proxy=$googleCookie";
178  } else if ($sysenv["devmode"] == 1 && $server == "localhost") {
179  $url = "http://localhost/hcuadm/hcucontact_rpt.prg?report=4&csv=raw";
180  $curlCookies = "HCUTicket=$hcuTicket";
181  } else {
182  $url = "https://$server.homecu.net/hcuadm/hcucontact_rpt?report=4&csv=raw";
183  $curlCookies = "HCUTicket=$hcuTicket";
184  }
185 
186  $ch = curl_init($url);
187  curl_setopt($ch,CURLOPT_COOKIE, $curlCookies);
188  curl_setopt($ch,CURLOPT_USERPWD, "nobody:no1home");
189  curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); # get response as string
190 
191  $rawresp = curl_exec($ch);
192  curl_close($ch);
193 
194  $cuList = array();
195  if ($rawresp) {
196 
197  $lines = explode("\r\n", $rawresp);
198 
199  foreach($lines as $i => $line) {
200  // I don't care about the title or types.
201  if ($i < 2 || trim($line) == "") {
202  continue;
203  }
204 
205  $values = explode("\t", $line);
206 
207  $cu = HCU_array_key_value(0, $values);
208  $email = HCU_array_key_value(1, $values);
209  $cu = $cu === false ? "" : trim($cu);
210  $email = $email === false ? "" : trim($email);
211 
212  # if the monitor list has this cu on this server, store the result
213  if (HCU_array_key_exists($cu, $validCus) && $email != "") {
214  $cuList[$cu] = $email;
215  }
216  }
217  }
218 
219  $newCuList = array();
220  foreach ($cuList as $cu => $email) {
221  $newCuList[$cu] = array();
222  rtrim($email);
223  $emlist = preg_split('/[;, ]/',$email);
224  foreach ($emlist as $em) {
225  $em = trim($em);
226  if ("$em" <> "") {
227  $newCuList[$cu][] = $em;
228  }
229  }
230  }
231 
232  $elist = GetBroadcastFileLoc() . "elist_$server";
233  $handle = fopen("${elist}.new", "w");
234 
235  if (!$handle) {
236  throw new exception ("couldn't open file ${elist}.new", 2);
237  }
238 
239  fwrite($handle, HCU_JsonEncode($newCuList));
240  fclose($handle);
241 
242  $returnArray = array("status" => "000", "error" => "");
243  } catch (exception $e) {
244  $returnArray = array("status" => $e->getCode(), "error" => $e->getMessage());
245  }
246  return $returnArray;
247 }
248 
249 /**
250  * function ReadSetup($dbh, $sysenv)
251  * This sets up the page for download a CSV or sending emails.
252  * It returns all data for the kendo controls and preloads data from the servers.
253  *
254  * @param $dbh -- the database connection.
255  * @param $sysenv -- the system environment. (Uses devmode.)
256  *
257  * @return $status -- "000" if successful, nonzero otherwise.
258  * @return $error -- "" if successful, nonempty otherwise.
259  * @return $action -- "read." Tells the datasource what to do with results.
260  */
261 function ReadSetup($dbh, $sysenv) {
262  try {
263  $sql = "select email from cuadmnotify where cu = 'HOMECU' and role = 'SES'";
264  $sth = db_query($sql, $dbh);
265  if (!$sth) {
266  throw new exception ("Select statement failed.", 1);
267  }
268  $emailList = array();
269  if (db_num_rows($sth) > 0) {
270  $row = db_fetch_assoc($sth, 0);
271  $decodedList = HCU_JsonDecode($row["email"]);
272  foreach ($decodedList as $emailRec) {
273  if ($emailRec["verified"]) {
274  $emailList[] = $emailRec["email"];
275  }
276  }
277  }
278 
279  // Add the default "from."
280  array_unshift($emailList, GetDefaultEmail());
281 
282  $servers = array("ALL", "my", "www5", "www3", "www6");
283 
284  if ($sysenv["devmode"] == 1) {
285  $servers[] = "localhost";
286  }
287 
288  $serverList = array();
289  $whenToGetNewCopy = GetWhenToGetNewCopy();
290  $now = time();
291 
292  $file = GetBroadcastFileLoc() . "elist_master.new";
293  if (file_exists($file)) {
294  if ($now - filemtime($file) < $whenToGetNewCopy) {
295  $results = GatherCuList($dbh, $sysenv);
296  if ($results["status"] !== "000") {
297  throw new exception ($results["error"], 1);
298  }
299  }
300  } else {
301  $file = GetBroadcastFileLoc() . "elist_master.last";
302 
303  // last file doesn't exist or was modified more than a hour ago.
304  if (!file_exists($file) || $now - filemtime($file) < $whenToGetNewCopy) {
305  $results = GatherCuList($dbh, $sysenv);
306  if ($results["status"] !== "000") {
307  throw new exception ($results["error"], 7);
308  }
309  $file = GetBroadcastFileLoc() . "elist_master.new";
310  }
311  }
312  if (!file_exists($file)) {
313  throw new exception ("Cu List doesn't exist.", 2);
314  }
315  $serverList = file_get_contents($file);
316  if ($serverList == null || trim($serverList) == "") {
317  throw new exception ("Cu List doesn't exist.", 3);
318  }
319  $serverList = HCU_JsonDecode($serverList);
320 
321  // Step 2: Email Lists
322  $cus = array();
323  foreach($serverList as $server => $validCus) {
324  $file = GetBroadcastFileLoc() . "elist_$server.new";
325  if (file_exists($file)) {
326  if ($now - filemtime($file) < $whenToGetNewCopy) {
327  $results = GatherEmailListByServer($dbh, $sysenv, $server, $validCus);
328  if ($results["status"] !== "000") {
329  throw new exception ($results["error"], 4);
330  }
331  }
332  } else {
333  $file = GetBroadcastFileLoc() . "elist_$server.last";
334 
335  // last file doesn't exist or was modified more than a hour ago.
336  if (!file_exists($file) || $now - filemtime($file) < $whenToGetNewCopy) {
337  $results = GatherEmailListByServer($dbh, $sysenv, $server, $validCus);
338  if ($results["status"] !== "000") {
339  throw new exception ($results["error"], 5);
340  }
341  $file = GetBroadcastFileLoc() . "elist_$server.new";
342  }
343  }
344 
345  if (!file_exists($file)) {
346  throw new exception ("Cu List doesn't exist.", 6);
347  }
348 
349  $cus = array_merge($cus, array_keys($validCus));
350  }
351  sort($cus, SORT_STRING);
352 
353  $actions = array(array("text" => "Email", "value" => "email"),
354  array("text" => "Download Tab-Delimited File", "value" => "download"));
355 
356  $data = array("emailList" => $emailList, "servers" => $servers, "cuList" => $cus, "actions" => $actions);
357  $returnArray = array("status" => "000", "error" => "", "data" => $data, "action" => "read");
358 
359  } catch (exception $e) {
360  $returnArray = array("status" => $e->getCode(), "error" => $e->getMessage(), "action" => "read");
361  }
362  return $returnArray;
363 }
364 
365 /**
366  * function GetFilteredCUList($sysenv)
367  * This gets a filtered list based on the Cu and server options.
368  *
369  * @param $sysenv -- the system variables
370  * Uses post variables in "IMPORTS" and devmode.
371  *
372  * @return $status -- "000" if successful, nonzero otherwise.
373  * @return $error -- "" if successful, nonempty otherwise.
374  * @return $cuList -- list of CUs & their emails.
375  */
376 function GetFilteredCUList($sysenv) {
377  try {
378  $file = GetBroadcastFileLoc() . "elist_master.new";
379  if (!file_exists($file)) {
380  $file = GetBroadcastFileLoc() . "elist_master.last";
381 
382  if (!file_exists($file)) {
383  throw new exception ("Master file doesn't exist.", 1);
384  }
385  }
386  $serverList = file_get_contents($file);
387  if ($serverList == null || trim($serverList) == "") {
388  throw new exception ("Master file doesn't exist.", 2);
389  }
390 
391  $filteredCus = HCU_array_key_value("filteredCus", $sysenv["IMPORTS"]);
392  $filteredServers = HCU_array_key_value("filteredServers", $sysenv["IMPORTS"]);
393  $filteredCus = $filteredCus === false ? "" : trim($filteredCus);
394  $filteredServers = $filteredServers === false ? "" : trim($filteredServers);
395 
396  if ($filteredCus == "") {
397  throw new exception ("Filtered Cus are required.", 5);
398  }
399  if ($filteredServers === "") {
400  throw new exception ("Filtered servers are required.", 6);
401  }
402  $filteredCus = HCU_JsonDecode($filteredCus);
403  $filteredServers = HCU_JsonDecode($filteredServers);
404 
405  $serverList = HCU_JsonDecode($serverList);
406  $cuList = array();
407  foreach($serverList as $server => $unused) {
408  if (count($filteredServers) > 0 && !in_array("ALL", $filteredServers) && !in_array($server, $filteredServers)) {
409  continue;
410  }
411  $file = GetBroadcastFileLoc() . "elist_$server.new";
412  if (!file_exists($file)) {
413  $file = GetBroadcastFileLoc() . "elist_$server.last";
414 
415  if (!file_exists($file)) {
416  throw new exception ("Server file $server doesn't exist.", 3);
417  }
418  }
419  $serverCus = file_get_contents($file);
420  if ($serverCus == null || trim($serverCus) == "") {
421  throw new exception ("Server file $server doesn't exist.", 4);
422  }
423  $serverCus = HCU_JsonDecode($serverCus);
424 
425  foreach($serverCus as $cu => $emails) {
426  if (count($filteredCus) > 0 && !in_array($cu, $filteredCus)) {
427  continue;
428  }
429  $cuRecord = array("cu" => $cu, "server" => $server, "emails" => $emails);
430  $cuList[$cu] = $cuRecord;
431  }
432  }
433 
434  // Now sort
435  ksort($cuList, SORT_STRING);
436 
437  $returnArray = array("status" => "000", "error" => "", "cuList" => $cuList);
438  } catch (exception $e) {
439  $returnArray = array("status" => $e->getCode(), "error" => $e->getMessage());
440  }
441  return $returnArray;
442 }
443 
444 /**
445  * function ChangeToLast()
446  * This changes the files from .new to .last to preserve history up to two places.
447  *
448  * @return $status -- "000" if successful, nonzero otherwise.
449  * @return $error -- "" if successful, nonempty otherwise.
450  */
451 function ChangeToLast() {
452  try {
453  $fileList = array("master", "localhost", "www3", "www5", "www6", "my");
454  foreach($fileList as $filePart) {
455  $file = GetBroadcastFileLoc() . "elist_$filePart";
456  if (file_exists("$file.new")) {
457  $results = shell_exec("mv ${file}.new ${file}.last 2>&1");
458  if ($results != "") {
459  throw new exception ($results, 1);
460  }
461  }
462  }
463 
464  $returnArray = array("status" => "000", "error" => "");
465  } catch (exception $e) {
466  $returnArray = array("status" => $e->getCode(), "error" => $e->getMessage());
467  }
468  return $returnArray;
469 }
470 
471 /**
472  * function DownloadCSV($dbh, $sysenv)
473  * This downloads a CSV from filtered CU and server options.
474  *
475  * @param $dbh -- the database connection.
476  * @param $sysenv -- the system environment. (Uses post variables in "IMPORTS".)
477  *
478  * @return void
479  */
480 function DownloadCSV($dbh, $sysenv) {
481  try {
482  $csvData = array();
483  $results = GetFilteredCUList($sysenv);
484 
485  if ($results["status"] !== "000") {
486  throw new exception ($results["error"], 1);
487  }
488 
489  $csvData[] = "Display Name\tServer\tPrimary Email";
490 
491  foreach($results["cuList"] as $cuRecord) {
492  foreach($cuRecord["emails"] as $email) {
493  $csvData[] = $cuRecord["cu"] . "\t" . $cuRecord["server"] . "\t" . $email;
494  }
495  }
496 
497  $results = ChangeToLast();
498  if ($results["status"] !== "000") {
499  throw new exception ($results["error"], 2);
500  }
501 
502  } catch (exception $e) {
503  $csvData = array("Download Failed: " . $e->getMessage());
504  }
505 
506  $csvData = implode("\r\n", $csvData);
507 
508  header("Content-length: " . strlen($csvData) );
509  header("Content-type: application/octetstream");
510  header("Content-disposition: inline; filename=\"elist.csv\"");
511  print ($csvData);
512 }
513 
514 /**
515  * function ValidateEmailParameters($sysenv, $requireTestEmail)
516  * This validates & sanitizes input for emails.
517  *
518  * @param $sysenv -- the system environment. (Uses post variables in "IMPORTS".)
519  * @param $requireTestEmail -- if true, then also throw if the test email is invalid.
520  *
521  * @return $status -- "000" if successful, nonzero otherwise.
522  * @return $error -- "" if successful, nonempty otherwise.
523  * @return $data -- array of the sanitized values.
524  */
525 function ValidateEmailParameters($sysenv, $requireTestEmail) {
526  try {
527  $fromEmail = HCU_array_key_value("fromEmail", $sysenv["IMPORTS"]);
528  $fromEmail = $fromEmail === false ? "" : trim($fromEmail);
529  if ($fromEmail == "") {
530  throw new exception("From Email is required.", 1);
531  }
532  $fromName = HCU_array_key_value("fromName", $sysenv["IMPORTS"]);
533  $fromName = $fromName === false ? "" : trim($fromName);
534 
535  $subject = HCU_array_key_value("subject", $sysenv["IMPORTS"]);
536  $subject = $subject === false ? "" : trim($subject);
537 
538  $testEmail = HCU_array_key_value("testEmail", $sysenv["IMPORTS"]);
539  $testEmail = $testEmail === false ? "" : trim($testEmail);
540  if ($testEmail == "" && $requireTestEmail) {
541  throw new exception ("Test Email is required.", 2);
542  }
543 
544  $body = HCU_array_key_value("body", $sysenv["IMPORTS"]);
545  $body = $body === false ? "" : htmlspecialchars_decode(trim($body));
546 
547  if (!validateEmail($fromEmail)) {
548  throw new exception ("From Email is not valid.", 3);
549  }
550 
551  if ($testEmail != "" && !validateEmail($testEmail)) {
552  throw new exception ("Test Email is not valid.", 4);
553  }
554 
555  $data = array("fromEmail" => $fromEmail, "fromName" => $fromName, "subject" => $subject, "testEmail" => $testEmail, "body" => $body);
556  $returnArray = array("status" => "000", "error" => "", "data" => $data);
557  } catch (exception $e) {
558  $returnArray = array("status" => $e->getCode(), "error" => $e->getMessage());
559  }
560  return $returnArray;
561 }
562 
563 /**
564  * function SendTestEmail($dbh, $sysenv)
565  * This sends a test email.
566  *
567  * @param $dbh -- the database connection.
568  * @param $sysenv -- the system environment. (Uses post variables in "IMPORTS".)
569  *
570  * @return $status -- "000" if successful, nonzero otherwise.
571  * @return $error -- "" if successful, nonempty otherwise.
572  * @return $action -- "preview." Tells the datasource what to do with results.
573  */
574 function SendTestEmail($dbh, $sysenv) {
575  try {
576  $results = ValidateEmailParameters($sysenv, true);
577  if ($results["status"] !== "000") {
578  throw new exception ($results["error"], 1);
579  }
580  extract($results["data"]);
581 
582  $notify = new ErrorMail;
583  $notify->mailfrom = $fromEmail;
584  $notify->mailfromname = $fromName;
585  $notify->subject = $subject;
586  $notify->htmlMsgbody = $body;
587  $notify->executeQuietly = true;
588  $notify->mailto = $testEmail;
589  $notify->SendMail();
590 
591  $returnArray = array("status" => "000", "error" => "", "action" => "preview");
592  } catch (exception $e) {
593  $returnArray = array("status" => $e->getCode(), "error" => $e->getMessage(), "action" => "preview");
594  }
595  return $returnArray;
596 }
597 
598 /**
599  * function SendEmails($dbh, $sysenv)
600  * This sends emails to all emails from the filtered list.
601  *
602  * @param $dbh -- the database connection.
603  * @param $sysenv -- the system environment. (Uses post variables in "IMPORTS".)
604  *
605  * @return $status -- "000" if successful, nonzero otherwise.
606  * @return $error -- "" if successful, nonempty otherwise.
607  * @return $action -- "send." Tells the datasource what to do with results.
608  */
609 function SendEmails($dbh, $sysenv) {
610  try {
611  $results = ValidateEmailParameters($sysenv, false);
612  if ($results["status"] !== "000") {
613  throw new exception ($results["error"], 1);
614  }
615  extract($results["data"]);
616 
617  $results = GetFilteredCUList($sysenv);
618 
619  if ($results["status"] !== "000") {
620  throw new exception ($results["error"], 2);
621  }
622 
623  $emailList = array();
624  foreach($results["cuList"] as $cuRecord) {
625  foreach($cuRecord["emails"] as $email) {
626  $emailList[] = $email;
627  }
628  }
629 
630  $notify = new ErrorMail;
631  $notify->mailfrom = $fromEmail;
632  $notify->mailfromname = $fromName;
633  $notify->subject = $subject;
634  $notify->htmlMsgbody = $body;
635  $notify->executeQuietly = true;
636  $notify->mailto = $emailList;
637  $notify->bulk = true;
638  $notify->hideto = true;
639  $notify->SendMail();
640 
641  $results = ChangeToLast();
642  if ($results["status"] !== "000") {
643  throw new exception ($results["error"], 3);
644  }
645 
646  // Add email to SES role to HOMECU if it's new.
647  if ($fromEmail != GetDefaultEmail()) {
648  $sql = "select email from cuadmnotify where cu = 'HOMECU' and role = 'SES'";
649  $sth = db_query($sql, $dbh);
650  if (!$sth) {
651  throw new exception ("Select query failed.", 4);
652  }
653  // For this, always assume that the email is verified.
654  if (db_num_rows($sth) <= 0) {
655  $mode = "create";
656  $verifiedEmails = array(array("email" => $fromEmail, "verified" => true));
657  } else {
658  $mode = "update";
659  $verifiedEmails = db_fetch_row($sth, 0)[0];
660  $verifiedEmails = isset($verifiedEmails) ? HCU_JsonDecode($verifiedEmails) : array();
661  $newEmailTest = trim(strtolower($fromEmail));
662  foreach ($verifiedEmails as $emailRec) {
663  if ($newEmailTest == trim(strtolower($emailRec["email"]))) {
664  $mode = "don't";
665  break;
666  }
667  }
668 
669  if ($mode != "don't") {
670  $verifiedEmails[] = array("email" => $fromEmail, "verified" => true);
671  }
672  }
673 
674  switch($mode) {
675  case "create":
676  $sql = "insert into cuadmnotify (cu, role, email) values ('HOMECU', 'SES', '" . prep_save(HCU_JsonEncode($verifiedEmails)) . "')";
677  $sth = db_query($sql, $dbh);
678  if (!$sth) {
679  throw new exception ("Insert query failed.", 5);
680  }
681  break;
682  case "update":
683  $sql = "update cuadmnotify set email = '" . prep_save(HCU_JsonEncode($verifiedEmails)) . "' where cu = 'HOMECU' and role = 'SES'";
684  $sth = db_query($sql, $dbh);
685  if (!$sth) {
686  throw new exception ("Update query failed.", 6);
687  }
688  }
689  }
690 
691  $returnArray = array("status" => "000", "error" => "", "action" => "send", "info" => "Emails were successfully sent.");
692  } catch (exception $e) {
693  $returnArray = array("status" => $e->getCode(), "error" => $e->getMessage(), "action" => "send");
694  }
695  return $returnArray;
696 }