1 <?php
declare(strict_types
=1);
3 require_once('vendor/autoload.php');
4 require_once(__DIR__
. '/config.php');
8 function getTelegram(): \Telegram\Bot\Api
{
10 return $tg = $tg ??
new \Telegram\Bot\
Api(BOT_TOKEN
);
13 function splitBill($amount) {
14 return floor($amount/2);
17 function identity($x) {
21 const notEmpty
= 'notEmpty';
22 function notEmpty($value) {
23 return !empty($value);
26 function getMessageSender($update) {
27 return PARTICIPANT_IDS
[$update->get('message')->get('from')->get('id')];
30 function getMessageSenderDisplayName($update) {
31 return $update->get('message')->get('from')->get('first_name');
34 function canChatWith($update) {
35 return in_array($update->get('message')->get('from')->get('id'), array_keys(PARTICIPANT_IDS
));
38 function debug($whatever) {
44 function partition(int $numPartitions, $array) {
45 $partitionSize = (int)ceil(count($array) / $numPartitions);
48 array_values(filter(notEmpty
)(
49 map(function($p) use ($array, $partitionSize) {
50 return array_slice($array, $p*$partitionSize, $partitionSize);
51 })(range(0, $numPartitions-1))
55 function getInbox($inbox) {
58 if (!isset($inboxes[$inbox])) {
59 $inboxes[$inbox] = imap_open(
60 '{imap.gmail.com:993/debug/imap/ssl/novalidate-cert}' . $inbox,
66 return $inboxes[$inbox];
71 return $rules = $rules ??
require 'rules.php';
74 const getString
= 'getString';
75 function getString($identifier, ...$vars) {
77 $strings = $strings ??
require 'strings.php';
79 return isset($strings[$identifier]) ?
sprintf($strings[$identifier], ...$vars) : "[[$identifier]]";
82 const getStringAndCode
= 'getStringAndCode';
83 function getStringAndCode($string) {
84 return getString($string) . " (" . $string . ")";
87 function formatDate($date) {
88 return $date->format(DATE_FORMAT
);
91 function ssort($comparitor) {
92 return function($array) use ($comparitor) {
93 uasort($array, uncurry($comparitor));
98 function uncurry($f) {
99 return function($a, $b) use ($f) {
104 const sendToGroupChat
= 'sendToGroupChat';
105 function sendToGroupChat(string $message) {
106 return getTelegram()->sendMessage(['chat_id' => CHAT_ID
, 'text' => $message]);
109 const generateReminderText
= 'generateReminderText';
110 function generateReminderText($message) {
111 return getString('billreminder', REMIND_THRESHOLD
, $message['service'], splitBill($message['amount']), formatDate($message['due']));
114 const generateNewBillText
= 'generateNewBillText';
115 function generateNewBillText($message) {
116 return getString('newbill', $message['service'], splitBill($message['amount']), formatDate($message['due']));
119 const messageNeedsReminder
= 'messageNeedsReminder';
120 function messageNeedsReminder($message) {
121 return $message['due']->diff(new DateTimeImmutable
)->d
== REMIND_THRESHOLD
;
124 const lines
= 'lines';
125 function lines(string $string): array {
126 return explode("\n", $string);
130 function glue(string $delim): callable
{
131 return function(array $strings) use ($delim): string {
132 return implode($delim, $strings);
136 const unlines
= 'unlines';
137 function unlines($lines) {
138 return implode("\n", $lines);
141 const ununlines
= 'ununlines';
142 function ununlines($lines) {
143 return implode("\n\n", $lines);
146 const zipWith
= 'zipWith';
147 function zipWith(callable
$zipper, array $a, array $b) {
148 return array_map($zipper, $a, $b);
151 function field($field) {
152 return function($array) use ($field) {
153 return $array[$field];
159 return function($b) use ($a) {
166 return function($arg) use ($fs) {
167 return array_reduce(array_reverse($fs), function($c, $f) {
173 function map($callable) {
174 return function($list) use ($callable) {
175 return array_map($callable, $list);
179 function aaray_column($column) {
180 return function($array) use ($column) {
181 return array_column($array, $column);
185 function aaray_slice($start) {
186 return function($length) use ($start) {
187 return function($array) use ($length, $start) {
188 return array_slice($array, $start, $length);
193 function filter($callable) {
194 return function($list) use ($callable) {
195 return array_filter($list, $callable);
199 function f∘
(callable
$f) {
200 return function(callable
$g) use ($f) {
201 return function($arg) use($g, $f) {
207 function ∘
f(callable
$f) {
208 return function(callable
$g) use ($f) {
209 return function($arg) use($g, $f) {
216 return array_merge($a, $b);
219 function getSeason(int $monthNum) {
220 return ['summer', 'autumn', 'winter', 'spring'][floor(($monthNum%12
)/3)];
223 function getMonthName($monthNum) {
224 return ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'][$monthNum-1];
227 // XXX: Consider renaming these to "is[First/Last]WeekOf[Month/Season]"
228 function isStartOfSeason($monthNum, $dayNum) {
229 return ($monthNum)%3
== 0 && isStartOfMonth($dayNum);
232 function isStartOfMonth($dayNum) {
236 function isEndOfSeason($yearNum, $monthNum, $dayNum) {
237 return ($monthNum+
1)%3
== 0 && isEndOfMonth($yearNum, $monthNum, $dayNum);
240 function isEndOfMonth($yearNum, $monthNum, $dayNum) {
241 return $dayNum +
7 > cal_days_in_month(CAL_GREGORIAN
, $monthNum, $yearNum);
244 function isEndOfYear($yearNum, $monthNum, $dayNum) {
245 return $monthNum == 12 && isEndOfMonth($yearNum, $monthNum, $dayNum);
248 function getTasksForTheSeason($season, $taskMatrix) {
251 $taskMatrix['annualy'][$season],
255 array_reduce($v, function($c, $v) {
256 return array_merge($c, is_array($v) ?
$v : [$v]);
265 function getTasksForTheMonth($monthNum, $taskMatrix) {
267 $taskMatrix['monthly'],
268 $monthNum %
6 == 0 ?
$taskMatrix['biannualy'] : [],
269 $monthNum %
3 == 0 ?
$taskMatrix['quadriannualy'] : [],
271 $taskMatrix['annualy'][getSeason($monthNum)][getMonthName($monthNum)],
273 return !is_array($v);
279 function getTasksForTheWeek(int $weekNum, int $monthNum, array $taskMatrix) {
281 $weekNum %
2 == 0 ?
$taskMatrix['bimonthly'] : [],
282 $taskMatrix['annualy'][getSeason($monthNum)][getMonthName($monthNum)]['weekly'] ??
[],
283 partition(4, getTasksForTheMonth($monthNum, $taskMatrix))[$weekNum-1]
287 const getFilePathForWeek
= 'getFilePathForWeek';
288 function getFilePathForWeek(int $year, int $monthNum, int $weekNum) {
289 // December is part of next year's summer
292 'tasks/%s/%s/%s/week%s.txt',
294 getSeason($monthNum),
295 getMonthName($monthNum),
300 function getFilePathsForMonth(int $year, int $monthNum) {
301 return map(function($week) use ($year, $monthNum){
302 return getFilePathForWeek($year, $monthNum, $week);
306 function getFilePathsForSeason(int $year, string $season) {
307 return array_merge(...map(function($monthNum) use ($year) {
308 // Summer of the current year includes december of the previous year.
309 $seasonYear = $year - ($monthNum == 12 ?
1 : 0);
310 return getFilePathsForMonth($seasonYear, $monthNum);
311 })(array_filter(range(1,12), function($month) use ($season) {
312 return getSeason($month) == $season;
316 function getFilePathsForYear(int $year) {
317 return array_merge(...map(function($season) use ($year) {
318 return getFilePathsForSeason($year, $season);
319 })(['summer', 'winter', 'spring', 'autumn']));
322 function closest($n, $list) {
323 $a = array_filter($list, function($value) use ($n) {
328 return array_values($a)[0];
331 function reveal($str) {
332 $lastBytes = array_filter(
333 (unpack('C*', $str)),
335 return $key %
4 == 0;
340 $penultimateBytes = array_filter(
341 (unpack('C*', $str)),
343 return ($key +
1) %
4 == 0;
348 return implode('', zipWith(function($byte, $prevByte) {
349 return chr($byte - ($prevByte == 133 ?
64 : 128));
350 }, $lastBytes, $penultimateBytes));
353 function hide($str) {
354 $charBytes = unpack('C*', $str);
355 return pack(...array_merge(['C*'], array_merge(...map(function($charByte) {
356 $magic = [243, 160, $charByte < 65 ?
132 : 133];
357 return array_merge($magic, [$charByte +
($charByte < 65 ?
128 : 64)]);
361 function getMessagesFromInbox($inbox, array $rules, $unseenOnly = true
) {
364 function($rule, $service) use ($inbox, $unseenOnly) {
365 $emails = imap_search($inbox, ['SEEN ', 'UNSEEN '][$unseenOnly] . $rule['imapQuery'], SE_UID
);
371 $messageTransform = $rule['messageTransform'] ??
'identity';
372 $dateTransform = $rule['dateTransform'] ??
'identity';
374 $body = quoted_printable_decode(imap_fetchbody($inbox, $emails[0], '1', FT_UID
));
375 preg_match($rule['regex'], $messageTransform($body), $matches);
378 'service' => $service,
379 'id' => substr(md5($body), 0, 6),
381 'due' => new DateTimeImmutable($dateTransform($matches['due'])),
382 'amount' => $matches['amount']