7b88a6700146889832598fe518b768cec644427e
[SonOfLokstallBot.git] / common.php
1 <?php declare(strict_types=1);
2
3 namespace Common;
4
5 require 'vendor/autoload.php';
6 require __DIR__ . '/config.php';
7
8 use Telegram\Bot\Api;
9 use DateTimeImmutable;
10
11 function getTelegram() {
12 STATIC $tg;
13 return $tg = $tg ?? new \Telegram\Bot\Api(BOT_TOKEN);
14 }
15
16 function splitBill($amount) {
17 return floor($amount/2);
18 }
19
20 function identity($x) {
21 return $x;
22 }
23
24 function getMessageSender($update) {
25 return PARTICIPANT_IDS[$update->get('message')->get('from')->get('id')];
26 }
27
28 function getMessageSenderDisplayName($update) {
29 return $update->get('message')->get('from')->get('first_name');
30 }
31
32 function canChatWith($update) {
33 return in_array($update->get('message')->get('from')->get('id'), array_keys(PARTICIPANT_IDS));
34 }
35
36 function debug($whatever) {
37 echo '<pre>';
38 print_r($whatever);
39 echo '</pre>';
40 }
41
42 function getInbox($inbox) {
43 STATIC $inboxes;
44
45 if (!isset($inboxes[$inbox])) {
46 $inboxes[$inbox] = imap_open(
47 '{imap.gmail.com:993/debug/imap/ssl/novalidate-cert}' . $inbox,
48 EMAIL,
49 PASSWORD
50 );
51 }
52
53 return $inboxes[$inbox];
54 }
55
56 function getMessagesFromInbox($inbox, array $rules, $unseenOnly = true) {
57 return array_filter(
58 array_map(
59 function($rule, $service) use ($inbox, $unseenOnly) {
60 $emails = imap_search($inbox, ['SEEN ', 'UNSEEN '][$unseenOnly] . $rule['imapQuery'], SE_UID);
61
62 if(!$emails) {
63 return [];
64 }
65
66 $body = imap_fetchbody($inbox, $emails[0], '1', FT_UID);
67 preg_match($rule['regex'], $rule['messageTransform']($body), $matches);
68
69 return [
70 'service' => $service,
71 'id' => substr(md5($body), 0, 6),
72 'uid' => $emails[0],
73 'telegramMessage' => $rule['telegramMessage'],
74 'due' => new DateTimeImmutable($rule['dateTransform']($matches['due'])),
75 'amount' => $matches['amount']
76 ];
77 },
78 $rules,
79 array_keys($rules)
80 ),
81 function($e) {
82 return !!$e;
83 }
84 );
85 }