Add constant for path to tasks files
[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 as TelegramAPI;
7 use Telegram\Bot\Objects\Update as TelegramUpdate;
8
9 final class Monday {
10 private $year;
11 private $month;
12 private $season;
13 private $weekNum;
14 private $dayNum;
15
16 public function __construct(
17 int $year,
18 int $month,
19 string $season,
20 int $weekNum,
21 int $dayNum
22 ) {
23 $this->year = $year;
24 $this->month = $month;
25 $this->season = $season;
26 $this->weekNum = $weekNum;
27 $this->dayNum = $dayNum;
28 }
29
30 public function __get($property) {
31 return $this->$property;
32 }
33 }
34
35 // Returns a the closest previous Monday given a date.
36 // weekNumber is 1-5 (mondays in months are considered the start of a week, so if a month has 5 mondays it has 5 weeks)
37 // dayNumber is the day of the month
38 function turnBackTime(DateTimeImmutable $date) {
39 $y = (int) $date->format('Y');
40 $m = (int) $date->format('n');
41 $d = (int) $date->format('d');
42 return new Monday(
43 getYearWeekBeginsIn($y, $m, $d),
44 getMonthWeekBeginsIn($y, $m, $d),
45 getSeason(getMonthWeekBeginsIn($y, $m, $d)),
46 getWeekNumber($y, $m, $d),
47 getDayNumber($y, $m, $d)
48 );
49 }
50
51 function getTelegram(): TelegramAPI {
52 STATIC $tg;
53 return $tg = $tg ?? new TelegramAPI(BOT_TOKEN);
54 }
55
56 function splitBill(float $amount) : float {
57 return floor($amount/2);
58 }
59
60 function identity($x) {
61 return $x;
62 }
63
64 const notEmpty = 'notEmpty';
65 function notEmpty($value) : bool {
66 return !empty($value);
67 }
68
69 function getMessageSender(TelegramUpdate $update) : string {
70 return PARTICIPANT_IDS[getMessageSenderId($update)];
71 }
72
73 function getMessageSenderId(TelegramUpdate $update) : int {
74 return $update->get('message')->get('from')->get('id');
75 }
76
77 function getMessageSenderDisplayName(TelegramUpdate $update) : string {
78 return $update->get('message')->get('from')->get('first_name');
79 }
80
81 function canChatWith(TelegramUpdate $update) : bool {
82 return in_array($update->get('message')->get('from')->get('id'), array_keys(PARTICIPANT_IDS));
83 }
84
85 function partition(int $numPartitions, array $array) : array {
86 $partitionSize = (int)ceil(count($array) / $numPartitions);
87
88 return array_values(
89 map(function($p) use ($array, $partitionSize) {
90 return array_slice($array, $p*$partitionSize, $partitionSize);
91 })(range(0, $numPartitions-1))
92 );
93 }
94
95 function getInbox(string $inbox) {
96 STATIC $inboxes;
97
98 if (!isset($inboxes[$inbox])) {
99 $inboxes[$inbox] = imap_open(
100 '{imap.gmail.com:993/debug/imap/ssl/novalidate-cert}' . $inbox,
101 EMAIL,
102 PASSWORD
103 );
104 }
105
106 return $inboxes[$inbox];
107 }
108
109 function getRules() {
110 STATIC $rules;
111 return $rules = $rules ?? require 'rules.php';
112 }
113
114 const getString = 'getString';
115 function getString($identifier, ...$vars) {
116 STATIC $strings;
117 $strings = $strings ?? require 'strings.php';
118
119 return isset($strings[$identifier]) ? sprintf($strings[$identifier], ...$vars) : "[[$identifier]]";
120 }
121
122 const getStringAndCode = 'getStringAndCode';
123 function getStringAndCode($string) {
124 return getString($string) . " (" . $string . ")";
125 };
126
127 function formatDate($date) {
128 return $date->format(DATE_FORMAT);
129 }
130
131 function ssort($comparitor) {
132 return function($array) use ($comparitor) {
133 uasort($array, uncurry($comparitor));
134 return $array;
135 };
136 }
137
138 function uncurry($f) {
139 return function($a, $b) use ($f) {
140 return $f($a)($b);
141 };
142 }
143
144 function between($content, $start){
145 $r = explode($start, $content);
146 if (isset($r[1])){
147 $r = explode($start, $r[1]);
148 return $r[0];
149 }
150 return '';
151 }
152
153 const sendToGroupChat = 'sendToGroupChat';
154 function sendToGroupChat(string $message) {
155 return getTelegram()->sendMessage(['chat_id' => CHAT_ID, 'text' => $message]);
156 }
157
158 const generateReminderText = 'generateReminderText';
159 function generateReminderText($message) {
160 return getString('billreminder', REMIND_THRESHOLD, $message['service'], splitBill($message['amount']), formatDate($message['due']));
161 }
162
163 const generateNewBillText = 'generateNewBillText';
164 function generateNewBillText($message) {
165 return getString('newbill', $message['service'], splitBill($message['amount']), formatDate($message['due']));
166 }
167
168 const messageNeedsReminder = 'messageNeedsReminder';
169 function messageNeedsReminder($message) {
170 return $message['due']->diff(new DateTimeImmutable)->d == REMIND_THRESHOLD;
171 }
172
173 const lines = 'lines';
174 function lines(string $string): array {
175 return explode("\n", $string);
176 }
177
178 const glue = 'glue';
179 function glue(string $delim): callable {
180 return function(array $strings) use ($delim): string {
181 return implode($delim, $strings);
182 };
183 }
184
185 const unlines = 'unlines';
186 function unlines($lines) {
187 return implode("\n", $lines);
188 }
189
190 const ununlines = 'ununlines';
191 function ununlines($lines) {
192 return implode("\n\n", $lines);
193 }
194
195 const zipWith = 'zipWith';
196 function zipWith(callable $zipper, array $a, array $b) {
197 return array_map($zipper, $a, $b);
198 }
199
200 function field($field) {
201 return function($array) use ($field) {
202 return $array[$field];
203 };
204 }
205
206 const ⬄ = '⬄';
207 function ⬄($a) {
208 return function($b) use ($a) {
209 return $a <=> $b;
210 };
211 }
212
213
214 function ∘(...$fs) {
215 return function($arg) use ($fs) {
216 return array_reduce(array_reverse($fs), function($c, $f) {
217 return $f($c);
218 }, $arg);
219 };
220 }
221
222 function map($callable) {
223 return function($list) use ($callable) {
224 return array_map($callable, $list);
225 };
226 }
227
228 function aaray_column($column) {
229 return function($array) use ($column) {
230 return array_column($array, $column);
231 };
232 }
233
234 function aaray_slice($start) {
235 return function($length) use ($start) {
236 return function($array) use ($length, $start) {
237 return array_slice($array, $start, $length);
238 };
239 };
240 }
241
242 function filter($callable) {
243 return function($list) use ($callable) {
244 return array_filter($list, $callable);
245 };
246 }
247
248 function f∘(callable $f) {
249 return function(callable $g) use ($f) {
250 return function($arg) use($g, $f) {
251 return $f($g($arg));
252 };
253 };
254 }
255
256 function ∘f(callable $f) {
257 return function(callable $g) use ($f) {
258 return function($arg) use($g, $f) {
259 return $g($f($arg));
260 };
261 };
262 }
263
264 function ∪($a, $b) {
265 return array_merge($a, $b);
266 }
267
268 function getSeason(int $monthNum) {
269 return ['summer', 'autumn', 'winter', 'spring'][(int)floor(($monthNum%12)/3)];
270 }
271
272 function getMonthName($monthNum) {
273 return ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'][$monthNum-1];
274 }
275
276 // XXX: Consider renaming these to "is[First/Last]WeekOf[Month/Season]"
277 function isStartOfSeason($monthNum, $dayNum) {
278 return ($monthNum)%3 == 0 && isStartOfMonth($dayNum);
279 }
280
281 function isStartOfMonth($dayNum) {
282 return $dayNum < 8;
283 }
284
285 function isEndOfSeason($yearNum, $monthNum, $dayNum) {
286 return ($monthNum+1)%3 == 0 && isEndOfMonth($yearNum, $monthNum, $dayNum);
287 }
288
289 function isEndOfMonth($yearNum, $monthNum, $dayNum) {
290 return $dayNum + 7 > cal_days_in_month(CAL_GREGORIAN, $monthNum, $yearNum);
291 }
292
293 function isEndOfYear($yearNum, $monthNum, $dayNum) {
294 return $monthNum == 12 && isEndOfMonth($yearNum, $monthNum, $dayNum);
295 }
296
297 function getTasksForTheSeason($season, $taskMatrix) {
298 return array_unique(
299 array_reduce(
300 $taskMatrix['annualy'][$season],
301 function($c, $v) {
302 return array_merge(
303 $c,
304 array_reduce($v, function($c, $v) {
305 return array_merge($c, is_array($v) ? [] : [$v]);
306 }, [])
307 );
308 },
309 []
310 )
311 );
312 }
313
314 function getTasksForTheMonth($monthNum, $taskMatrix) {
315 return array_merge(
316 $taskMatrix['monthly'],
317 $monthNum % 6 == 0 ? $taskMatrix['biannualy'] : [],
318 $monthNum % 3 == 0 ? $taskMatrix['quadriannualy'] : [],
319 array_filter(
320 $taskMatrix['annualy'][getSeason($monthNum)][getMonthName($monthNum)],
321 function($v) {
322 return !is_array($v);
323 }
324 )
325 );
326 }
327
328 function getTasksForTheWeek(int $year, int $monthNum, int $weekNum, array $taskMatrix) {
329 return array_merge(
330 $weekNum % 2 == 0 ? $taskMatrix['bimonthly'] : [],
331 $taskMatrix['annualy'][getSeason($monthNum)][getMonthName($monthNum)]['weekly'] ?? [],
332 partition(count(getMondaysForMonth($year, $monthNum)), getTasksForTheMonth($monthNum, $taskMatrix))[$weekNum-1]
333 );
334 }
335
336 const getFilePathForWeek = 'getFilePathForWeek';
337 function getFilePathForWeek(int $year, int $monthNum, int $weekNum, string $base) {
338 // December is part of next year's summer
339 $seasonYear = $year;
340 return sprintf(
341 '%s/tasks/%s/%s/%s/week%s.txt',
342 $base,
343 $seasonYear,
344 getSeason($monthNum),
345 getMonthName($monthNum),
346 $weekNum
347 );
348 }
349
350 function getMondaysForMonth(int $year, int $monthNum) {
351 $dt = DateTimeImmutable::createFromFormat('Y n', "$year $monthNum");
352 $m = $dt->format('F');
353 $y = $dt->format('Y');
354 $fifthMonday = (int)(new DateTimeImmutable("fifth monday of $m $y"))->format('d');
355 $mondays = [
356 (int)(new DateTimeImmutable("first monday of $m $y"))->format('d'),
357 (int)(new DateTimeImmutable("second monday of $m $y"))->format('d'),
358 (int)(new DateTimeImmutable("third monday of $m $y"))->format('d'),
359 (int)(new DateTimeImmutable("fourth monday of $m $y"))->format('d'),
360 ];
361
362 return array_merge(
363 $mondays,
364 $fifthMonday > $mondays[3] ? [$fifthMonday] : []
365 );
366 }
367
368 function getDayNumber(int $year, int $month, int $day) {
369 $potentialMondays = array_filter(
370 getMondaysForMonth($year, $month),
371 function($monday) use ($day) {
372 return $monday <= $day;
373 }
374 );
375
376 return $potentialMondays
377 ? closest($day, $potentialMondays)
378 : array_values(
379 array_slice(
380 getMondaysForMonth(
381 getYearWeekBeginsIn($year, $month, $day),
382 getMonthWeekBeginsIn($year, $month, $day)
383 ),
384 -1
385 )
386 )[0];
387 }
388
389 function getWeekNumber(int $year, int $month, int $day) {
390 $potentialMondays = array_filter(
391 getMondaysForMonth($year, $month),
392 function($monday) use ($day) {
393 return $monday <= $day;
394 }
395 );
396
397 return $potentialMondays
398 ? closestIndex($day, $potentialMondays) + 1
399 : count(
400 getMondaysForMonth(
401 getYearWeekBeginsIn($year, $month, $day),
402 getMonthWeekBeginsIn($year, $month, $day)
403 )
404 );
405 }
406
407 function getMonthWeekBeginsIn(int $year, int $month, int $day) {
408 return array_merge([12], range(1,11), [12])[
409 $month - ($day < getMondaysForMonth($year, $month)[0] ? 1 : 0)
410 ];
411 }
412
413 function getYearWeekBeginsIn(int $year, int $month, int $day) {
414 return $year - (int)($month == 1 && getMonthWeekBeginsIn($year, $month, $day) == 12);
415 }
416
417 function getFilePathsForMonth(int $year, int $monthNum, string $base) {
418 return map(function($week) use ($year, $monthNum, $base){
419 return getFilePathForWeek($year, $monthNum, $week, $base);
420 })(range(1, count(getMondaysForMonth($year, $monthNum))));
421 }
422
423 function getFilePathsForSeason(int $year, string $season, string $base) {
424 return array_merge(...map(function($monthNum) use ($year, $base) {
425 // Summer of the current year includes december of the previous year.
426 $seasonYear = $year - ($monthNum == 12 ? 1 : 0);
427 return getFilePathsForMonth($seasonYear, $monthNum, $base);
428 })(array_filter(range(1,12), function($month) use ($season) {
429 return getSeason($month) == $season;
430 })));
431 }
432
433 function getFilePathsForYear(int $year, string $base) {
434 return array_merge(...map(function($season) use ($year, $base) {
435 return getFilePathsForSeason($year, $season, $base);
436 })(['summer', 'winter', 'spring', 'autumn']));
437 }
438
439 function closestIndex(int $n, array $list) {
440 $a = map(function(int $v) use ($n) : int {
441 return abs($v - $n);
442 })
443 ($list);
444
445 asort($a);
446 return array_keys($a)[0];
447 }
448
449 function closest(int $n, array $list) : int {
450 return $list[closestIndex($n, $list)];
451 }
452
453 function reveal($str) {
454 $lastBytes = array_filter(
455 (unpack('C*', $str)),
456 function($key) {
457 return $key % 4 == 0;
458 },
459 ARRAY_FILTER_USE_KEY
460 );
461
462 $penultimateBytes = array_filter(
463 (unpack('C*', $str)),
464 function($key) {
465 return ($key + 1) % 4 ==
466 0;
467 },
468 ARRAY_FILTER_USE_KEY
469 );
470
471 return implode('', zipWith(function($byte, $prevByte) {
472 return chr($byte - ($prevByte == 133 ? 64 : 128));
473 }, $lastBytes, $penultimateBytes));
474 }
475
476 function hide($str) {
477 $charBytes = unpack('C*', $str);
478 return pack(...array_merge(['C*'], array_merge(...map(function($charByte) {
479 $magic = [243, 160, $charByte < 65 ? 132 : 133];
480 return array_merge($magic, [$charByte + ($charByte < 65 ? 128 : 64)]);
481 })($charBytes))));
482 }
483
484 function getMessagesFromInbox($inbox, array $rules, $unseenOnly = true) {
485 return array_filter(
486 array_map(
487 function($rule, $service) use ($inbox, $unseenOnly) {
488 $emails = imap_search($inbox, ['SEEN ', 'UNSEEN '][$unseenOnly] . $rule['imapQuery'], SE_UID);
489
490 if(!$emails) {
491 return [];
492 }
493
494 $messageTransform = $rule['messageTransform'] ?? 'identity';
495 $dateTransform = $rule['dateTransform'] ?? 'identity';
496
497 $body = quoted_printable_decode(imap_fetchbody($inbox, $emails[0], '1', FT_UID));
498 preg_match($rule['regex'], $messageTransform($body), $matches);
499
500 return [
501 'service' => $service,
502 'id' => substr(md5($body), 0, 6),
503 'uid' => $emails[0],
504 'due' => new DateTimeImmutable($dateTransform($matches['due'])),
505 'amount' => (float)$matches['amount']
506 ];
507 },
508 $rules,
509 array_keys($rules)
510 ),
511 function($e) {
512 return !!$e;
513 }
514 );
515 }