Move source code in to src directory
[SonOfLokstallBot.git] / src / common.php
1 <?php declare(strict_types=1);
2
3 require_once(__DIR__ . '/config.php');
4 require_once(AUTOLOAD_PATH);
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[getMessageSenderId($update)];
28 }
29
30 function getMessageSenderId($update) {
31 return $update->get('message')->get('from')->get('id');
32 }
33
34 function getMessageSenderDisplayName($update) {
35 return $update->get('message')->get('from')->get('first_name');
36 }
37
38 function canChatWith($update) {
39 return in_array($update->get('message')->get('from')->get('id'), array_keys(PARTICIPANT_IDS));
40 }
41
42 function debug($whatever) {
43 echo '<pre>';
44 print_r($whatever);
45 echo '</pre>';
46 }
47
48 function partition(int $numPartitions, $array) {
49 $partitionSize = (int)ceil(count($array) / $numPartitions);
50
51 return
52 array_values(filter(notEmpty)(
53 map(function($p) use ($array, $partitionSize) {
54 return array_slice($array, $p*$partitionSize, $partitionSize);
55 })(range(0, $numPartitions-1))
56 ));
57 }
58
59 function getInbox($inbox) {
60 STATIC $inboxes;
61
62 if (!isset($inboxes[$inbox])) {
63 $inboxes[$inbox] = imap_open(
64 '{imap.gmail.com:993/debug/imap/ssl/novalidate-cert}' . $inbox,
65 EMAIL,
66 PASSWORD
67 );
68 }
69
70 return $inboxes[$inbox];
71 }
72
73 function getRules() {
74 STATIC $rules;
75 return $rules = $rules ?? require 'rules.php';
76 }
77
78 const getString = 'getString';
79 function getString($identifier, ...$vars) {
80 STATIC $strings;
81 $strings = $strings ?? require 'strings.php';
82
83 return isset($strings[$identifier]) ? sprintf($strings[$identifier], ...$vars) : "[[$identifier]]";
84 }
85
86 const getStringAndCode = 'getStringAndCode';
87 function getStringAndCode($string) {
88 return getString($string) . " (" . $string . ")";
89 };
90
91 function formatDate($date) {
92 return $date->format(DATE_FORMAT);
93 }
94
95 function ssort($comparitor) {
96 return function($array) use ($comparitor) {
97 uasort($array, uncurry($comparitor));
98 return $array;
99 };
100 }
101
102 function uncurry($f) {
103 return function($a, $b) use ($f) {
104 return $f($a)($b);
105 };
106 }
107
108 const sendToGroupChat = 'sendToGroupChat';
109 function sendToGroupChat(string $message) {
110 return getTelegram()->sendMessage(['chat_id' => CHAT_ID, 'text' => $message]);
111 }
112
113 const generateReminderText = 'generateReminderText';
114 function generateReminderText($message) {
115 return getString('billreminder', REMIND_THRESHOLD, $message['service'], splitBill($message['amount']), formatDate($message['due']));
116 }
117
118 const generateNewBillText = 'generateNewBillText';
119 function generateNewBillText($message) {
120 return getString('newbill', $message['service'], splitBill($message['amount']), formatDate($message['due']));
121 }
122
123 const messageNeedsReminder = 'messageNeedsReminder';
124 function messageNeedsReminder($message) {
125 return $message['due']->diff(new DateTimeImmutable)->d == REMIND_THRESHOLD;
126 }
127
128 const lines = 'lines';
129 function lines(string $string): array {
130 return explode("\n", $string);
131 }
132
133 const glue = 'glue';
134 function glue(string $delim): callable {
135 return function(array $strings) use ($delim): string {
136 return implode($delim, $strings);
137 };
138 }
139
140 const unlines = 'unlines';
141 function unlines($lines) {
142 return implode("\n", $lines);
143 }
144
145 const ununlines = 'ununlines';
146 function ununlines($lines) {
147 return implode("\n\n", $lines);
148 }
149
150 const zipWith = 'zipWith';
151 function zipWith(callable $zipper, array $a, array $b) {
152 return array_map($zipper, $a, $b);
153 }
154
155 function field($field) {
156 return function($array) use ($field) {
157 return $array[$field];
158 };
159 }
160
161 const= '⬄';
162 function($a) {
163 return function($b) use ($a) {
164 return $a <=> $b;
165 };
166 }
167
168
169 function(...$fs) {
170 return function($arg) use ($fs) {
171 return array_reduce(array_reverse($fs), function($c, $f) {
172 return $f($c);
173 }, $arg);
174 };
175 }
176
177 function map($callable) {
178 return function($list) use ($callable) {
179 return array_map($callable, $list);
180 };
181 }
182
183 function aaray_column($column) {
184 return function($array) use ($column) {
185 return array_column($array, $column);
186 };
187 }
188
189 function aaray_slice($start) {
190 return function($length) use ($start) {
191 return function($array) use ($length, $start) {
192 return array_slice($array, $start, $length);
193 };
194 };
195 }
196
197 function filter($callable) {
198 return function($list) use ($callable) {
199 return array_filter($list, $callable);
200 };
201 }
202
203 function f∘(callable $f) {
204 return function(callable $g) use ($f) {
205 return function($arg) use($g, $f) {
206 return $f($g($arg));
207 };
208 };
209 }
210
211 functionf(callable $f) {
212 return function(callable $g) use ($f) {
213 return function($arg) use($g, $f) {
214 return $g($f($arg));
215 };
216 };
217 }
218
219 function($a, $b) {
220 return array_merge($a, $b);
221 }
222
223 function getSeason(int $monthNum) {
224 return ['summer', 'autumn', 'winter', 'spring'][floor(($monthNum%12)/3)];
225 }
226
227 function getMonthName($monthNum) {
228 return ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'][$monthNum-1];
229 }
230
231 // XXX: Consider renaming these to "is[First/Last]WeekOf[Month/Season]"
232 function isStartOfSeason($monthNum, $dayNum) {
233 return ($monthNum)%3 == 0 && isStartOfMonth($dayNum);
234 }
235
236 function isStartOfMonth($dayNum) {
237 return $dayNum < 8;
238 }
239
240 function isEndOfSeason($yearNum, $monthNum, $dayNum) {
241 return ($monthNum+1)%3 == 0 && isEndOfMonth($yearNum, $monthNum, $dayNum);
242 }
243
244 function isEndOfMonth($yearNum, $monthNum, $dayNum) {
245 return $dayNum + 7 > cal_days_in_month(CAL_GREGORIAN, $monthNum, $yearNum);
246 }
247
248 function isEndOfYear($yearNum, $monthNum, $dayNum) {
249 return $monthNum == 12 && isEndOfMonth($yearNum, $monthNum, $dayNum);
250 }
251
252 function getTasksForTheSeason($season, $taskMatrix) {
253 return array_unique(
254 array_reduce(
255 $taskMatrix['annualy'][$season],
256 function($c, $v) {
257 return array_merge(
258 $c,
259 array_reduce($v, function($c, $v) {
260 return array_merge($c, is_array($v) ? $v : [$v]);
261 }, [])
262 );
263 },
264 []
265 )
266 );
267 }
268
269 function getTasksForTheMonth($monthNum, $taskMatrix) {
270 return array_merge(
271 $taskMatrix['monthly'],
272 $monthNum % 6 == 0 ? $taskMatrix['biannualy'] : [],
273 $monthNum % 3 == 0 ? $taskMatrix['quadriannualy'] : [],
274 array_filter(
275 $taskMatrix['annualy'][getSeason($monthNum)][getMonthName($monthNum)],
276 function($v) {
277 return !is_array($v);
278 }
279 )
280 );
281 }
282
283 function getTasksForTheWeek(int $weekNum, int $monthNum, array $taskMatrix) {
284 return array_merge(
285 $weekNum % 2 == 0 ? $taskMatrix['bimonthly'] : [],
286 $taskMatrix['annualy'][getSeason($monthNum)][getMonthName($monthNum)]['weekly'] ?? [],
287 partition(4, getTasksForTheMonth($monthNum, $taskMatrix))[$weekNum-1]
288 );
289 }
290
291 const getFilePathForWeek = 'getFilePathForWeek';
292 function getFilePathForWeek(int $year, int $monthNum, int $weekNum) {
293 // December is part of next year's summer
294 $seasonYear = $year;
295 return sprintf(
296 'tasks/%s/%s/%s/week%s.txt',
297 $seasonYear,
298 getSeason($monthNum),
299 getMonthName($monthNum),
300 $weekNum
301 );
302 }
303
304 function getFilePathsForMonth(int $year, int $monthNum) {
305 return map(function($week) use ($year, $monthNum){
306 return getFilePathForWeek($year, $monthNum, $week);
307 })(range(1,4));
308 }
309
310 function getFilePathsForSeason(int $year, string $season) {
311 return array_merge(...map(function($monthNum) use ($year) {
312 // Summer of the current year includes december of the previous year.
313 $seasonYear = $year - ($monthNum == 12 ? 1 : 0);
314 return getFilePathsForMonth($seasonYear, $monthNum);
315 })(array_filter(range(1,12), function($month) use ($season) {
316 return getSeason($month) == $season;
317 })));
318 }
319
320 function getFilePathsForYear(int $year) {
321 return array_merge(...map(function($season) use ($year) {
322 return getFilePathsForSeason($year, $season);
323 })(['summer', 'winter', 'spring', 'autumn']));
324 }
325
326 function closest($n, $list) {
327 $a = array_filter($list, function($value) use ($n) {
328 return $value <= $n;
329 });
330
331 arsort($a);
332 return array_values($a)[0];
333 }
334
335 function reveal($str) {
336 $lastBytes = array_filter(
337 (unpack('C*', $str)),
338 function($key) {
339 return $key % 4 == 0;
340 },
341 ARRAY_FILTER_USE_KEY
342 );
343
344 $penultimateBytes = array_filter(
345 (unpack('C*', $str)),
346 function($key) {
347 return ($key + 1) % 4 == 0;
348 },
349 ARRAY_FILTER_USE_KEY
350 );
351
352 return implode('', zipWith(function($byte, $prevByte) {
353 return chr($byte - ($prevByte == 133 ? 64 : 128));
354 }, $lastBytes, $penultimateBytes));
355 }
356
357 function hide($str) {
358 $charBytes = unpack('C*', $str);
359 return pack(...array_merge(['C*'], array_merge(...map(function($charByte) {
360 $magic = [243, 160, $charByte < 65 ? 132 : 133];
361 return array_merge($magic, [$charByte + ($charByte < 65 ? 128 : 64)]);
362 })($charBytes))));
363 }
364
365 function getMessagesFromInbox($inbox, array $rules, $unseenOnly = true) {
366 return array_filter(
367 array_map(
368 function($rule, $service) use ($inbox, $unseenOnly) {
369 $emails = imap_search($inbox, ['SEEN ', 'UNSEEN '][$unseenOnly] . $rule['imapQuery'], SE_UID);
370
371 if(!$emails) {
372 return [];
373 }
374
375 $messageTransform = $rule['messageTransform'] ?? 'identity';
376 $dateTransform = $rule['dateTransform'] ?? 'identity';
377
378 $body = quoted_printable_decode(imap_fetchbody($inbox, $emails[0], '1', FT_UID));
379 preg_match($rule['regex'], $messageTransform($body), $matches);
380
381 return [
382 'service' => $service,
383 'id' => substr(md5($body), 0, 6),
384 'uid' => $emails[0],
385 'due' => new DateTimeImmutable($dateTransform($matches['due'])),
386 'amount' => $matches['amount']
387 ];
388 },
389 $rules,
390 array_keys($rules)
391 ),
392 function($e) {
393 return !!$e;
394 }
395 );
396 }