pushover.php 10 KB

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