pushover.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 = $headers['X-Rspamd-Subject'];
  54. $priority = 0;
  55. $symbols_array = json_decode($headers['X-Rspamd-Symbols'], true);
  56. if (is_array($symbols_array)) {
  57. foreach ($symbols_array as $symbol) {
  58. if ($symbol['name'] == 'HAS_X_PRIO_ONE') {
  59. $priority = 1;
  60. break;
  61. }
  62. }
  63. }
  64. $sender_address = $json_body->header_from[0];
  65. $sender_name = '-';
  66. if (preg_match('/(?<name>.*?)<(?<address>.*?)>/i', $sender_address, $matches)) {
  67. $sender_address = $matches['address'];
  68. $sender_name = trim($matches['name'], '"\' ');
  69. }
  70. $to_address = $json_body->header_to[0];
  71. $to_name = '-';
  72. if (preg_match('/(?<name>.*?)<(?<address>.*?)>/i', $to_address, $matches)) {
  73. $to_address = $matches['address'];
  74. $to_name = trim($matches['name'], '"\' ');
  75. }
  76. $rcpt_final_mailboxes = array();
  77. // Loop through all rcpts
  78. foreach (json_decode($rcpts, true) as $rcpt) {
  79. // Remove tag
  80. $rcpt = preg_replace('/^(.*?)\+.*(@.*)$/', '$1$2', $rcpt);
  81. // Break rcpt into local part and domain part
  82. $parsed_rcpt = parse_email($rcpt);
  83. // Skip if not a mailcow handled domain
  84. try {
  85. if (!$redis->hGet('DOMAIN_MAP', $parsed_rcpt['domain'])) {
  86. continue;
  87. }
  88. }
  89. catch (RedisException $e) {
  90. error_log("NOTIFY: " . $e . PHP_EOL);
  91. http_response_code(504);
  92. exit;
  93. }
  94. // Always assume rcpt is not a final mailbox but an alias for a mailbox or further aliases
  95. //
  96. // rcpt
  97. // |
  98. // mailbox <-- goto ---> alias1, alias2, mailbox2
  99. // | |
  100. // mailbox3 |
  101. // |
  102. // alias3 ---> mailbox4
  103. //
  104. try {
  105. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :rcpt AND `active` = '1'");
  106. $stmt->execute(array(
  107. ':rcpt' => $rcpt
  108. ));
  109. $gotos = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  110. if (empty($gotos)) {
  111. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :rcpt AND `active` = '1'");
  112. $stmt->execute(array(
  113. ':rcpt' => '@' . $parsed_rcpt['domain']
  114. ));
  115. $gotos = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  116. }
  117. if (empty($gotos)) {
  118. $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :rcpt AND `active` = '1'");
  119. $stmt->execute(array(':rcpt' => $parsed_rcpt['domain']));
  120. $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain'];
  121. if ($goto_branch) {
  122. $gotos = $parsed_rcpt['local'] . '@' . $goto_branch;
  123. }
  124. }
  125. $gotos_array = explode(',', $gotos);
  126. $loop_c = 0;
  127. while (count($gotos_array) != 0 && $loop_c <= 20) {
  128. // Loop through all found gotos
  129. foreach ($gotos_array as $index => &$goto) {
  130. error_log("RCPT RESOVLER: http pipe: query " . $goto . " as username from mailbox" . PHP_EOL);
  131. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :goto AND (`active`= '1' OR `active`= '2');");
  132. $stmt->execute(array(':goto' => $goto));
  133. $username = $stmt->fetch(PDO::FETCH_ASSOC)['username'];
  134. if (!empty($username)) {
  135. error_log("RCPT RESOVLER: http pipe: mailbox found: " . $username . PHP_EOL);
  136. // Current goto is a mailbox, save to rcpt_final_mailboxes if not a duplicate
  137. if (!in_array($username, $rcpt_final_mailboxes)) {
  138. $rcpt_final_mailboxes[] = $username;
  139. }
  140. }
  141. else {
  142. $parsed_goto = parse_email($goto);
  143. if (!$redis->hGet('DOMAIN_MAP', $parsed_goto['domain'])) {
  144. error_log("RCPT RESOVLER:" . $goto . " is not a mailcow handled mailbox or alias address" . PHP_EOL);
  145. }
  146. else {
  147. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :goto AND `active` = '1'");
  148. $stmt->execute(array(':goto' => $goto));
  149. $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  150. if ($goto_branch) {
  151. error_log("RCPT RESOVLER: http pipe: goto address " . $goto . " is an alias branch for " . $goto_branch . PHP_EOL);
  152. $goto_branch_array = explode(',', $goto_branch);
  153. } else {
  154. $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain AND `active` AND '1'");
  155. $stmt->execute(array(':domain' => $parsed_goto['domain']));
  156. $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain'];
  157. if ($goto_branch) {
  158. error_log("RCPT RESOVLER: http pipe: goto domain " . $parsed_goto['domain'] . " is a domain alias branch for " . $goto_branch . PHP_EOL);
  159. $goto_branch_array = array($parsed_goto['local'] . '@' . $goto_branch);
  160. }
  161. }
  162. }
  163. }
  164. // goto item was processed, unset
  165. unset($gotos_array[$index]);
  166. }
  167. // Merge goto branch array derived from previous loop (if any), filter duplicates and unset goto branch array
  168. if (!empty($goto_branch_array)) {
  169. $gotos_array = array_unique(array_merge($gotos_array, $goto_branch_array));
  170. unset($goto_branch_array);
  171. }
  172. // Reindex array
  173. $gotos_array = array_values($gotos_array);
  174. // Force exit if loop cannot be solved
  175. // Postfix does not allow for alias loops, so this should never happen.
  176. $loop_c++;
  177. error_log("RCPT RESOVLER: http pipe: goto array count on loop #". $loop_c . " is " . count($gotos_array) . PHP_EOL);
  178. }
  179. }
  180. catch (PDOException $e) {
  181. error_log("RCPT RESOVLER: " . $e->getMessage() . PHP_EOL);
  182. http_response_code(502);
  183. exit;
  184. }
  185. }
  186. foreach ($rcpt_final_mailboxes as $rcpt_final) {
  187. error_log("NOTIFY: pushover pipe: processing pushover message for rcpt " . $rcpt_final . PHP_EOL);
  188. $stmt = $pdo->prepare("SELECT * FROM `pushover`
  189. WHERE `username` = :username AND `active` = '1'");
  190. $stmt->execute(array(
  191. ':username' => $rcpt_final
  192. ));
  193. $api_data = $stmt->fetch(PDO::FETCH_ASSOC);
  194. if (isset($api_data['key']) && isset($api_data['token'])) {
  195. $title = (!empty($api_data['title'])) ? $api_data['title'] : 'Mail';
  196. $text = (!empty($api_data['text'])) ? $api_data['text'] : 'You\'ve got mail 📧';
  197. $attributes = json_decode($api_data['attributes'], true);
  198. $senders = explode(',', $api_data['senders']);
  199. $senders = array_filter($senders);
  200. $senders_regex = $api_data['senders_regex'];
  201. $sender_validated = false;
  202. if (empty($senders) && empty($senders_regex)) {
  203. $sender_validated = true;
  204. }
  205. else {
  206. if (!empty($senders)) {
  207. if (in_array($sender, $senders)) {
  208. $sender_validated = true;
  209. }
  210. }
  211. if (!empty($senders_regex) && $sender_validated !== true) {
  212. if (preg_match($senders_regex, $sender)) {
  213. $sender_validated = true;
  214. }
  215. }
  216. }
  217. if ($sender_validated === false) {
  218. error_log("NOTIFY: pushover pipe: skipping unwanted sender " . $sender);
  219. continue;
  220. }
  221. if ($attributes['only_x_prio'] == "1" && $priority == 0) {
  222. error_log("NOTIFY: pushover pipe: mail has no X-Priority: 1 header, skipping");
  223. continue;
  224. }
  225. $post_fields = array(
  226. "token" => $api_data['token'],
  227. "user" => $api_data['key'],
  228. "title" => sprintf("%s", str_replace(
  229. array('{SUBJECT}', '{SENDER}', '{SENDER_NAME}', '{SENDER_ADDRESS}', '{TO_NAME}', '{TO_ADDRESS}'),
  230. array($subject, $sender, $sender_name, $sender_address, $to_name, $to_address), $title)
  231. ),
  232. "priority" => $priority,
  233. "message" => sprintf("%s", str_replace(
  234. array('{SUBJECT}', '{SENDER}', '{SENDER_NAME}', '{SENDER_ADDRESS}', '{TO_NAME}', '{TO_ADDRESS}', '\n'),
  235. array($subject, $sender, $sender_name, $sender_address, $to_name, $to_address, PHP_EOL), $text)
  236. ),
  237. "sound" => $attributes['sound'] ?? "pushover"
  238. );
  239. if ($attributes['evaluate_x_prio'] == "1" && $priority == 1) {
  240. $post_fields['expire'] = 600;
  241. $post_fields['retry'] = 120;
  242. $post_fields['priority'] = 2;
  243. }
  244. curl_setopt_array($ch = curl_init(), array(
  245. CURLOPT_URL => "https://api.pushover.net/1/messages.json",
  246. CURLOPT_POSTFIELDS => $post_fields,
  247. CURLOPT_SAFE_UPLOAD => true,
  248. CURLOPT_RETURNTRANSFER => true,
  249. ));
  250. $result = curl_exec($ch);
  251. $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  252. curl_close($ch);
  253. error_log("NOTIFY: result: " . $httpcode . PHP_EOL);
  254. }
  255. }