-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.php
More file actions
3161 lines (2607 loc) · 88.5 KB
/
Copy pathstore.php
File metadata and controls
3161 lines (2607 loc) · 88.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// SQL-based store.
namespace store;
$_URL = getenv("DATABASE_URL") ?: "sqlite://data.db";
if(str_starts_with($_URL, "sqlite://")) {
$_DATABASE = ['scheme' => 'sqlite', 'path' => substr($_URL, strlen("sqlite://"))];
}
else {
$_DATABASE = parse_url($_URL) or fail("Syntax error in database connection string.");
}
switch($_DATABASE['scheme']) {
case 'mysql': require __DIR__ . "/store/adapter/mysql.php"; break;
case 'postgres': require __DIR__ . "/store/adapter/postgres.php"; break;
case 'sqlite': require __DIR__ . "/store/adapter/sqlite.php"; break;
default: fail("Unsupported database driver '{$_DATABASE['scheme']}'.");
}
define('ENUM_TIMEZONE', \DateTimeZone::listIdentifiers());
define('ENUM_TASK_STATUS', ['todo', 'wip', 'backlog', 'blocked', 'done', 'nvm']);
define('ENUM_WISH_STATUS', ['dream', 'bought', 'nvm']);
define('ENUM_SSL_MODE', ['plain', 'tls', 'ssl']);
function get_anything($humid) {
$entry = one('SELECT * FROM humids WHERE id = ?', [$humid]);
if(!$entry) return false;
$item = match($entry['type']) {
'note' => get_note($humid),
'todo' => get_task($humid),
'wish' => get_wish($humid),
'appointment' => get_appointment_by_humid($humid),
'timing' => get_timing($humid),
'bookmark' => get_bookmark($humid),
'contact' => get_contact($humid),
'organisation' => get_organisation($humid),
'address' => get_address($humid),
default => false,
};
return $item ? ['type' => $entry['type'], ...$item] : false;
}
function list_anything_tags($item) {
return match($item['type']) {
'note' => list_note_tags($item['id']),
'todo' => list_task_tags($item['id']),
'wish' => list_wish_tags($item['id']),
'appointment' => list_appointment_tags($item['id']),
'timing' => list_timing_tags($item['id']),
'bookmark' => list_bookmark_tags($item['id']),
'contact' => list_contact_tags($item['id']),
'organisation' => list_organisation_tags($item['id']),
'address' => [],
};
}
// HumIDs
function put_humid($type, $id = null) {
$id ??= generate_humid();
exec_query('INSERT INTO humids (id, type) VALUES (?, ?)', [$id, $type]);
return $id;
}
function reserve_humid($type, $id) {
$entry = one('SELECT type FROM humids WHERE id = ?', [$id]);
if(!$entry) return put_humid($type, $id);
if($entry['type'] != $type) fail("HumID $id already belongs to {$entry['type']}.");
return $id;
}
function convert_humid($id, $type) {
return exec_query('UPDATE humids SET type = ? WHERE id = ?', [$type, $id]);
}
// Notes
function put_note($title, $content, $date = null) {
exec_query('INSERT INTO notes (
id,
title,
content,
written_at
) VALUES (?, ?, ?, ?)', [
$id = put_humid('note'),
$title,
$content,
$date ?? gmdate('c')
]);
return $id;
}
function update_note($id, $title, $content, $date = null) {
return exec_query('UPDATE notes SET
title = ?,
content = ?,
written_at = ?
WHERE id = ?', [$title, $content, $date, $id]);
}
function update_note_apple_id($id, $apple_id) {
return exec_query('UPDATE notes SET apple_id = ? WHERE id = ?', [$apple_id, $id]);
}
function clear_note_apple_ids() {
return exec_query('UPDATE notes SET apple_id = NULL', []);
}
function get_note($id) {
return one('SELECT * FROM notes WHERE id = ?', [$id]);
}
function get_note_by_apple_id($apple_id) {
return one('SELECT * FROM notes WHERE apple_id = ?', [$apple_id]);
}
function list_note_tags($id) {
return tags_of('notes_tags', 'note_id', $id);
}
function list_note_tag_ids($id) {
return array_column(list_note_tags($id), 'id');
}
function set_note_tags($id, $tag_ids) {
set_tags('notes_tags', 'note_id', $id, $tag_ids);
}
function notes_query($query, $stable = false, $count = false) {
[$tags, $terms] = \core\parse_query($query);
$where = [];
$params = [];
foreach($terms as $term) {
$where[] = '(EXO_NORMALIZE(title) LIKE EXO_NORMALIZE(?)
OR EXO_NORMALIZE(content) LIKE EXO_NORMALIZE(?))';
$like = "%$term%";
$params[] = $like;
$params[] = $like;
}
foreach($tags as $id) {
$where[] = 'EXISTS (SELECT 1 FROM notes_tags nt
WHERE nt.note_id = notes.id AND nt.tag_id = ?)';
$params[] = $id;
}
$sql = $count ? 'SELECT COUNT(*) AS count FROM notes' : 'SELECT * FROM notes';
if($where) $sql .= ' WHERE ' . join(' AND ', $where);
if(!$count) {
$sql .= ' ORDER BY CASE WHEN written_at IS NULL THEN 1 ELSE 0 END, written_at DESC';
if($stable) $sql .= ', id DESC';
}
return [$sql, $params];
}
function count_notes($query = "") {
[$sql, $params] = notes_query($query, count: true);
return one($sql, $params)['count'];
}
function list_notes($query = "") {
[$sql, $params] = notes_query($query);
return all($sql, $params);
}
function list_notes_paginated($query, $limit, $offset = 0) {
[$sql, $params] = notes_query($query, stable: true);
return paginate($sql, $limit, offset: $offset, params: $params);
}
function list_apple_notes() {
return all('SELECT * FROM notes WHERE apple_id IS NOT NULL');
}
function delete_note($id) {
return exec_query('DELETE FROM notes WHERE id = ?', [$id]);
}
function put_note_tombstone($apple_id, $deleted_at) {
exec_query('DELETE FROM notes_tombstones WHERE apple_id = ?', [$apple_id]);
return exec_query('INSERT INTO notes_tombstones (apple_id, deleted_at) VALUES (?, ?)',
[$apple_id, $deleted_at]);
}
function list_note_tombstones() {
return all('SELECT * FROM notes_tombstones');
}
function delete_note_tombstone($apple_id) {
return exec_query('DELETE FROM notes_tombstones WHERE apple_id = ?', [$apple_id]);
}
function clear_note_tombstones() {
return exec_query('DELETE FROM notes_tombstones', []);
}
// Tasks
function put_task(
$title,
$content,
$status,
$urgent = false,
$recurrence = null,
$open_at = null,
$due_at = null,
$due_all_day = false,
$expire_at = null,
$comment = null,
$id = null
) {
if(!in_array($status, ENUM_TASK_STATUS)) fail("status $status does not exist");
$open_at ??= gmdate('c');
exec_query('INSERT INTO tasks (
id,
title,
content,
urgent,
recurrence,
open_at,
due_at,
due_all_day,
expire_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [
$id = $id ? reserve_humid('todo', $id) : put_humid('todo'),
$title,
$content,
$urgent,
$recurrence,
$open_at,
$due_at,
$due_all_day,
$expire_at
]);
exec_query('INSERT INTO task_log (
task_id,
changed_at,
status,
comment
) VALUES (?, ?, ?, ?)', [
$id,
gmdate('c'),
$status,
$comment
]);
return $id;
}
function update_task(
$id,
$title,
$content,
$urgent,
$recurrence,
$open_at,
$due_at,
$due_all_day,
$expire_at
) {
return exec_query('UPDATE tasks SET
title = ?,
content = ?,
urgent = ?,
recurrence = ?,
open_at = ?,
due_at = ?,
due_all_day = ?,
expire_at = ?
WHERE id = ?', [
$title,
$content,
$urgent,
$recurrence,
$open_at,
$due_at,
$due_all_day,
$expire_at,
$id
]);
}
function set_task_urgent($id, $urgent) {
return exec_query('UPDATE tasks SET urgent = ? WHERE id = ?', [$urgent, $id]);
}
function set_task_status($id, $status, $comment = "") {
if(!in_array($status, ENUM_TASK_STATUS)) fail("status $status does not exist");
// Skip redundant transitions: if the latest entry already has this status and
// no comment is being added, there is nothing new to record. This stops rapid
// toggles from the listing (which race the async re-render) from stacking up
// empty log events.
$latest = one('SELECT status FROM task_log
WHERE task_id = ? ORDER BY changed_at DESC, id DESC', [$id]);
if($latest && $latest['status'] === $status && !$comment) return true;
return exec_query('INSERT INTO task_log (
task_id,
changed_at,
status,
comment
) VALUES (?, ?, ?, ?)', [
$id,
gmdate('c'),
$status,
$comment
]);
}
function list_task_tags($id) {
return tags_of('tasks_tags', 'task_id', $id);
}
function list_task_tag_ids($id) {
return array_column(list_task_tags($id), 'id');
}
function set_task_tags($id, $tag_ids) {
set_tags('tasks_tags', 'task_id', $id, $tag_ids);
}
// Status is derived from the log (see \recurrence\task_state) and a recurring
// task's effective status can differ from its latest log row, so filtering
// happens in PHP rather than SQL. $override lists ids that bypass the filter
// entirely (freshly clicked tasks that shouldn't vanish under the cursor).
// $respect_horizon hides recurring tasks outside their visibility window; the
// calendar passes false to keep future deadlines addressable.
function list_tasks($query = "", $override = [], $respect_horizon = true) {
$include = [];
$exclude = [];
$urgent = null;
$expired = null;
$overdue = null;
foreach(explode(" ", $query) as $segment) {
$parts = explode(":", $segment);
if(count($parts) != 2) continue;
[$selector, $value] = $parts;
if($value == 'urgent') $urgent = $selector == "is";
elseif($value == 'expired') $expired = $selector == 'is';
elseif($value == 'overdue') $overdue = $selector == 'is';
elseif($selector == "is" && $value == 'open') $include = [...$include, 'todo', 'wip', 'blocked'];
elseif($selector == "is" && in_array($value, ENUM_TASK_STATUS)) $include[] = $value;
elseif($selector == "not" && in_array($value, ENUM_TASK_STATUS)) $exclude[] = $value;
}
$rows = all("SELECT
tasks.*,
tags.id as tag_id,
tags.label as tag_label,
tags.color as tag_color,
tags.parent_id as tag_parent_id,
log.status,
log.comment,
log.changed_at as updated_date,
(SELECT done.changed_at FROM task_log done
WHERE done.task_id = tasks.id AND done.status = 'done'
ORDER BY done.changed_at DESC, done.id DESC LIMIT 1) AS last_done
FROM tasks
LEFT JOIN task_log log
ON log.id = (
SELECT ranked.id
FROM task_log ranked
WHERE ranked.task_id = tasks.id
ORDER BY ranked.changed_at DESC, ranked.id DESC
LIMIT 1
)
LEFT JOIN tasks_tags tt ON tt.task_id = tasks.id
LEFT JOIN tags ON tags.id = tt.tag_id
ORDER BY
due_at NULLS LAST,
expire_at NULLS LAST,
open_at");
if(!$rows) return $rows;
$override = $override ?? [];
$result = [];
$colors = array_column(list_tags(), 'color', 'id');
$now = new \DateTimeImmutable("now", new \DateTimeZone(TIMEZONE));
foreach(collect_by($rows, 'tag', 'tags') as $task) {
foreach($task['tags'] as &$tag) {
$tag['color'] = @$colors[$tag['id']] ?: $tag['color'];
}
unset($tag);
$state = \recurrence\task_state($task);
$task = array_merge($task, $state);
if(in_array($task['id'], $override, true)) { $result[] = $task; continue; }
$is_expired = $task['expire_at'] && strtotime($task['expire_at']) <= time();
if($expired !== null && $is_expired != $expired) continue;
if($respect_horizon && !$is_expired && !$state['visible']) continue;
$due = $task['next'] ? new \DateTimeImmutable($task['next']) : null;
if($due && cast_bool($task['due_all_day'])) {
$due = $due->setTimezone(new \DateTimeZone(TIMEZONE))->modify('+1 day');
}
$is_overdue = $due && $due <= $now;
if($overdue !== null && $is_overdue != $overdue) continue;
if($urgent !== null && filter_var($task['urgent'], FILTER_VALIDATE_BOOLEAN) != $urgent) continue;
if($include && !in_array($state['status'], $include)) continue;
if($exclude && in_array($state['status'], $exclude)) continue;
$result[] = $task;
}
return $result;
}
function get_task($id) {
$task = one('SELECT
task.id,
task.title,
task.content,
task.urgent,
task.recurrence,
task.open_at,
task.due_at,
task.due_all_day,
task.expire_at,
log.status,
log.comment,
log.changed_at as updated_date,
(SELECT done.changed_at FROM task_log done
WHERE done.task_id = task.id AND done.status = \'done\'
ORDER BY done.changed_at DESC, done.id DESC LIMIT 1) AS last_done
FROM tasks task
LEFT JOIN task_log log ON log.task_id = task.id
WHERE task.id = ?
ORDER BY log.changed_at DESC, log.id DESC', [$id]);
if($task === false) return $task;
$task = array_merge($task, \recurrence\task_state($task));
$tags = all('SELECT tags.label FROM tags
JOIN tasks_tags tt ON tt.tag_id = tags.id
WHERE tt.task_id = ?', [$id]);
$task['tags'] = array_column($tags, 'label');
return $task;
}
function get_task_log($id) {
return all('SELECT * FROM task_log WHERE task_id = ? ORDER BY changed_at ASC, id ASC', [$id]);
}
function amend_task_status($id, $comment) {
$log = all('SELECT * FROM task_log
WHERE task_id = ? ORDER BY changed_at DESC, id DESC LIMIT 2', [$id]);
if(!$log) return $log;
return exec_query('UPDATE task_log SET comment = ?
WHERE id = ? AND task_id = ?', [$comment, $log[0]['id'], $id]);
}
function undo_task_status($id, $log_id) {
$log = all('SELECT id, status FROM task_log
WHERE task_id = ? ORDER BY changed_at DESC, id DESC LIMIT 2', [$id]);
if(!$log || count($log) < 2 || $log[0]['id'] != $log_id ||
$log[0]['status'] == $log[1]['status']) return false;
$query = exec_query('DELETE FROM task_log
WHERE id = ? AND task_id = ? AND id = (
SELECT latest.id FROM (
SELECT id FROM task_log
WHERE task_id = ? ORDER BY changed_at DESC, id DESC LIMIT 1
) latest
)', [$log_id, $id, $id]);
return $query && $query->rowCount() == 1;
}
function delete_task($id) {
return exec_query('DELETE FROM tasks WHERE id = ?', [$id]);
}
// Wishes
function put_wish($title, $content, $status, $urgent = false, $date = null) {
if(!in_array($status, ENUM_WISH_STATUS)) fail("status $status does not exist");
exec_query('INSERT INTO wishes (
id,
title,
content,
urgent,
added_at
) VALUES (?, ?, ?, ?, ?)', [
$id = put_humid('wish'),
$title,
$content,
$urgent,
$date ?? gmdate('c')
]);
exec_query('INSERT INTO wish_log (
wish_id,
status
) VALUES (?, ?)', [$id, $status]);
return $id;
}
function set_wish_status($id, $status, $comment = "") {
if(!in_array($status, ENUM_WISH_STATUS)) fail("status $status does not exist");
// Skip redundant transitions (see set_task_status): the wish listing has the
// same toggle, so rapid clicks would otherwise stack up empty log events.
$latest = one('SELECT status FROM wish_log
WHERE wish_id = ? ORDER BY changed_at DESC, id DESC', [$id]);
if($latest && $latest['status'] === $status && !$comment) return true;
return exec_query('INSERT INTO wish_log (
wish_id,
status,
comment
) VALUES (?, ?, ?)', [$id, $status, $comment]);
}
function update_wish($id, $title, $content, $urgent, $date = null) {
return exec_query('UPDATE wishes SET
title = ?,
content = ?,
urgent = ?,
added_at = ?
WHERE id = ?', [$title, $content, $urgent, $date, $id]);
}
function get_wish($id) {
$wish = one('SELECT
wishes.*,
log.status,
log.comment,
log.changed_at as updated_date
FROM wishes
LEFT JOIN wish_log log
ON log.id = (
SELECT ranked.id
FROM wish_log ranked
WHERE ranked.wish_id = wishes.id
ORDER BY ranked.changed_at DESC, ranked.id DESC
LIMIT 1
)
WHERE wishes.id = ?', [$id]);
if(!$wish) return $wish;
$wish['urls'] = list_wish_urls($id);
return $wish;
}
function list_wish_urls($id) {
return all('SELECT url, price FROM wish_urls WHERE wish_id = ? ORDER BY id', [$id]);
}
function set_wish_urls($id, $rows) {
set_children('wish_urls', 'wish_id', $id, $rows);
}
function list_wish_tags($id) {
return tags_of('wishes_tags', 'wish_id', $id);
}
function list_wish_tag_ids($id) {
return array_column(list_wish_tags($id), 'id');
}
function set_wish_tags($id, $tag_ids) {
set_tags('wishes_tags', 'wish_id', $id, $tag_ids);
}
function get_wish_log($id) {
return all('SELECT * FROM wish_log WHERE wish_id = ? ORDER BY changed_at ASC', [$id]);
}
function wishes_query($statuses = [], $override = []) {
$params = [];
$where = [];
if($statuses) {
$status = 'log.status IN (' . join(', ', array_fill(0, count($statuses), '?')) . ')';
$params = [...$params, ...$statuses];
if($override) {
$status = "($status OR wishes.id IN (" . join(', ', array_fill(0, count($override), '?')) . '))';
$params = [...$params, ...$override];
}
$where[] = $status;
}
$sql = "SELECT
wishes.*,
log.status,
log.comment,
log.changed_at as updated_date,
(SELECT SUM(price) FROM wish_urls WHERE wish_urls.wish_id = wishes.id) as total_price
FROM wishes
LEFT JOIN wish_log log
ON log.id = (
SELECT ranked.id
FROM wish_log ranked
WHERE ranked.wish_id = wishes.id
ORDER BY ranked.changed_at DESC, ranked.id DESC
LIMIT 1
)";
if($where) $sql .= ' WHERE ' . join(' AND ', $where);
$sql .= ' ORDER BY wishes.added_at DESC, wishes.id DESC';
return [$sql, $params];
}
function list_wishes($statuses = [], $override = []) {
[$sql, $params] = wishes_query($statuses, $override);
return all($sql, $params);
}
function list_wishes_paginated($statuses, $override, $limit, $offset = 0) {
[$sql, $params] = wishes_query($statuses, $override);
return paginate($sql, $limit, offset: $offset, params: $params);
}
function delete_wish($id) {
return exec_query('DELETE FROM wishes WHERE id = ?', [$id]);
}
// Bookmarks
function put_bookmark($url, $label = null, $note = null, $favicon = null, $date = null) {
exec_query('INSERT INTO bookmarks (
id,
label,
url,
note,
favicon,
saved_at
) VALUES (?, ?, ?, ?, ?, ?)', [
$id = put_humid('bookmark'),
$label,
$url,
$note,
$favicon,
$date ?? gmdate('c')
]);
return $id;
}
function update_bookmark($id, $label, $url, $note = null, $date = null) {
return exec_query('UPDATE bookmarks SET
label = ?,
url = ?,
note = ?,
saved_at = ?
WHERE id = ?', [$label, $url, $note, $date, $id]);
}
function update_bookmark_favicon($id, $favicon) {
return exec_query('UPDATE bookmarks SET favicon = ? WHERE id = ?', [$favicon, $id]);
}
function list_bookmark_tags($id) {
return tags_of('bookmarks_tags', 'bookmark_id', $id);
}
function list_bookmark_tag_ids($id) {
return array_column(list_bookmark_tags($id), 'id');
}
function set_bookmark_tags($id, $tag_ids) {
set_tags('bookmarks_tags', 'bookmark_id', $id, $tag_ids);
}
function get_bookmark($id) {
return one('SELECT * FROM bookmarks WHERE id = ?', [$id]);
}
function bookmarks_query($query, $stable = false) {
[$tags, $terms] = \core\parse_query($query);
$where = [];
$params = [];
foreach($terms as $term) {
$where[] = '(EXO_NORMALIZE(label) LIKE EXO_NORMALIZE(?)
OR EXO_NORMALIZE(url) LIKE EXO_NORMALIZE(?)
OR EXO_NORMALIZE(note) LIKE EXO_NORMALIZE(?))';
$like = "%$term%";
$params[] = $like;
$params[] = $like;
$params[] = $like;
}
foreach($tags as $id) {
$where[] = 'EXISTS (SELECT 1 FROM bookmarks_tags bt
WHERE bt.bookmark_id = bookmarks.id AND bt.tag_id = ?)';
$params[] = $id;
}
$sql = 'SELECT * FROM bookmarks';
if($where) $sql .= ' WHERE ' . join(' AND ', $where);
$sql .= ' ORDER BY CASE WHEN saved_at IS NULL THEN 1 ELSE 0 END, saved_at DESC';
if($stable) $sql .= ', id DESC';
return [$sql, $params];
}
function list_bookmarks($query = "") {
[$sql, $params] = bookmarks_query($query);
return all($sql, $params);
}
function list_bookmarks_paginated($query, $limit, $offset = 0) {
[$sql, $params] = bookmarks_query($query, stable: true);
return paginate($sql, $limit, offset: $offset, params: $params);
}
function delete_bookmark($id) {
return exec_query('DELETE FROM bookmarks WHERE id = ?', [$id]);
}
// Tracker
function put_timing($description, $starts_at, $ends_at, $task_id = null) {
if($task_id) get_task($task_id) or fail("task with ID $task_id does not exist");
exec_query('INSERT INTO timings (
id,
description,
starts_at,
ends_at,
task_id
) VALUES (?, ?, ?, ?, ?)', [
$id = put_humid('timing'),
$description,
$starts_at,
$ends_at,
$task_id
]);
return $id;
}
function update_timing($id, $description, $starts_at, $ends_at, $task_id) {
if($task_id) get_task($task_id) or fail("task with ID $task_id does not exist");
return exec_query('UPDATE timings SET
description = ?,
starts_at = ?,
ends_at = ?,
task_id = ?
WHERE id = ?', [
$description,
$starts_at,
$ends_at,
$task_id,
$id
]);
}
function list_timing_tags($id) {
return tags_of('timings_tags', 'timing_id', $id);
}
function list_timings_tags($ids) {
if(!$ids) return [];
$placeholders = join(', ', array_fill(0, count($ids), '?'));
return inherit_tag_colors(all("SELECT link.timing_id, tags.* FROM tags
JOIN timings_tags link ON link.tag_id = tags.id
WHERE link.timing_id IN ($placeholders)
ORDER BY tags.position ASC, tags.id DESC", $ids));
}
function list_timing_tag_ids($id) {
return array_column(list_timing_tags($id), 'id');
}
function set_timing_tags($id, $tag_ids) {
set_tags('timings_tags', 'timing_id', $id, $tag_ids);
}
function list_timings() {
return all('SELECT * FROM timings ORDER BY starts_at DESC');
}
function list_timings_paginated($limit, $offset = 0) {
return paginate('SELECT * FROM timings ORDER BY starts_at DESC, id DESC', $limit, offset: $offset);
}
function search_timings_paginated($query, $limit, $offset = 0) {
[$tags, $terms] = \core\parse_query($query);
$where = [];
$params = [];
foreach($terms as $term) {
$where[] = 'EXO_NORMALIZE(description) LIKE EXO_NORMALIZE(?)';
$params[] = "%$term%";
}
foreach($tags as $id) {
$where[] = 'EXISTS (SELECT 1 FROM timings_tags tt
WHERE tt.timing_id = timings.id AND tt.tag_id = ?)';
$params[] = $id;
}
$sql = 'SELECT * FROM timings';
if($where) $sql .= ' WHERE ' . join(' AND ', $where);
$sql .= ' ORDER BY starts_at DESC, id DESC';
return paginate($sql, $limit, offset: $offset, params: $params);
}
function resolve_timing_page($id, $limit) {
$timing = get_timing($id) or fail("Timing not found.", status: 404);
$before = one('SELECT COUNT(*) AS count FROM timings
WHERE starts_at > ? OR (starts_at = ? AND id > ?)',
[$timing['starts_at'], $timing['starts_at'], $id])['count'];
$page = intdiv($before, $limit) + 1;
return [$page, ($page - 1) * $limit];
}
// Timings overlapping [$from, $to), each carrying its first tag (lowest id).
// The caller resolves that tag to its root to pick a colour; keeping it a bare
// id keeps this query portable across the SQL engines we target.
function list_timings_between($from, $to) {
return all('SELECT
t.*,
(SELECT tt.tag_id FROM timings_tags tt
WHERE tt.timing_id = t.id
ORDER BY tt.tag_id ASC LIMIT 1) AS first_tag_id
FROM timings t
WHERE t.starts_at < ? AND t.ends_at > ?
ORDER BY t.starts_at', [$to, $from]);
}
function list_timing_tags_between($from, $to) {
return all('SELECT t.id, t.starts_at, t.ends_at, tt.tag_id
FROM timings t
JOIN timings_tags tt ON tt.timing_id = t.id
WHERE t.starts_at < ? AND t.ends_at > ?', [$to, $from]);
}
function get_timing($id) {
return one('SELECT * FROM timings WHERE id = ?', [$id]);
}
function delete_timing($id) {
return exec_query('DELETE FROM timings WHERE id = ?', [$id]);
}
// Quotas
function list_quotas() {
$quotas = all('SELECT q.*, t.label, t.color
FROM quotas q
JOIN tags t ON t.id = q.tag_id
ORDER BY t.position ASC, t.id DESC');
return inherit_tag_colors($quotas, id_key: 'tag_id');
}
function get_quota_by_tag($tag_id) {
return one('SELECT * FROM quotas WHERE tag_id = ?', [$tag_id]);
}
function put_quota($tag_id, $period, $minutes, $start_date) {
return exec_query('INSERT INTO quotas (tag_id, period, minutes, start_date)
VALUES (?, ?, ?, ?)', [$tag_id, $period, $minutes, $start_date]);
}
function update_quota($tag_id, $period, $minutes, $start_date) {
return exec_query('UPDATE quotas
SET period = ?, minutes = ?, start_date = ? WHERE tag_id = ?',
[$period, $minutes, $start_date, $tag_id]);
}
function delete_quota($tag_id) {
return exec_query('DELETE FROM quotas WHERE tag_id = ?', [$tag_id]);
}
// Tags
function put_tag($label, $color, $parent_id) {
if($parent_id) get_tag($parent_id) or fail("tag with ID $parent_id does not exist");
exec_query('INSERT INTO tags (
label,
color,
parent_id,
position
) VALUES (?, ?, ?, ?)', [
$label,
$color,
$parent_id,
prepend_order('tags')
]);
return DBH->lastInsertId();
}
function update_tag($id, $label, $color, $parent_id) {
if($parent_id) {
$cursor = $parent_id;
while($cursor) {
if($cursor == $id) fail("illegal circular structure detected");
$tag = get_tag($cursor) or fail("tag with ID $cursor does not exist");
$cursor = $tag['parent_id'];
}
}
return exec_query('UPDATE tags SET
label = ?,
color = COALESCE(?, color),
parent_id = ?
WHERE id = ?', [
$label,
$color,
$parent_id,
$id
]);
}
function list_tags() {
$tags = all('SELECT * FROM tags ORDER BY position ASC, id DESC');
$children = [];
foreach($tags as $tag) $children[$tag['parent_id']][] = $tag;
$result = [];
$walk = function($parent_id, $color = null) use (&$walk, &$children, &$result) {
foreach($children[$parent_id] ?? [] as $tag) {
if($parent_id) $tag['color'] = $color;
$result[] = $tag;
$walk($tag['id'], $tag['color']);
}
};
$walk(null);
return $result;
}
function inherit_tag_colors($items, $id_key = 'id') {
$colors = array_column(list_tags(), 'color', 'id');
return array_map(function($item) use ($colors, $id_key) {
$item['color'] = @$colors[$item[$id_key]] ?: $item['color'];
return $item;
}, $items);
}
function reorder_tags($ids) {
foreach(array_values($ids) as $order => $id) {
exec_query('UPDATE tags
SET position = ? WHERE id = ?', [$order, $id]);
}
return true;
}
function tags_of($table, $fk, $id) {
$tags = all("SELECT tags.* FROM tags
JOIN $table link ON link.tag_id = tags.id
WHERE link.$fk = ?
ORDER BY tags.position ASC, tags.id DESC", [$id]);
return inherit_tag_colors($tags);
}
function set_tags($table, $fk, $id, $tag_ids) {
set_children($table, $fk, $id,
array_map(fn($tag_id) => ['tag_id' => $tag_id], $tag_ids));
}