1 <?php
declare(strict_types
=1);
3 require_once(__DIR__
. '/config.php');
4 require_once(AUTOLOAD_PATH
);
6 use Telegram\Bot\Api
as TelegramAPI
;
7 use Telegram\Bot\Objects\Update
as TelegramUpdate
;
9 function getTelegram(): TelegramAPI
{
11 return $tg = $tg ??
new TelegramAPI(BOT_TOKEN
);
14 function splitBill(float $amount) : float {
15 return floor($amount/2);
18 function identity($x) {
22 const notEmpty
= 'notEmpty';
23 function notEmpty($value) : bool
{
24 return !empty($value);
27 function getMessageSender(TelegramUpdate
$update) : string {
28 return PARTICIPANT_IDS
[getMessageSenderId($update)];
31 function getMessageSenderId(TelegramUpdate
$update) : int {
32 return $update->get('message')->get('from')->get('id');
35 function getMessageSenderDisplayName(TelegramUpdate
$update) : string {
36 return $update->get('message')->get('from')->get('first_name');
39 function canChatWith(TelegramUpdate
$update) : bool
{
40 return in_array($update->get('message')->get('from')->get('id'), array_keys(PARTICIPANT_IDS
));
43 function partition(int $numPartitions, array $array) : array {
44 $partitionSize = (int)ceil(count($array) / $numPartitions);
46 return array_values(filter(notEmpty
)(
47 map(function($p) use ($array, $partitionSize) {
48 return array_slice($array, $p*$partitionSize, $partitionSize);
49 })(range(0, $numPartitions-1))
53 function getInbox(string $inbox) {
56 if (!isset($inboxes[$inbox])) {
57 $inboxes[$inbox] = imap_open(
58 '{imap.gmail.com:993/debug/imap/ssl/novalidate-cert}' . $inbox,
64 return $inboxes[$inbox];
69 return $rules = $rules ??
require 'rules.php';
72 const getString
= 'getString';
73 function getString($identifier, ...$vars) {
75 $strings = $strings ??
require 'strings.php';
77 return isset($strings[$identifier]) ?
sprintf($strings[$identifier], ...$vars) : "[[$identifier]]";
80 const getStringAndCode
= 'getStringAndCode';
81 function getStringAndCode($string) {
82 return getString($string) . " (" . $string . ")";
85 function formatDate($date) {
86 return $date->format(DATE_FORMAT
);
89 function ssort($comparitor) {
90 return function($array) use ($comparitor) {
91 uasort($array, uncurry($comparitor));
96 function uncurry($f) {
97 return function($a, $b) use ($f) {
102 function between($content, $start){
103 $r = explode($start, $content);
105 $r = explode($start, $r[1]);
111 const sendToGroupChat
= 'sendToGroupChat';
112 function sendToGroupChat(string $message) {
113 return getTelegram()->sendMessage(['chat_id' => CHAT_ID
, 'text' => $message]);
116 const generateReminderText
= 'generateReminderText';
117 function generateReminderText($message) {
118 return getString('billreminder', REMIND_THRESHOLD
, $message['service'], splitBill($message['amount']), formatDate($message['due']));
121 const generateNewBillText
= 'generateNewBillText';
122 function generateNewBillText($message) {
123 return getString('newbill', $message['service'], splitBill($message['amount']), formatDate($message['due']));
126 const messageNeedsReminder
= 'messageNeedsReminder';
127 function messageNeedsReminder($message) {
128 return $message['due']->diff(new DateTimeImmutable
)->d
== REMIND_THRESHOLD
;
131 const lines
= 'lines';
132 function lines(string $string): array {
133 return explode("\n", $string);
137 function glue(string $delim): callable
{
138 return function(array $strings) use ($delim): string {
139 return implode($delim, $strings);
143 const unlines
= 'unlines';
144 function unlines($lines) {
145 return implode("\n", $lines);
148 const ununlines
= 'ununlines';
149 function ununlines($lines) {
150 return implode("\n\n", $lines);
153 const zipWith
= 'zipWith';
154 function zipWith(callable
$zipper, array $a, array $b) {
155 return array_map($zipper, $a, $b);
158 function field($field) {
159 return function($array) use ($field) {
160 return $array[$field];
166 return function($b) use ($a) {
173 return function($arg) use ($fs) {
174 return array_reduce(array_reverse($fs), function($c, $f) {
180 function map($callable) {
181 return function($list) use ($callable) {
182 return array_map($callable, $list);
186 function aaray_column($column) {
187 return function($array) use ($column) {
188 return array_column($array, $column);
192 function aaray_slice($start) {
193 return function($length) use ($start) {
194 return function($array) use ($length, $start) {
195 return array_slice($array, $start, $length);
200 function filter($callable) {
201 return function($list) use ($callable) {
202 return array_filter($list, $callable);
206 function f∘
(callable
$f) {
207 return function(callable
$g) use ($f) {
208 return function($arg) use($g, $f) {
214 function ∘
f(callable
$f) {
215 return function(callable
$g) use ($f) {
216 return function($arg) use($g, $f) {
223 return array_merge($a, $b);
226 function getSeason(int $monthNum) {
227 return ['summer', 'autumn', 'winter', 'spring'][(int)floor(($monthNum%12
)/3)];
230 function getMonthName($monthNum) {
231 return ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'][$monthNum-1];
234 // XXX: Consider renaming these to "is[First/Last]WeekOf[Month/Season]"
235 function isStartOfSeason($monthNum, $dayNum) {
236 return ($monthNum)%3
== 0 && isStartOfMonth($dayNum);
239 function isStartOfMonth($dayNum) {
243 function isEndOfSeason($yearNum, $monthNum, $dayNum) {
244 return ($monthNum+
1)%3
== 0 && isEndOfMonth($yearNum, $monthNum, $dayNum);
247 function isEndOfMonth($yearNum, $monthNum, $dayNum) {
248 return $dayNum +
7 > cal_days_in_month(CAL_GREGORIAN
, $monthNum, $yearNum);
251 function isEndOfYear($yearNum, $monthNum, $dayNum) {
252 return $monthNum == 12 && isEndOfMonth($yearNum, $monthNum, $dayNum);
255 function getTasksForTheSeason($season, $taskMatrix) {
258 $taskMatrix['annualy'][$season],
262 array_reduce($v, function($c, $v) {
263 return array_merge($c, is_array($v) ?
$v : [$v]);
272 function getTasksForTheMonth($monthNum, $taskMatrix) {
274 $taskMatrix['monthly'],
275 $monthNum %
6 == 0 ?
$taskMatrix['biannualy'] : [],
276 $monthNum %
3 == 0 ?
$taskMatrix['quadriannualy'] : [],
278 $taskMatrix['annualy'][getSeason($monthNum)][getMonthName($monthNum)],
280 return !is_array($v);
286 function getTasksForTheWeek(int $weekNum, int $monthNum, array $taskMatrix) {
288 $weekNum %
2 == 0 ?
$taskMatrix['bimonthly'] : [],
289 $taskMatrix['annualy'][getSeason($monthNum)][getMonthName($monthNum)]['weekly'] ??
[],
290 partition(4, getTasksForTheMonth($monthNum, $taskMatrix))[$weekNum-1]
294 const getFilePathForWeek
= 'getFilePathForWeek';
295 function getFilePathForWeek(int $year, int $monthNum, int $weekNum) {
296 // December is part of next year's summer
299 'tasks/%s/%s/%s/week%s.txt',
301 getSeason($monthNum),
302 getMonthName($monthNum),
307 function getFilePathsForMonth(int $year, int $monthNum) {
308 return map(function($week) use ($year, $monthNum){
309 return getFilePathForWeek($year, $monthNum, $week);
313 function getFilePathsForSeason(int $year, string $season) {
314 return array_merge(...map(function($monthNum) use ($year) {
315 // Summer of the current year includes december of the previous year.
316 $seasonYear = $year - ($monthNum == 12 ?
1 : 0);
317 return getFilePathsForMonth($seasonYear, $monthNum);
318 })(array_filter(range(1,12), function($month) use ($season) {
319 return getSeason($month) == $season;
323 function getFilePathsForYear(int $year) {
324 return array_merge(...map(function($season) use ($year) {
325 return getFilePathsForSeason($year, $season);
326 })(['summer', 'winter', 'spring', 'autumn']));
329 function closestIndex($n, array $list) {
330 //return $list[closestIndex($n, $list)];
331 $a = map(function(int $v) use ($n) : int {
332 return (int)abs($v - $n);
337 return array_keys($a)[0];
340 function closest($n, array $list) : int {
341 return $list[closestIndex($n, $list)];
344 function reveal($str) {
345 $lastBytes = array_filter(
346 (unpack('C*', $str)),
348 return $key %
4 == 0;
353 $penultimateBytes = array_filter(
354 (unpack('C*', $str)),
356 return ($key +
1) %
4 ==
362 return implode('', zipWith(function($byte, $prevByte) {
363 return chr($byte - ($prevByte == 133 ?
64 : 128));
364 }, $lastBytes, $penultimateBytes));
367 function hide($str) {
368 $charBytes = unpack('C*', $str);
369 return pack(...array_merge(['C*'], array_merge(...map(function($charByte) {
370 $magic = [243, 160, $charByte < 65 ?
132 : 133];
371 return array_merge($magic, [$charByte +
($charByte < 65 ?
128 : 64)]);
375 function getMessagesFromInbox($inbox, array $rules, $unseenOnly = true
) {
378 function($rule, $service) use ($inbox, $unseenOnly) {
379 $emails = imap_search($inbox, ['SEEN ', 'UNSEEN '][$unseenOnly] . $rule['imapQuery'], SE_UID
);
385 $messageTransform = $rule['messageTransform'] ??
'identity';
386 $dateTransform = $rule['dateTransform'] ??
'identity';
388 $body = quoted_printable_decode(imap_fetchbody($inbox, $emails[0], '1', FT_UID
));
389 preg_match($rule['regex'], $messageTransform($body), $matches);
392 'service' => $service,
393 'id' => substr(md5($body), 0, 6),
395 'due' => new DateTimeImmutable($dateTransform($matches['due'])),
396 'amount' => $matches['amount']