-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgedcom_parser.php
More file actions
362 lines (331 loc) · 14.4 KB
/
Copy pathgedcom_parser.php
File metadata and controls
362 lines (331 loc) · 14.4 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
<?php
/**
* GEDCOM 5.5.1 parser.
* Returns ['individuals' => [...], 'families' => [...]]
*/
function parse_gedcom(string $filepath): array {
$fh = fopen($filepath, 'r');
if ($fh === false) return ['individuals' => [], 'families' => []];
// Detect charset from GEDCOM header (first 30 lines)
$charset = 'UTF-8';
$firstLine = true;
for ($i = 0; $i < 30 && ($peek = fgets($fh)) !== false; $i++) {
if ($firstLine && strncmp($peek, "\xEF\xBB\xBF", 3) === 0) {
$peek = substr($peek, 3);
}
$firstLine = false;
if (preg_match('/^1\s+CHAR\s+(\S+)/', rtrim($peek), $m)) {
$cs = strtoupper(trim($m[1]));
if (in_array($cs, ['ANSI', 'ANSEL', 'WINDOWS-1252', 'CP1252'])) {
$charset = 'Windows-1252';
} elseif (in_array($cs, ['ISO-8859-1', 'LATIN1', 'LATIN-1'])) {
$charset = 'ISO-8859-1';
}
break;
}
}
rewind($fh);
$individuals = [];
$families = [];
$notes = [];
$ctx = null; // 'INDI' | 'FAM' | 'NOTE'
$id = null;
$rec = [];
$l1 = null; // current level-1 tag
$last_text_key = null;
$firstLine = true;
$flush = function() use (&$individuals, &$families, &$notes, &$ctx, &$id, &$rec) {
if (!$ctx || !$id) return;
if ($ctx === 'INDI') $individuals[$id] = $rec;
elseif ($ctx === 'FAM') $families[$id] = $rec;
elseif ($ctx === 'NOTE') $notes[$id] = $rec['_text'] ?? '';
};
$ev = fn() => ['date' => '', 'place' => ''];
while (($raw = fgets($fh)) !== false) {
$line = rtrim($raw, "\r\n");
if ($firstLine) {
if (strncmp($line, "\xEF\xBB\xBF", 3) === 0) {
$line = substr($line, 3);
}
$firstLine = false;
}
if ($charset !== 'UTF-8') {
$line = iconv($charset, 'UTF-8//TRANSLIT//IGNORE', $line);
if ($line === false) continue;
}
if ($line === '') continue;
if (!preg_match('/^(\d+)\s+(\S+)(?:\s+(.*))?$/', $line, $m)) continue;
$level = (int)$m[1];
$tag = $m[2];
$value = isset($m[3]) ? rtrim($m[3]) : '';
// CONT/CONC — append to the last text field we recorded
if ($tag === 'CONT' || $tag === 'CONC') {
if ($last_text_key !== null && $ctx === 'NOTE') {
$sep = $tag === 'CONT' ? "\n" : '';
$rec['_text'] = ($rec['_text'] ?? '') . $sep . $value;
} elseif ($last_text_key !== null && isset($rec[$last_text_key])) {
$sep = $tag === 'CONT' ? "\n" : '';
$rec[$last_text_key] .= $sep . $value;
}
continue;
}
// Level-0 record boundary
if ($level === 0) {
$flush();
$ctx = null; $id = null; $rec = []; $l1 = null; $last_text_key = null;
if (preg_match('/^@(.+)@$/', $tag, $im)) {
$id = $im[1];
// For level-0 xref records the value may be "TYPE inline-text"
// (e.g. "NOTE The actual text") — split so $ctx is just the type.
$spacePos = strpos($value, ' ');
$ctx = $spacePos !== false ? substr($value, 0, $spacePos) : $value;
$l0inline = $spacePos !== false ? substr($value, $spacePos + 1) : '';
if ($ctx === 'INDI') {
$rec = [
'id' => $id, 'name' => '',
'npfx' => '', 'givn' => '',
'nick' => '', 'spfx' => '',
'surn' => '', 'nsfx' => '',
'_given' => '', '_surn' => '',
'sex' => 'U',
'birth' => $ev(), 'death' => $ev(),
'burial' => $ev(), 'chr' => $ev(),
'occu' => '', 'reli' => '',
'resi' => '', 'note' => '',
'fams' => [], 'famc' => [],
'_note_refs' => [],
];
} elseif ($ctx === 'FAM') {
$rec = [
'id' => $id,
'husb' => '', 'wife' => '',
'children' => [],
'marr' => $ev(), 'div' => $ev(),
'note' => '',
];
} elseif ($ctx === 'NOTE') {
$rec = ['_text' => $l0inline];
$last_text_key = '_text';
}
}
continue;
}
if (!$ctx) continue;
// Unwrap @pointer@ values
$ptr = '';
if (preg_match('/^@(.+)@$/', $value, $pm)) $ptr = $pm[1];
// ── INDI ─────────────────────────────────────────────────────────
if ($ctx === 'INDI') {
if ($level === 1) {
$l1 = $tag;
$last_text_key = null;
switch ($tag) {
case 'NAME':
if (empty($rec['name'])) {
$rec['name'] = trim(str_replace('/', '', $value));
// Extract given name and surname from standard /Surname/ notation
if (preg_match('/^(.*?)\s*\/([^\/]*)\//u', $value, $nm)) {
$rec['_given'] = trim($nm[1]);
$rec['_surn'] = trim($nm[2]);
}
}
break;
case 'SEX': $rec['sex'] = $value; break;
case 'OCCU': $rec['occu'] = $value; $last_text_key = 'occu'; break;
case 'RELI': $rec['reli'] = $value; $last_text_key = 'reli'; break;
case 'RESI': $rec['resi'] = $value; $last_text_key = 'resi'; break;
case 'FAMS': if ($ptr) $rec['fams'][] = $ptr; break;
case 'FAMC': if ($ptr) $rec['famc'][] = $ptr; break;
case 'NOTE':
if ($ptr) {
$rec['_note_refs'][] = $ptr;
} else {
if ($rec['note'] !== '') $rec['note'] .= "\n";
$rec['note'] .= $value;
$last_text_key = 'note';
}
break;
}
} elseif ($level === 2) {
$last_text_key = null;
switch ($l1) {
case 'NAME':
switch ($tag) {
case 'NPFX': $rec['npfx'] = $value; break;
case 'GIVN': $rec['givn'] = $value; break;
case 'NICK': $rec['nick'] = $value; break;
case 'SPFX': $rec['spfx'] = $value; break;
case 'SURN': $rec['surn'] = $value; break;
case 'NSFX': $rec['nsfx'] = $value; break;
}
break;
case 'BIRT': case 'DEAT': case 'BURI': case 'CHR':
case 'BAPM': case 'CONF': case 'ADOP': case 'GRAD':
case 'RETI': case 'EMIG': case 'IMMI':
$ekey = ged_event_key($l1);
if (!isset($rec[$ekey])) $rec[$ekey] = $ev();
if ($tag === 'DATE') { $rec[$ekey]['date'] = $value; }
if ($tag === 'PLAC') { $rec[$ekey]['place'] = $value; }
if ($tag === 'AGE') { $rec[$ekey]['age'] = $value; }
break;
case 'RESI':
if ($tag === 'PLAC') { $rec['resi'] = $value; $last_text_key = 'resi'; }
if ($tag === 'DATE') $rec['resi_date'] = $value;
break;
}
}
// ── FAM ──────────────────────────────────────────────────────────
} elseif ($ctx === 'FAM') {
if ($level === 1) {
$l1 = $tag;
$last_text_key = null;
switch ($tag) {
case 'HUSB': if ($ptr) $rec['husb'] = $ptr; break;
case 'WIFE': if ($ptr) $rec['wife'] = $ptr; break;
case 'CHIL': if ($ptr) $rec['children'][] = $ptr; break;
case 'NOTE':
if (!$ptr) {
if ($rec['note'] !== '') $rec['note'] .= "\n";
$rec['note'] .= $value;
$last_text_key = 'note';
}
break;
}
} elseif ($level === 2) {
$last_text_key = null;
if ($l1 === 'MARR' || $l1 === 'DIV') {
$ekey = strtolower($l1 === 'MARR' ? 'marr' : 'div');
if ($tag === 'DATE') $rec[$ekey]['date'] = $value;
if ($tag === 'PLAC') $rec[$ekey]['place'] = $value;
}
}
}
}
fclose($fh);
$flush();
// Resolve @xref@ note pointers
foreach ($individuals as &$ind) {
foreach ($ind['_note_refs'] as $nref) {
if (isset($notes[$nref])) {
if ($ind['note'] !== '') $ind['note'] .= "\n";
$ind['note'] .= $notes[$nref];
}
}
unset($ind['_note_refs']);
// Build canonical display name from components
$hasStructure = $ind['givn'] || $ind['surn'] || $ind['_given'] || $ind['_surn'];
if ($hasStructure) {
$given = $ind['givn'] ?: $ind['_given'];
$surn = $ind['surn'] ?: $ind['_surn'];
$parts = array_filter([
$ind['npfx'],
$given,
$ind['nick'] ? '"' . $ind['nick'] . '"' : '',
$ind['spfx'],
$surn,
$ind['nsfx'],
]);
$built = trim(implode(' ', $parts));
} else {
$built = $ind['name']; // use full cleaned NAME value as-is
}
$ind['display_name'] = $built ?: '(Unknown)';
$ind['name'] = $ind['display_name'];
unset($ind['_given'], $ind['_surn']);
}
unset($ind);
return ['individuals' => $individuals, 'families' => $families];
}
/**
* Builds the slim index payload (names, links, birth/death dates only).
* This is what the browser loads on startup — no notes, places, or extra events.
*/
function build_slim_index(array $data): array {
$out_inds = [];
foreach ($data['individuals'] as $id => $ind) {
$out_inds[$id] = [
'id' => $id,
'name' => $ind['name'],
'surn' => $ind['surn'] ?? '',
'sex' => $ind['sex'],
'fams' => $ind['fams'],
'famc' => $ind['famc'],
'birth' => ['date' => $ind['birth']['date'] ?? ''],
'death' => ['date' => $ind['death']['date'] ?? ''],
];
}
$out_fams = [];
foreach ($data['families'] as $id => $fam) {
$out_fams[$id] = [
'id' => $id,
'husb' => $fam['husb'],
'wife' => $fam['wife'],
'children' => $fam['children'],
'marr' => ['date' => $fam['marr']['date'] ?? ''],
];
}
return ['individuals' => $out_inds, 'families' => $out_fams];
}
/**
* Returns the slim index from its own small cache file.
* On a cache hit this reads/decodes only the slim file — never the full one.
*/
function get_slim_index(string $filepath): array {
$cache_dir = __DIR__ . '/cache/';
$cache_key = md5(realpath($filepath) ?: $filepath);
$index_file = $cache_dir . $cache_key . '_index.json';
if (is_file($index_file) && filemtime($index_file) >= filemtime($filepath)) {
$json = file_get_contents($index_file);
if ($json !== false) {
$data = json_decode($json, true);
if (is_array($data)) return $data;
}
}
// Cache miss — parse and write both files, then return slim index
get_cached_gedcom($filepath);
$json = file_get_contents($index_file);
return $json ? (json_decode($json, true) ?: []) : [];
}
/**
* Returns full parsed GEDCOM data, using a file-based cache keyed on the .ged mtime.
* Also writes the slim index cache so get_slim_index() stays fast.
* The cache/ directory and its .htaccess are created automatically on first use.
*/
function get_cached_gedcom(string $filepath): array {
$cache_dir = __DIR__ . '/cache/';
$cache_key = md5(realpath($filepath) ?: $filepath);
$cache_file = $cache_dir . $cache_key . '.json';
$index_file = $cache_dir . $cache_key . '_index.json';
if (is_file($cache_file) && filemtime($cache_file) >= filemtime($filepath)) {
$json = file_get_contents($cache_file);
if ($json !== false) {
$data = json_decode($json, true);
if (is_array($data)) return $data;
}
}
$data = parse_gedcom($filepath);
if (!is_dir($cache_dir)) {
mkdir($cache_dir, 0755, true);
file_put_contents($cache_dir . '.htaccess',
"<IfModule mod_authz_core.c>\n Require all denied\n</IfModule>\n" .
"<IfModule !mod_authz_core.c>\n Order deny,allow\n Deny from all\n</IfModule>\n");
}
$oldUmask = umask(0177);
if (!file_put_contents($cache_file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE))) {
error_log('familytree: failed to write cache ' . $cache_file);
}
if (!file_put_contents($index_file, json_encode(build_slim_index($data), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_INVALID_UTF8_SUBSTITUTE))) {
error_log('familytree: failed to write slim index ' . $index_file);
}
umask($oldUmask);
return $data;
}
function ged_event_key(string $tag): string {
static $map = [
'BIRT' => 'birth', 'DEAT' => 'death', 'BURI' => 'burial',
'CHR' => 'chr', 'BAPM' => 'chr', 'CONF' => 'conf',
'ADOP' => 'adop', 'GRAD' => 'grad', 'RETI' => 'reti',
'EMIG' => 'emig', 'IMMI' => 'immi',
];
return $map[$tag] ?? strtolower($tag);
}