-
Notifications
You must be signed in to change notification settings - Fork 1
/
kb.php
882 lines (767 loc) · 29.9 KB
/
kb.php
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
<?php
# Database description.
define('DSN', 'sqlite:./database.db');
# Namespaces.
define('DC_CREATED', 'http://purl.org/dc/terms/created');
define('DC_CREATOR', 'http://purl.org/dc/terms/creator');
define('DC_SOURCE', 'http://purl.org/dc/terms/source');
define('DPV', 'https://w3id.org/dpv#');
define('DPV_GDPR', 'https://w3id.org/dpv/dpv-gdpr#');
define('DPV_PD', 'https://w3id.org/dpv/dpv-pd#');
define('DPV_CONCEPT', 'https://w3id.org/dpv#Concept');
define('DPV_ISSUBTYPEOF', 'https://w3id.org/dpv#isSubTypeOf');
define('DC_TERMS', 'http://purl.org/dc/terms/');
define('DC_VALID', 'http://purl.org/dc/terms/valid');
define('SCHEMA_ORG', 'http://schema.org/');
define('NS_GDPR', 'https://trapeze-project.eu/ns/gdpr#');
define('RDFS_ISDEFINEDBY', 'http://www.w3.org/2000/01/rdf-schema#isDefinedBy');
define('SCHEMA_DATE', 'http://www.w3.org/2001/XMLSchema#date');
define('SKOS_BROADER', 'http://www.w3.org/2004/02/skos/core#broader');
define('SKOS_CONCEPT', 'http://www.w3.org/2004/02/skos/core#Concept');
define('SKOS_DEFINITION', 'http://www.w3.org/2004/02/skos/core#definition');
define('SKOS_INSCHEME', 'http://www.w3.org/2004/02/skos/core#inScheme');
define('SKOS_NOTE', 'http://www.w3.org/2004/02/skos/core#note');
define('SKOS_PREFLABEL', 'http://www.w3.org/2004/02/skos/core#prefLabel');
define('SKOS_RELATED', 'http://www.w3.org/2004/02/skos/core#related');
define('SW_TERMSTATUS', 'http://www.w3.org/2003/06/sw-vocab-status/ns#term_status');
define('DPA', 'https://w3id.org/dpv#DataProtectionAuthority');
define('NS_SEARCH_RESULTS', 'https://trapeze-project.eu/ns/search-results#');
define('NS_THREAT_INFO', 'https://trapeze-project.eu/ns/threat-info#');
# Error messages. These functions call gettext() to return a localized message.
function ERR_USAGE()
{
return _('<html lang=en>
<title>Missing or unknown ‘action’ parameter</title>
<h1>Missing or unknown ‘action’ parameter</h1>
<p>The ‘action’ parameter must be present and must be one
of ‘search’, ‘definitions’, ‘gdpr’, ‘articles’, ‘status’,
‘articles’, ‘dpv’, ‘threat’, ‘controller’, ‘logo’ or ‘debug’.
');
}
function ERR_NOT_IMPLEMENTED()
{
return _('<html lang=en>
<title>Not yet implemented</title>
<p>Not yet implemented.
');
}
function ERR_MISSING_WORDS()
{
return _('<html lang=en>
<title>Missing ‘words’ parameter</title>
<h1>Missing ‘words’ parameter</h1>
<p>When the ‘action’ parameter is ‘search’,
the ‘words’ parameter is required.
');
}
function ERR_MISSING_TERM()
{
return _('<html lang=en>
<title>Missing ‘term’ parameter</title>
<h1>Missing ‘term’ parameter</h1>
<p>When the ‘action’ parameter is ‘definitions’,
the ‘term’ parameter is required.
');
}
function ERR_MISSING_ARTICLE()
{
return _('<html lang=en>
<title>Missing ‘article’ parameter</title>
<h1>Missing ‘article’ parameter</h1>
<p>When the ‘action’ parameter is ‘gdpr’,
the ‘article’ parameter is required.
');
}
function ERR_NO_DEFINITION()
{
return _('<html lang=en>
<title>No definition found</title>
<p>No definition found.
');
}
function ERR_NO_SUCH_ARTICLE()
{
return _('<title>No such article</title>
<h1>No such article</h1>
<p>The requested article or clause does not exist.
');
}
function ERR_DATABASE()
{
return _('<html lang=en>
<title>Server error: Database not available</title>
<h1>Server error: Database not available</h1>
<p>An error occurred when trying to open the database.
');
}
function ERR_NO_SUCH_DPA()
{
return _('<title>No such DPA</title>
<h1>No such DPA</h1>
<p>No Data Protection Agency exists for the selected country or with the given name.
');
}
function ERR_NO_SUCH_DPV()
{
return _('<title>No such DPV term</title>
<h1>No such DPV term</h1>
<p>No term with the given name exists in the DPV vocabulary.
');
}
function ERR_NO_SUCH_CONTROLLER()
{
return _('<title>No such controller</title>
<h1>No such controller</h1>
<p>No controller with the given ID exists in the database.
');
}
function ERR_NO_CONTROLLER_LOGO()
{
return _('<title>No such logo</title>
<h1>No such logo</h1>
<p>No logo found for this controller.
');
}
function ERR_MISSING_DPV_TERM()
{
return _('<html lang=en>
<title>Missing ‘term’ parameter</title>
<h1>Missing ‘term’ parameter</h1>
<p>When the ‘action’ parameter is ‘dpv’,
the ‘term’ parameter is required.
');
}
function ERR_MISSING_CONTROLLER_ID()
{
return _('<html lang=en>
<title>Missing ‘id’ parameter</title>
<h1>Missing ‘id’ parameter</h1>
<p>When the ‘action’ parameter is ‘controller’ or ‘logo’,
the ‘id’ parameter is required.
');
}
# get_languages -- parse an accept-language string into a sorted array
function get_languages(string $lang)
{
$langs = []; # The resulting list of languages
$weights = []; # Array of quality factors, used for sorting
foreach (explode(',', $lang) as $s) {
if (preg_match('/^\s*([a-z-]+)\s*(?:;\s*q=([0-9.]+))?/i', $s, $matches)) {
# Get the q factor (or 1.0 if not set), and the language code.
$weight = 0 + ($matches[2] ?? 1.0);
$code = strtolower($matches[1]);
# Insert the language & weight at the right places in the sorted arrays.
for ($i = 0; $i < count($weights) && $weights[$i] >= $weight; $i++);
array_splice($weights, $i, 0, $weight);
array_splice($langs, $i, 0, $code);
} else {
# TODO: Report a syntax error in the string?
}
}
return $langs;
}
# find_definitions -- find definitions of term, in the preferred language
function find_definitions(object $db, array $langs, string $term)
{
# TODO: handle language variants ('fr' vs 'fr-be' vs 'fr-fr')
$result = [];
$stmt = $db->prepare('SELECT language, term, definition FROM definitions
WHERE lower(:t) = lower(term) AND :l = language');
for ($i = 0; $result == [] && $i < count($langs); $i++) {
$stmt->execute([':t' => $term, ':l' => $langs[$i]]);
while (($row = $stmt->fetch()))
$result[] = [
'@context' => [
'@language' => $row['language'],
'term' => 'http://www.w3.org/ns/lemon/ontolex#writtenRep',
'definition' => 'http://www.lexinfo.net/ontology/2.0/lexinfo#gloss' ],
'@type' => 'http://www.w3.org/ns/lemon/ontolex#Word',
'term' => $row['term'],
'definition' => $row['definition']];
}
return $result;
}
# find_articles -- return array of online articles relevant to $words
function find_articles(object $db, array $langs, string $words)
{
# The $words should be a full-text search query with the syntax of FTS5
# See https://www.sqlite.org/fts5.html
# TODO: Limit the results if there are too many.
$stmt = $db->prepare('SELECT * FROM articles
WHERE :l = language AND articles MATCH :w ORDER BY RANK');
# Try the query for all languages until there is a result.
$result = [];
for ($i = 0; $result == [] && $i < count($langs); $i++) {
$stmt->execute([':w' => $words, ':l' => $langs[$i]]);
while (($row = $stmt->fetch()))
$result[] = [
'@context' => [
'@language' => $row['language'],
'@vocab' => DC_TERMS,
'keywords' => '@subject',
'authors' => '@creator',
'kind' => '@type',
'url' => '@identifier' ],
'title' => $row['title'],
'abstract' => $row['abstract'],
'keywords' => $row['keywords'],
'authors' => $row['authors'],
'kind' => $row['kind'],
'url' => $row['url']];
}
return $result;
}
# articles -- return articles related to given keywords
function articles(object $db, array $langs)
{
$words = $_REQUEST['words'];
if (!isset($words)) return array(400, ERR_MISSING_WORDS());
$articles = find_articles($db, $langs, $words);
return array(200, ['articles' => $articles]);
}
# search -- return various kinds of information related to given keywords
function search(object $db, array $langs)
{
$words = $_REQUEST['words'];
if (!isset($words)) return array(400, ERR_MISSING_WORDS());
$info = [
'@context' => ['@vocab' => NS_SEARCH_RESULTS],
'definitions' => [],
'articles' => []];
# A "word" is delimited by white space, or it is anything between quotes (")
$wordlist = preg_split('/[,;\s]*"([^"]+)"[,;\s]*|[,;\s]+/', $words, 0,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
# See if we have definitions for the words.
foreach ($wordlist as $word)
array_push($info['definitions'], ...find_definitions($db, $langs, $word));
# See if there are online articles with any of the words.
$text = '"' . implode('" OR "', $wordlist) . '"';
array_push($info['articles'], ...find_articles($db, $langs, $text));
return array(200, $info);
}
# definitions -- return the definitions of a given term
function definitions(object $db, array $langs)
{
$term = $_REQUEST['term'];
if (!isset($term)) return array(400, ERR_MISSING_TERM());
$defs = find_definitions($db, $langs, $term);
return array(200, ['definitions' => $defs]);
}
# gdpr -- given a number ("30(1)(g)") return that article/clause from the GDPR
function gdpr(object $db, array $langs)
{
# TODO: Also handle sections from the preamble.
$results = [];
$number = $_REQUEST['article'];
if (!isset($number))
return array(400, ERR_MISSING_ARTICLE());
if (!preg_match('/^\s*(r?\d+)(?:\((\d+)\)(?:\((\w)\))?)?\s*$/', $number, $m))
return array(400, ERR_INVALID_ARTICLE());
# Create query based on whether articles, clauses or sub-clauses are desired.
$s = 'SELECT language, article, clause, subclause, eli, text FROM gdpr
WHERE language = :l AND article = :a';
if (isset($m[2])) $s .= ' AND clause = :c';
if (isset($m[3])) $s .= ' AND subclause = :s';
$s .= ' ORDER BY clause, subclause';
$stmt = $db->prepare($s);
# Try the preferred languages until one succeeds.
for ($i = 0; $results == [] && $i < count($langs); $i++) {
$stmt->bindValue(':l', $langs[$i], PDO::PARAM_STR);
$stmt->bindValue(':a', $m[1], PDO::PARAM_STR);
if (isset($m[2])) $stmt->bindValue(':c', $m[2], PDO::PARAM_INT);
if (isset($m[3])) $stmt->bindValue(':s', $m[3], PDO::PARAM_STR);
$stmt->execute();
while (($row = $stmt->fetch())) {
$n = $row['article'];
if ($row['clause']) $n .= '(' . $row['clause'] . ')';
if ($row['subclause']) $n .= '(' . $row['subclause'] . ')';
$results[] = [
'@context' => [
'@language' => $row['language'],
'@vocab' => NS_GDPR ],
'n' => $n,
'eli' => $row['eli'],
'text' => $row['text'] ];
}
}
if ($results == [])
return array(400, ERR_NO_SUCH_ARTICLE());
else
return array(200, $results);
}
# dpa -- return the address of a DPA, by country code or partial name
function dpa(object $db, array $langs)
{
$results = [];
$country = $_REQUEST['country'] ?? '';
$partialname = $_REQUEST['name'] ?? '';
# Create a SQL query.
# Note that parameters are used twice in a query. This only works
# when PDO::ATTR_EMULATE_PREPARES is set on the database handle.
if (!empty($country)) {
$stmt = $db->prepare('SELECT language, country, name, address, tel, fax,
email, url, id, modified FROM dpa WHERE lower(country) = lower(:country)
AND (language = :language OR (language = "en" AND
NOT EXISTS (SELECT * FROM dpa WHERE lower(country) = lower(:country)
AND language = :language)))');
} else if (!empty($partialname)) {
$stmt = $db->prepare('SELECT language, country, name, address, tel, fax,
email, url, id, modified FROM dpa WHERE name LIKE :partialname
AND (language = :language OR (language = "en" AND
NOT EXISTS (SELECT * FROM dpa WHERE name LIKE :partialname
AND language = :language)))');
} else { # Return addresses in English of all DPAs
$stmt = $db->prepare('SELECT language, country, name, address, tel, fax,
email, url, id, modified FROM dpa WHERE language = "en"');
}
# Try the preferred languages until one succeeds.
$langs[] = 'en'; # Add English at the end
for ($i = 0; $results == [] && $i < count($langs); $i++) {
if (!empty($country)) {
$stmt->bindValue(':language', $langs[$i], PDO::PARAM_STR);
$stmt->bindValue(':country', $country, PDO::PARAM_STR);
} else if (!empty($partialname)) {
$stmt->bindValue(':language', $langs[$i], PDO::PARAM_STR);
$stmt->bindValue(':partialname', "%$partialname%", PDO::PARAM_STR);
}
$res = $stmt->execute();
while (($row = $stmt->fetch())) {
$results[] = [
'@context' => [
'@language' => $row['language'],
'@vocab' => SCHEMA_ORG,
'country' => '@addressCountry',
'address' => '@streetAddress',
'tel' => '@telephone',
'fax' => '@faxNumber',
'modified' => DC_VALID ],
'@type' => DPA,
'@id' => $row['id'],
'country' => $row['country'],
'name' => $row['name'],
'address' => $row['address'],
'tel' => $row['tel'],
'fax' => $row['fax'],
'email' => $row['email'],
'url' => $row['url'],
'modified' => $row['modified'] ];
}
}
if ($results == [])
return array(400, ERR_NO_SUCH_DPA());
else
return array(200, $results);
}
# dpv -- return information about a term from the DPV vocabulary
function dpv(object $db, array $langs)
{
$term = $_REQUEST['term'];
if (!isset($term)) return array(400, ERR_MISSING_DPV_TERM());
# Find the term and the creation date. If the term is not a full
# URL, try with the DPV, DPV-PD and DPV_GDPR namespaces.
$stmt = $db->prepare('SELECT term, created FROM dpv_terms WHERE term = :t');
if (preg_match('/^[a-z]+:/i', $term)) {
$res = $stmt->execute([':t' => DPV . $term]);
$row = $stmt->fetch();
} else {
foreach ([DPV, DPV_PD, DPV_GDPR] as $ns) {
$res = $stmt->execute([':t' => $ns . $term]);
$row = $stmt->fetch();
if ($row) {$term = $ns . $term; break;}
}
}
if (! $row) return array(400, ERR_NO_SUCH_DPV());
$created = $row['created'];
# Get the list of sources from the dpv_sources table.
$sources = [];
$stmt = $db->prepare('SELECT source FROM dpv_sources WHERE term = :t');
$res = $stmt->execute([':t' => $term]);
while (($row = $stmt->fetch()))
$sources[] = ['@id' => $row['source']];
# Get the list of related terms from the dpv_related table.
$related = [];
$stmt = $db->prepare('SELECT related FROM dpv_related WHERE term = :t');
$res = $stmt->execute([':t' => $term]);
while (($row = $stmt->fetch()))
$related[] = ['@id' => $row['related']];
# Get the list of creators from the dpv_creators table.
$creators = [];
$stmt = $db->prepare('SELECT creator FROM dpv_creators WHERE term = :t');
$res = $stmt->execute([':t' => $term]);
while (($row = $stmt->fetch()))
$creators[] = ['@value' => $row['creator']];
# Get the definition in the requested language from the dpv_definitions table.
$definitions = [];
$stmt = $db->prepare('SELECT language, definition FROM dpv_definitions
WHERE term = :t AND language = :l');
for ($i = 0; $definitions == [] && $i < count($langs); $i++) {
$res = $stmt->execute([':t' => $term, ':l' => $langs[$i]]);
while (($row = $stmt->fetch())) {
$definitions[] = [
'@language' => $row['language'],
'@value' => $row['definition'] ];
}
}
# Get the notes in the requested language from the dpv_notes table.
$notes = [];
$stmt = $db->prepare('SELECT language, note FROM dpv_notes
WHERE term = :t AND language = :l');
for ($i = 0; $notes == [] && $i < count($langs); $i++) {
$res = $stmt->execute([':t' => $term, ':l' => $langs[$i]]);
while (($row = $stmt->fetch()))
$notes[] = ['@language' => $row['language'], '@value' => $row['note']];
}
# Get the human-readable name in the requested language from the
# dpv_labels table.
$labels = [];
$stmt = $db->prepare('SELECT language, label FROM dpv_labels
WHERE term = :t AND language = :l');
for ($i = 0; $labels == [] && $i < count($langs); $i++) {
$res = $stmt->execute([':t' => $term, ':l' => $langs[$i]]);
while (($row = $stmt->fetch()))
$labels[] = ['@language' => $row['language'], '@value' => $row['label']];
}
# Get the status in the requested language from the dpv_statuses
# table.
$statuses = [];
$stmt = $db->prepare('SELECT language, status FROM dpv_statuses
WHERE term = :t AND language = :l');
for ($i = 0; $statuses == [] && $i < count($langs); $i++) {
$res = $stmt->execute([':t' => $term, ':l' => $langs[$i]]);
while (($row = $stmt->fetch()))
$statuses[] = ['@language'=>$row['language'], '@value'=>$row['status']];
}
# Get the list of supertypes from the dpv_supertypes table.
$supertypes = [];
$stmt = $db->prepare('SELECT supertype FROM dpv_supertypes WHERE term = :t');
$res = $stmt->execute([':t' => $term]);
while (($row = $stmt->fetch()))
$supertypes[] = ['@value' => $row['supertype']];
# Get the list of vocabularies defining $term from the dpv_vocabs table.
$vocabs = [];
$stmt = $db->prepare('SELECT vocab FROM dpv_vocabs WHERE term = :t');
$res = $stmt->execute([':t' => $term]);
while (($row = $stmt->fetch()))
$vocabs[] = ['@id' => $row['vocab']];
$result['@id'] = $term;
$result['@type'] = [SKOS_CONCEPT, DPV_CONCEPT];
$result[DC_CREATED] = [ ['@type' => SCHEMA_DATE, '@value' => $created] ];
if ($creators) $result[DC_CREATOR] = $creators;
if ($sources) $result[DC_SOURCE] = $sources;
if ($vocabs) $result[RDFS_ISDEFINEDBY] = $vocabs;
if ($statuses) $result[SW_TERMSTATUS] = $statuses;
if ($supertypes) $result[SKOS_BROADER] = $supertypes;
if ($definitions) $result[SKOS_DEFINITION] = $definitions;
if ($vocabs) $result[SKOS_INSCHEME] = $vocabs;
if ($labels) $result[SKOS_PREFLABEL] = $labels;
if ($supertypes) $result[DPV_ISSUBTYPEOF] = $supertypes;
if ($notes) $result[SKOS_NOTE] = $notes;
if ($related) $result[SKOS_RELATED] = $related;
return array(200, [ $result ]);
}
# threat -- return information about a set of threats
function threat(object $db, array $langs)
{
$categories = $_REQUEST['category'];
$results = [];
# Get the description and actions for each category.
foreach ($categories as $category) {
# Get the description of this threat category.
$stmt = $db->prepare('SELECT language, description
FROM threat_verdict_category_info
WHERE verdict_category = :c AND language = :l');
# Try the preferred languages until one succeeds.
$description = '';
for ($i = 0; $description == '' && $i < count($langs); $i++) {
$stmt->bindValue(':c', $category, PDO::PARAM_STR);
$stmt->bindValue(':l', $langs[$i], PDO::PARAM_STR);
$res = $stmt->execute();
if (($row = $stmt->fetch())) {
$language = $row['language'];
$description = $row['description'];
}
}
# Get the actions for this threat category, their priorities and
# their descriptions, into an array $actions.
$stmt = $db->prepare(
'SELECT t.sequence, a.priority, a.language, a.description
FROM threat_resolution_actions AS t, threat_action_info AS a
WHERE t.verdict_category = :c AND t.action = a.action AND a.language = :l
ORDER BY t.sequence');
# Try the preferred languages until one succeeds.
$actions = [];
for ($i = 0; $actions == [] && $i < count($langs); $i++) {
$stmt->bindValue(':c', $category, PDO::PARAM_STR);
$stmt->bindValue(':l', $langs[$i], PDO::PARAM_STR);
$res = $stmt->execute();
while (($row = $stmt->fetch()))
if ($row['language'] == $language)
$actions[] = [
'priority' => $row['priority'],
'description' => $row['description'] ];
else # Not the same language as the threat description
$actions[] = [
'@context' => ['@language' => $row['language']],
'priority' => $row['priority'],
'description' => $row['description'] ];
}
$results[] = [
'@context' => [
'@vocab' => NS_THREAT_INFO,
'@language' => $language ],
'category' => $category,
'description' => $description,
'actions' => $actions ];
}
return array(200, $results);
}
# controller -- return information about a controller identified by id
function controller(object $db, array $langs)
{
if (!isset($_REQUEST['id'])) return array(400, ERR_MISSING_CONTROLLER_ID());
$id = $_REQUEST['id'];
# Get all information for the controller except the logo.
$stmt = $db->prepare('SELECT name, telephone, fax_number, email, url,
locality, postal_code, address FROM controllers WHERE id = :i');
$res = $stmt->execute([':i' => $id]);
if (! ($row = $stmt->fetch()))
return array(400, ERR_NO_SUCH_CONTROLLER());
$results = [
'@context' => SCHEMA_ORG,
'@type' => 'Organization',
'@id' => $id,
'name' => $row['name'],
'telephone' => $row['telephone'] ?? '',
'faxNumber' => $row['fax_number'] ?? '',
'email' => $row['email'] ?? '',
'url' => $row['url'] ?? '',
'address' => [
'@type' => 'PostalAddress',
'addressLocality' => $row['locality'] ?? '',
'postalCode' => $row['postal_code'] ?? '',
'streetAddress' => $row['address'] ?? '' ] ];
# Find the employees of this controller.
$employees = [];
$stmt = $db->prepare('SELECT name, job_title FROM controller_employees
WHERE controller = :i');
$res = $stmt->execute([':i' => $id]);
while (($row = $stmt->fetch()))
$employees[] = [
'@type' => 'Person',
'name' => $row['name'] ?? '',
'jobTitle' => $row['job_title'] ?? '' ];
$results['employee'] = $employees;
return array(200, $results);
}
# logo -- return the logo of a controller identified by id
function logo(object $db, array $langs)
{
if (!isset($_REQUEST['id'])) return array(400, ERR_MISSING_CONTROLLER_ID());
$id = $_REQUEST['id'];
$stmt = $db->prepare('SELECT logo FROM controllers WHERE id = :i');
$res = $stmt->execute([':i' => $id]);
if (! ($row = $stmt->fetch()))
return array(400, ERR_NO_CONTROLLER_LOGO());
else
return array(200, $row['logo']);
}
# status -- return some information about the service
function status(object $db, array $langs)
{
return array(200, ['status' => [
'langs' => $langs,
'cwd' => getcwd()]]);
}
# testform -- return an HTML form with a minimal user interface
function testform(object $db, array $langs)
{
# Get the list of known threat categories from the database.
$categories = '';
$stmt = $db->prepare('SELECT verdict_category
FROM threat_verdict_category_info
ORDER by verdict_category');
$res = $stmt->execute();
while (($row = $stmt->fetch()))
$categories .= '<option>' . htmlspecialchars($row['verdict_category']);
# Get some examples of controller IDs
$controllers = 'e.g.';
$stmt = $db->prepare('SELECT id FROM controllers LIMIT 5');
$res = $stmt->execute();
while (($row = $stmt->fetch()))
$controllers .= ', ' . htmlspecialchars($row['id']);
return array(202, '<!DOCTYPE html>
<html lang=en>
<title>TRAPEZE knowledge base test</title>
<style>
body {background: #fff; color: black; margin: 3em 5% 6em;
font-family: Arial, sans-serif}
form {border: solid thin; border-radius: 0.5em; padding: 1em 1em 0.5em 1em;
margin: 3em 0; /*box-shadow: 0 2px 4px #AAA*/}
h1, h2 {font-family: Archivo Black, Arial Black, Arial, sans-serif;
font-weight: 900}
h2 {line-height: 1.5; display: inline; background: 0 0.62em / 100% 0.4em
no-repeat linear-gradient(to bottom, #EED216, #EED216)}
</style>
<h1>TRAPEZE knowledge base test</h1>
<p>Use these forms to query the knowledge base.
<form action="">
<input type=hidden name=action value=definitions>
<h2><span>Search definitions of terms</span></h2>
<p><label>Accept-Language: <input name=lang
title="Zero or more comma-separated language codes
such as it, en, nl, fr or de"></label>
<label>Term: <input name=term></label> <input type=submit value=Submit></p>
</form>
<form action="">
<input type=hidden name=action value=gdpr>
<h2><span>Search GDPR articles by number</span></h2>
<p><label>Accept-Language: <input name=lang
title="Zero or more comma-separated language codes
such as it, en, nl, fr or de"></label>
<label>Article: <input name=article></label> <input type=submit value=Submit>
</form>
<form action="">
<input type=hidden name=action value=dpa>
<h2><span>Search DPAs by country</span></h2>
<p><label>Accept-Language: <input name=lang
title="Zero or more comma-separated language codes
such as it, en, nl, fr or de"></label>
<label>Country code: <input name=country></label> <input type=submit value=Submit>
</form>
<form action="">
<input type=hidden name=action value=dpa>
<h2><span>Search DPAs by name</span></h2>
<p><label>Accept-Language: <input name=lang
title="Zero or more comma-separated language codes
such as it, en, nl, fr or de"></label>
<label>(Partial) name: <input name=name></label> <input type=submit value=Submit>
</form>
<form action="">
<input type=hidden name=action value=articles>
<h2><span>Search articles by words from the title or abstract</span></h2>
<p><label>Accept-Language: <input name=lang
title="Zero or more comma-separated language codes
such as it, en, nl, fr or de"></label>
<label>Words: <input name=words title="May use NEAR(…), AND, OR, NOT and …*."></label> <input type=submit value=Submit></p>
</form>
<form action="">
<input type=hidden name=action value=dpv>
<h2><span>Search the DPV vocabulary</span></h2>
<p><label>Accept-Language: <input name=lang
title="Zero or more comma-separated language codes
such as it, en, nl, fr or de"></label>
<label>Term: <input name=term></label> <input type=submit value=Submit>
</form>
<form action="">
<input type=hidden name=action value=search>
<h2><span>Search by keywords</span></h2>
<p><label>Accept-Language: <input name=lang
title="Zero or more comma-separated language codes
such as it, en, nl, fr or de"></label>
<label>Keywords: <input name=words></label> <input type=submit value=Submit>
</form>
<form action="">
<input type=hidden name=action value=threat>
<h2><span>Explain threats</span></h2>
<p><label>Accept-Language: <input name=lang
title="Zero or more comma-separated language codes
such as it, en, nl, fr or de"></label>
<label>Threat categories: <select multiple name="category[]">
' . $categories . '
</select> <input type=submit value=Submit>
</form>
<form action="">
<input type=hidden name=action value=controller>
<h2><span>Look up a controller</span></h2>
<p><label>Accept-Language: <input name=lang
title="Zero or more comma-separated language codes
such as it, en, nl, fr or de"></label>
<label>ID: <input name=id
title="' . $controllers . '"></label>
<input type=submit value=Submit>
</form>
<form action="">
<input type=hidden name=action value=logo>
<h2><span>Look up the logo of a controller</span></h2>
<p><p><label>Accept-Language: <input name=lang
title="Zero or more comma-separated language codes
such as it, en, nl, fr or de"></label>
<label>ID: <input name=id
title="' . $controllers . '"></label>
<input type=submit value=Submit>
</form>
');
}
# usage -- return an error message explaining how to use this service
function usage(array $langs)
{
return array(400, ERR_USAGE());
}
# main
# Check what languages the client prefers. Use the "lang" parameter if
# given, otherwise the Accept-Language headers if it is present, and
# fall back to "en" (English).
$langs = get_languages(!empty($_REQUEST['lang']) ? $_REQUEST['lang'] :
(!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] :
'en'));
# Set up localization of error messages according to the client's languages.
# If that fails (PHP was not compiled with libintl), make _() a no-op.
try {
$domain = 'kb';
bindtextdomain($domain, './locale'); # Find message files under this directory
textdomain($domain); # Base name of translated message files
bind_textdomain_codeset($domain, 'UTF-8');
putenv('LANGUAGE=' . implode(':', $langs));
} catch (Throwable $e) {
function _($s) {return $s;}
}
# Connect to our database, then dispatch the request to the appropriate handler.
try {
$db = new PDO(DSN);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
switch ($_REQUEST['action'] ?? '') {
case 'search': list($status, $result) = search($db, $langs); break;
case 'definitions': list($status, $result) = definitions($db, $langs);break;
case 'gdpr': list($status, $result) = gdpr($db, $langs); break;
case 'dpa': list($status, $result) = dpa($db, $langs); break;
case 'status': list($status, $result) = status($db, $langs); break;
case 'articles': list($status, $result) = articles($db, $langs); break;
case 'dpv': list($status, $result) = dpv($db, $langs); break;
case 'threat': list($status, $result) = threat($db, $langs); break;
case 'controller': list($status, $result) = controller($db, $langs); break;
case 'logo': list($status, $result) = logo($db, $langs); break;
case 'debug': list($status, $result) = testform($db, $langs); break;
default: list($status, $result) = usage($langs);
}
} catch (PDOException $e) {
$status = 500;
$result = ERR_DATABASE();
}
# Return the result, either an error message in HTML (if $status is
# not 200), a bit of JSON (if $result is an array), or data in some
# other media type (if $result is a data URL).
if ($status != 200) {
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status);
header('Access-Control-Allow-Origin: ' . ($_SERVER['HTTP_ORIGIN'] ?? '*'));
header('Vary: Origin');
header('Content-Type: text/html;charset=utf-8');
echo $result;
} elseif (is_array($result)) {
header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
header('Access-Control-Allow-Origin: ' . ($_SERVER['HTTP_ORIGIN'] ?? '*'));
header('Vary: Origin');
header('Content-Type: application/json');
echo json_encode($result, JSON_UNESCAPED_UNICODE);
} elseif (preg_match('/^data:([^;,]+);base64,(.*)$/', $result, $matches)) {
header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
header('Access-Control-Allow-Origin: ' . ($_SERVER['HTTP_ORIGIN'] ?? '*'));
header('Vary: Origin');
header('Content-Type: ' . $matches[1]);
echo base64_decode($matches[2]);
} else {
header($_SERVER['SERVER_PROTOCOL'] . ' 500');
header('Access-Control-Allow-Origin: ' . ($_SERVER['HTTP_ORIGIN'] ?? '*'));
header('Vary: Origin');
header('Content-Type: text/html;charset=utf-8');
echo '<p>Software bug!';
}