pushover.php 9.3 KB

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