1d996ef7ff28a452e3db6a69693b4d0c6efc0b0a
[SonOfLokstallBot.git] / common.php
1 <?php declare(strict_types=1);
2
3 require_once('vendor/autoload.php');
4 require_once(__DIR__ . '/config.php');
5
6 use Telegram\Bot\Api;
7
8 function getTelegram(): \Telegram\Bot\Api {
9 STATIC $tg;
10 return $tg = $tg ?? new \Telegram\Bot\Api(BOT_TOKEN);
11 }
12
13 function splitBill($amount) {
14 return floor($amount/2);
15 }
16
17 function identity($x) {
18 return $x;
19 }
20
21 const notEmpty = 'notEmpty';
22 function notEmpty($value) {
23 return !empty($value);
24 }
25
26 function getMessageSender($update) {
27 return PARTICIPANT_IDS[$update->get('message')->get('from')->get('id')];
28 }
29
30 function getMessageSenderDisplayName($update) {
31 return $update->get('message')->get('from')->get('first_name');
32 }
33
34 function canChatWith($update) {
35 return in_array($update->get('message')->get('from')->get('id'), array_keys(PARTICIPANT_IDS));
36 }
37
38 function debug($whatever) {
39 echo '<pre>';
40 print_r($whatever);
41 echo '</pre>';
42 }
43
44 function partition(int $numPartitions, $array) {
45 $partitionSize = (int)ceil(count($array) / $numPartitions);
46
47 return
48 filter(notEmpty)(
49 map(function($p) use ($array, $partitionSize) {
50 return array_slice($array, $p*$partitionSize, $partitionSize);
51 })(range(0, $numPartitions-1))
52 );
53 }
54
55 function getInbox($inbox) {
56 STATIC $inboxes;
57
58 if (!isset($inboxes[$inbox])) {
59 $inboxes[$inbox] = imap_open(
60 '{imap.gmail.com:993/debug/imap/ssl/novalidate-cert}' . $inbox,
61 EMAIL,
62 PASSWORD
63 );
64 }
65
66 return $inboxes[$inbox];
67 }
68
69 function getRules() {
70 STATIC $rules;
71 return $rules = $rules ?? require 'rules.php';
72 }
73
74 const getString = 'getString';
75 function getString($identifier, ...$vars) {
76 STATIC $strings;
77 $strings = $strings ?? require 'strings.php';
78
79 return isset($strings[$identifier]) ? sprintf($strings[$identifier], ...$vars) : "[[$identifier]]";
80 }
81
82 function formatDate($date) {
83 return $date->format(DATE_FORMAT);
84 }
85
86 function ssort($comparitor) {
87 return function($array) use ($comparitor) {
88 uasort($array, uncurry($comparitor));
89 return $array;
90 };
91 }
92
93 function uncurry($f) {
94 return function($a, $b) use ($f) {
95 return $f($a)($b);
96 };
97 }
98
99 const sendToGroupChat = 'sendToGroupChat';
100 function sendToGroupChat(string $message) {
101 return getTelegram()->sendMessage(['chat_id' => CHAT_ID, 'text' => $message]);
102 }
103
104 const generateReminderText = 'generateReminderText';
105 function generateReminderText($message) {
106 return getString('billreminder', REMIND_THRESHOLD, $message['service'], splitBill($message['amount']), formatDate($message['due']));
107 }
108
109 const generateNewBillText = 'generateNewBillText';
110 function generateNewBillText($message) {
111 return getString('newbill', $message['service'], splitBill($message['amount']), formatDate($message['due']));
112 }
113
114 const messageNeedsReminder = 'messageNeedsReminder';
115 function messageNeedsReminder($message) {
116 return $message['due']->diff(new DateTimeImmutable)->d == REMIND_THRESHOLD;
117 }
118
119 const lines = 'lines';
120 function lines(string $string): array {
121 return explode("\n", $string);
122 }
123
124 const glue = 'glue';
125 function glue(string $delim): callable {
126 return function(array $strings) use ($delim): string {
127 return implode($delim, $strings);
128 };
129 }
130
131 const unlines = 'unlines';
132 function unlines($lines) {
133 return implode("\n", $lines);
134 }
135
136 const ununlines = 'ununlines';
137 function ununlines($lines) {
138 return implode("\n\n", $lines);
139 }
140
141 const zipWith = 'zipWith';
142 function zipWith(callable $zipper, array $a, array $b) {
143 return array_map($zipper, $a, $b);
144 }
145
146 function field($field) {
147 return function($array) use ($field) {
148 return $array[$field];
149 };
150 }
151
152 const= '⬄';
153 function($a) {
154 return function($b) use ($a) {
155 return $a <=> $b;
156 };
157 }
158
159
160 function(...$fs) {
161 return function($arg) use ($fs) {
162 return array_reduce(array_reverse($fs), function($c, $f) {
163 return $f($c);
164 }, $arg);
165 };
166 }
167
168 function map($callable) {
169 return function($list) use ($callable) {
170 return array_map($callable, $list);
171 };
172 }
173
174 function aaray_column($column) {
175 return function($array) use ($column) {
176 return array_column($array, $column);
177 };
178 }
179
180 function aaray_slice($start) {
181 return function($length) use ($start) {
182 return function($array) use ($length, $start) {
183 return array_slice($array, $start, $length);
184 };
185 };
186 }
187
188 function filter($callable) {
189 return function($list) use ($callable) {
190 return array_filter($list, $callable);
191 };
192 }
193
194 function f∘(callable $f) {
195 return function(callable $g) use ($f) {
196 return function($arg) use($g, $f) {
197 return $f($g($arg));
198 };
199 };
200 }
201
202 functionf(callable $f) {
203 return function(callable $g) use ($f) {
204 return function($arg) use($g, $f) {
205 return $g($f($arg));
206 };
207 };
208 }
209
210 function($a, $b) {
211 return array_merge($a, $b);
212 }
213
214 function getSeason($monthNum) {
215 return ['summer', 'autumn', 'winter', 'spring'][floor(($monthNum)%12/3)];
216 }
217
218 function getMonthName($monthNum) {
219 return ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'][$monthNum-1];
220 }
221
222 function isStartOfSeason($monthNum, $dayNum) {
223 return ($monthNum)%3 == 0 && isStartOfMonth($dayNum);
224 }
225
226 function isStartOfMonth($dayNum) {
227 return $dayNum < 8;
228 }
229
230 function getTasksForTheSeason($season, $taskMatrix) {
231 return array_unique(
232 array_reduce(
233 $taskMatrix['annualy'][$season],
234 function($c, $v) {
235 return array_merge(
236 $c,
237 array_reduce($v, function($c, $v) {
238 return array_merge($c, is_array($v) ? $v : [$v]);
239 }, [])
240 );
241 },
242 []
243 )
244 );
245 }
246
247 function getTasksForTheMonth($monthNum, $taskMatrix) {
248 return array_merge(
249 $taskMatrix['monthly'],
250 $monthNum % 6 == 0 ? $taskMatrix['biannualy'] : [],
251 $monthNum % 3 == 0 ? $taskMatrix['quadriannualy'] : [],
252 array_filter(
253 $taskMatrix['annualy'][getSeason($monthNum)][getMonthName($monthNum)],
254 function($v) {
255 return !is_array($v);
256 }
257 )
258 );
259 }
260
261 // NB weeknum is 1-4 (the week of the month, not consistent with other things)
262 function getTasksForTheWeek($weekNum, $monthNum, $taskMatrix) {
263 return array_merge(
264 $weekNum % 2 == 0 ? $taskMatrix['bimonthly'] : [],
265 $taskMatrix['annualy'][getSeason($monthNum)][getMonthName($monthNum)]['weekly'] ?? [],
266 partition(4, getTasksForTheMonth($monthNum, $taskMatrix))[$weekNum]
267 );
268 }
269
270 function closest($n, $list) {
271 $a = array_filter($list, function($value) use ($n) {
272 return $value <= $n;
273 });
274
275 arsort($a);
276 return array_values($a)[0];
277 }
278
279 function getMessagesFromInbox($inbox, array $rules, $unseenOnly = true) {
280 return array_filter(
281 array_map(
282 function($rule, $service) use ($inbox, $unseenOnly) {
283 $emails = imap_search($inbox, ['SEEN ', 'UNSEEN '][$unseenOnly] . $rule['imapQuery'], SE_UID);
284
285 if(!$emails) {
286 return [];
287 }
288
289 $messageTransform = $rule['messageTransform'] ?? 'identity';
290 $dateTransform = $rule['dateTransform'] ?? 'identity';
291
292 $body = quoted_printable_decode(imap_fetchbody($inbox, $emails[0], '1', FT_UID));
293 preg_match($rule['regex'], $messageTransform($body), $matches);
294
295 return [
296 'service' => $service,
297 'id' => substr(md5($body), 0, 6),
298 'uid' => $emails[0],
299 'due' => new DateTimeImmutable($dateTransform($matches['due'])),
300 'amount' => $matches['amount']
301 ];
302 },
303 $rules,
304 array_keys($rules)
305 ),
306 function($e) {
307 return !!$e;
308 }
309 );
310 }