pushover.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. <?php
  2. // File size is limited by Nginx site to 10M
  3. // To speed things up, we do not include prerequisites
  4. header('Content-Type: text/plain');
  5. require_once "vars.inc.php";
  6. // Do not show errors, we log to using error_log
  7. ini_set('error_reporting', 0);
  8. // Init database
  9. //$dsn = $database_type . ':host=' . $database_host . ';dbname=' . $database_name;
  10. $dsn = $database_type . ":unix_socket=" . $database_sock . ";dbname=" . $database_name;
  11. $opt = [
  12. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  13. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  14. PDO::ATTR_EMULATE_PREPARES => false,
  15. ];
  16. try {
  17. $pdo = new PDO($dsn, $database_user, $database_pass, $opt);
  18. }
  19. catch (PDOException $e) {
  20. error_log("NOTIFY: " . $e . PHP_EOL);
  21. http_response_code(501);
  22. exit;
  23. }
  24. // Init Redis
  25. $redis = new Redis();
  26. $redis->connect('redis-mailcow', 6379);
  27. // Functions
  28. function parse_email($email) {
  29. if(!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
  30. $a = strrpos($email, '@');
  31. return array('local' => substr($email, 0, $a), 'domain' => substr(substr($email, $a), 1));
  32. }
  33. if (!function_exists('getallheaders')) {
  34. function getallheaders() {
  35. if (!is_array($_SERVER)) {
  36. return array();
  37. }
  38. $headers = array();
  39. foreach ($_SERVER as $name => $value) {
  40. if (substr($name, 0, 5) == 'HTTP_') {
  41. $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
  42. }
  43. }
  44. return $headers;
  45. }
  46. }
  47. $headers = getallheaders();
  48. $json_body = json_decode(file_get_contents('php://input'));
  49. $qid = $headers['X-Rspamd-Qid'];
  50. $rcpts = $headers['X-Rspamd-Rcpt'];
  51. $sender = $headers['X-Rspamd-From'];
  52. $ip = $headers['X-Rspamd-Ip'];
  53. $subject = iconv_mime_decode($headers['X-Rspamd-Subject']);
  54. $messageid= $json_body->message_id;
  55. $priority = 0;
  56. $symbols_array = json_decode($headers['X-Rspamd-Symbols'], true);
  57. if (is_array($symbols_array)) {
  58. foreach ($symbols_array as $symbol) {
  59. if ($symbol['name'] == 'HAS_X_PRIO_ONE') {
  60. $priority = 1;
  61. break;
  62. }
  63. }
  64. }
  65. $sender_address = $json_body->header_from[0];
  66. $sender_name = '-';
  67. if (preg_match('/(?<name>.*?)<(?<address>.*?)>/i', $sender_address, $matches)) {
  68. $sender_address = $matches['address'];
  69. $sender_name = trim($matches['name'], '"\' ');
  70. }
  71. $to_address = $json_body->header_to[0];
  72. $to_name = '-';
  73. if (preg_match('/(?<name>.*?)<(?<address>.*?)>/i', $to_address, $matches)) {
  74. $to_address = $matches['address'];
  75. $to_name = trim($matches['name'], '"\' ');
  76. }
  77. $rcpt_final_mailboxes = array();
  78. // Loop through all rcpts
  79. foreach (json_decode($rcpts, true) as $rcpt) {
  80. // Remove tag
  81. $rcpt = preg_replace('/^(.*?)\+.*(@.*)$/', '$1$2', $rcpt);
  82. // Break rcpt into local part and domain part
  83. $parsed_rcpt = parse_email($rcpt);
  84. // Skip if not a mailcow handled domain
  85. try {
  86. if (!$redis->hGet('DOMAIN_MAP', $parsed_rcpt['domain'])) {
  87. continue;
  88. }
  89. }
  90. catch (RedisException $e) {
  91. error_log("NOTIFY: " . $e . PHP_EOL);
  92. http_response_code(504);
  93. exit;
  94. }
  95. // Always assume rcpt is not a final mailbox but an alias for a mailbox or further aliases
  96. //
  97. // rcpt
  98. // |
  99. // mailbox <-- goto ---> alias1, alias2, mailbox2
  100. // | |
  101. // mailbox3 |
  102. // |
  103. // alias3 ---> mailbox4
  104. //
  105. try {
  106. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :rcpt AND `active` = '1'");
  107. $stmt->execute(array(
  108. ':rcpt' => $rcpt
  109. ));
  110. $gotos = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  111. if (empty($gotos)) {
  112. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :rcpt AND `active` = '1'");
  113. $stmt->execute(array(
  114. ':rcpt' => '@' . $parsed_rcpt['domain']
  115. ));
  116. $gotos = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  117. }
  118. if (empty($gotos)) {
  119. $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :rcpt AND `active` = '1'");
  120. $stmt->execute(array(':rcpt' => $parsed_rcpt['domain']));
  121. $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain'];
  122. if ($goto_branch) {
  123. $gotos = $parsed_rcpt['local'] . '@' . $goto_branch;
  124. }
  125. }
  126. $gotos_array = explode(',', $gotos);
  127. $loop_c = 0;
  128. while (count($gotos_array) != 0 && $loop_c <= 20) {
  129. // Loop through all found gotos
  130. foreach ($gotos_array as $index => &$goto) {
  131. error_log("RCPT RESOVLER: http pipe: query " . $goto . " as username from mailbox" . PHP_EOL);
  132. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :goto AND (`active`= '1' OR `active`= '2');");
  133. $stmt->execute(array(':goto' => $goto));
  134. $username = $stmt->fetch(PDO::FETCH_ASSOC)['username'];
  135. if (!empty($username)) {
  136. error_log("RCPT RESOVLER: http pipe: mailbox found: " . $username . PHP_EOL);
  137. // Current goto is a mailbox, save to rcpt_final_mailboxes if not a duplicate
  138. if (!in_array($username, $rcpt_final_mailboxes)) {
  139. $rcpt_final_mailboxes[] = $username;
  140. }
  141. }
  142. else {
  143. $parsed_goto = parse_email($goto);
  144. if (!$redis->hGet('DOMAIN_MAP', $parsed_goto['domain'])) {
  145. error_log("RCPT RESOVLER:" . $goto . " is not a mailcow handled mailbox or alias address" . PHP_EOL);
  146. }
  147. else {
  148. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :goto AND `active` = '1'");
  149. $stmt->execute(array(':goto' => $goto));
  150. $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  151. if ($goto_branch) {
  152. error_log("RCPT RESOVLER: http pipe: goto address " . $goto . " is an alias branch for " . $goto_branch . PHP_EOL);
  153. $goto_branch_array = explode(',', $goto_branch);
  154. } else {
  155. $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain AND `active` AND '1'");
  156. $stmt->execute(array(':domain' => $parsed_goto['domain']));
  157. $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain'];
  158. if ($goto_branch) {
  159. error_log("RCPT RESOVLER: http pipe: goto domain " . $parsed_goto['domain'] . " is a domain alias branch for " . $goto_branch . PHP_EOL);
  160. $goto_branch_array = array($parsed_goto['local'] . '@' . $goto_branch);
  161. }
  162. }
  163. }
  164. }
  165. // goto item was processed, unset
  166. unset($gotos_array[$index]);
  167. }
  168. // Merge goto branch array derived from previous loop (if any), filter duplicates and unset goto branch array
  169. if (!empty($goto_branch_array)) {
  170. $gotos_array = array_unique(array_merge($gotos_array, $goto_branch_array));
  171. unset($goto_branch_array);
  172. }
  173. // Reindex array
  174. $gotos_array = array_values($gotos_array);
  175. // Force exit if loop cannot be solved
  176. // Postfix does not allow for alias loops, so this should never happen.
  177. $loop_c++;
  178. error_log("RCPT RESOVLER: http pipe: goto array count on loop #". $loop_c . " is " . count($gotos_array) . PHP_EOL);
  179. }
  180. }
  181. catch (PDOException $e) {
  182. error_log("RCPT RESOVLER: " . $e->getMessage() . PHP_EOL);
  183. http_response_code(502);
  184. exit;
  185. }
  186. }
  187. foreach ($rcpt_final_mailboxes as $rcpt_final) {
  188. error_log("NOTIFY: pushover pipe: processing pushover message for rcpt " . $rcpt_final . PHP_EOL);
  189. $stmt = $pdo->prepare("SELECT * FROM `pushover`
  190. WHERE `username` = :username AND `active` = '1'");
  191. $stmt->execute(array(
  192. ':username' => $rcpt_final
  193. ));
  194. $api_data = $stmt->fetch(PDO::FETCH_ASSOC);
  195. if (isset($api_data['key']) && isset($api_data['token'])) {
  196. $title = (!empty($api_data['title'])) ? $api_data['title'] : 'Mail';
  197. $text = (!empty($api_data['text'])) ? $api_data['text'] : 'You\'ve got mail 📧';
  198. $attributes = json_decode($api_data['attributes'], true);
  199. $senders = explode(',', $api_data['senders']);
  200. $senders = array_filter($senders);
  201. $senders_regex = $api_data['senders_regex'];
  202. $sender_validated = false;
  203. if (empty($senders) && empty($senders_regex)) {
  204. $sender_validated = true;
  205. }
  206. else {
  207. if (!empty($senders)) {
  208. if (in_array($sender, $senders)) {
  209. $sender_validated = true;
  210. }
  211. }
  212. if (!empty($senders_regex) && $sender_validated !== true) {
  213. if (preg_match($senders_regex, $sender)) {
  214. $sender_validated = true;
  215. }
  216. }
  217. }
  218. if ($sender_validated === false) {
  219. error_log("NOTIFY: pushover pipe: skipping unwanted sender " . $sender);
  220. continue;
  221. }
  222. if ($attributes['only_x_prio'] == "1" && $priority == 0) {
  223. error_log("NOTIFY: pushover pipe: mail has no X-Priority: 1 header, skipping");
  224. continue;
  225. }
  226. $post_fields = array(
  227. "token" => $api_data['token'],
  228. "user" => $api_data['key'],
  229. "title" => sprintf("%s", str_replace(
  230. array('{SUBJECT}', '{SENDER}', '{SENDER_NAME}', '{SENDER_ADDRESS}', '{TO_NAME}', '{TO_ADDRESS}', '{MSG_ID}'),
  231. array($subject, $sender, $sender_name, $sender_address, $to_name, $to_address, $messageid), $title)
  232. ),
  233. "priority" => $priority,
  234. "message" => sprintf("%s", str_replace(
  235. array('{SUBJECT}', '{SENDER}', '{SENDER_NAME}', '{SENDER_ADDRESS}', '{TO_NAME}', '{TO_ADDRESS}', '{MSG_ID}', '\n'),
  236. array($subject, $sender, $sender_name, $sender_address, $to_name, $to_address, $messageid, PHP_EOL), $text)
  237. ),
  238. "sound" => $attributes['sound'] ?? "pushover"
  239. );
  240. if ($attributes['evaluate_x_prio'] == "1" && $priority == 1) {
  241. $post_fields['expire'] = 600;
  242. $post_fields['retry'] = 120;
  243. $post_fields['priority'] = 2;
  244. }
  245. curl_setopt_array($ch = curl_init(), array(
  246. CURLOPT_URL => "https://api.pushover.net/1/messages.json",
  247. CURLOPT_POSTFIELDS => $post_fields,
  248. CURLOPT_SAFE_UPLOAD => true,
  249. CURLOPT_RETURNTRANSFER => true,
  250. ));
  251. $result = curl_exec($ch);
  252. $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  253. curl_close($ch);
  254. error_log("NOTIFY: result: " . $httpcode . PHP_EOL);
  255. }
  256. }