BlueGit

timfa 66wiki

Files

66wiki / web / dataIndex.php

dataIndex.php

json errors
timfa Tim Falken · pushed by timfa · 9 months ago
13c7c52c History
dataIndex.php 8.3 KiB Download Raw
1<?php
2ini_set('display_errors', '1');
3ini_set('display_startup_errors', '1');
4error_reporting(E_ALL);
5
6header('Content-Type: application/json; charset=utf-8');
7header('Access-Control-Allow-Origin: *');
8header('Access-Control-Allow-Methods: GET, HEAD, OPTIONS, POST');
9header('Access-Control-Allow-Headers: *');
10header('X-Robots-Tag: all');
11
12header('X-Content-Type-Options: nosniff');
13header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
14header('Pragma: no-cache');
15
16set_error_handler(function ($severity, $message, $file, $line) {
17 http_response_code(500);
18 echo json_encode([
19 'error' => 'PHP Error',
20 'severity' => $severity,
21 'message' => $message,
22 'file' => $file,
23 'line' => $line,
24 ], JSON_PRETTY_PRINT);
25 exit;
26});
27
28set_exception_handler(function ($e) {
29 http_response_code(500);
30 echo json_encode([
31 'error' => 'Uncaught Exception',
32 'type' => get_class($e),
33 'message' => $e->getMessage(),
34 'file' => $e->getFile(),
35 'line' => $e->getLine(),
36 'trace' => explode("\n", $e->getTraceAsString()),
37 ], JSON_PRETTY_PRINT);
38 exit;
39});
40
41
42require_once __DIR__ . '/folderNode.php';
43
44if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
45 http_response_code(204);
46 exit;
47}
48
49$dataRoot = __DIR__ . DIRECTORY_SEPARATOR . 'data';
50$chaptersRoot = $dataRoot . DIRECTORY_SEPARATOR . 'chapters';
51
52$allJson = loadAllJson($dataRoot);
53$visited = [];
54$baseUrl = getBaseUrl();
55
56$chaptersTree = loadFolderTree($chaptersRoot);
57$chapters = $chaptersTree->jsonRecursive();
58
59usort($chapters, fn($a, $b) => ($a->number ?? 0) <=> ($b->number ?? 0));
60
61foreach ($chapters as $chapterObj) {
62 $chapter = json_decode(json_encode($chapterObj), true);
63 $chapterLink = normalizeWikiPath($chapter['wikiPath'] ?? '');
64 $relPath = normalizeDataRelPath($chapterLink);
65 if ($relPath !== '')
66 $visited[$relPath] = true;
67}
68
69$index = [];
70foreach ($chapters as $chapterObj) {
71 $chapter = json_decode(json_encode($chapterObj), true);
72 $chapterLink = normalizeWikiPath($chapter['wikiPath'] ?? '');
73
74 $index[] = buildChapterNode($chapter, $chapterLink, $allJson, $visited, $baseUrl);
75}
76
77echo json_encode($index, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
78
79function loadAllJson(string $dataRoot): array
80{
81 $map = [];
82
83 $it = new RecursiveIteratorIterator(
84 new RecursiveDirectoryIterator($dataRoot, FilesystemIterator::SKIP_DOTS)
85 );
86
87 foreach ($it as $file) {
88 /** @var SplFileInfo $file */
89 if (strtolower($file->getExtension()) !== 'json')
90 continue;
91
92 $path = $file->getPathname();
93 $rel = str_replace('\\', '/', substr($path, strlen($dataRoot)));
94 if ($rel === '')
95 $rel = '/' . $file->getFilename();
96 if ($rel[0] !== '/')
97 $rel = '/' . $rel;
98
99 try {
100 $raw = file_get_contents($path);
101 if ($raw === false)
102 continue;
103 $json = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
104 if (!is_array($json))
105 continue;
106 } catch (Throwable $e) {
107 continue;
108 }
109
110 $json['_relPath'] = $rel;
111 $map[$rel] = $json;
112 }
113
114 return $map;
115}
116
117function buildChapterNode(array $chapter, string $chapterLink, array $allJson, array &$visited, string $baseUrl): array
118{
119 $name = $chapterLink !== '' ? basename($chapterLink, '.json') : ($chapter['name'] ?? 'chapter');
120 $fullChapterLink = $chapterLink !== '' ? $baseUrl . $chapterLink : '';
121
122 $node = [
123 'name' => $name,
124 'type' => $chapter['type'] ?? 'chapter',
125 'pageType' => 'page',
126 'link' => $fullChapterLink,
127 'children' => [],
128 ];
129
130 $folderIncludes = extractFolderIncludes($chapter, ['subheaders']);
131
132 $children = [];
133
134 foreach (($chapter['subheaders'] ?? []) as $subheader) {
135 if (!is_array($subheader))
136 continue;
137
138 $subNode = [
139 'name' => $subheader['name'] ?? 'subheader',
140 'type' => 'subheader',
141 'pageType' => 'page child element',
142 'link' => $fullChapterLink,
143 'children' => [],
144 ];
145
146 $subIncludes = extractFolderIncludes($subheader);
147 $subNode['children'] = mergeChildren(
148 buildChildrenFromFolderIncludes($subIncludes, $allJson, $visited, $baseUrl)
149 );
150
151 $children[] = $subNode;
152 }
153
154 $children = mergeChildren(
155 $children,
156 buildChildrenFromFolderIncludes($folderIncludes, $allJson, $visited, $baseUrl)
157 );
158
159 $node['children'] = $children;
160
161 return $node;
162}
163
164function buildChildrenFromFolderIncludes(array $folders, array $allJson, array &$visited, string $baseUrl): array
165{
166 $children = [];
167 $rels = array_keys($allJson);
168 sort($rels, SORT_NATURAL | SORT_FLAG_CASE);
169 foreach ($folders as $folder) {
170 $folderRel = '/' . trim(str_replace('\\', '/', $folder), '/');
171 foreach ($rels as $rel) {
172 if (str_starts_with($rel, $folderRel . '/')) {
173 $children[] = buildDataLinkNode($rel, '', $allJson, $visited, $baseUrl);
174 }
175 }
176 }
177
178 return $children;
179}
180
181function buildDataLinkNode(string $relPath, string $label, array $allJson, array &$visited, string $baseUrl): array
182{
183 $link = $baseUrl . '/data' . $relPath;
184 $json = $allJson[$relPath] ?? null;
185
186 $name = $label;
187 $type = 'linkedData';
188
189 if (is_array($json)) {
190 $type = $json['type'] ?? 'data';
191 if ($name === '') {
192 $name = $json['name'] ?? ($json['title'] ?? basename($relPath, '.json'));
193 }
194 }
195
196 $node = [
197 'name' => $name !== '' ? $name : basename($relPath, '.json'),
198 'type' => $type,
199 'pageType' => 'data link',
200 'link' => $link,
201 'children' => [],
202 ];
203
204 if (!is_array($json))
205 return $node;
206
207 if (isset($visited[$relPath]))
208 return $node;
209
210 $visited[$relPath] = true;
211
212 $folderChildren = buildChildrenFromFolderIncludes(extractFolderIncludes($json), $allJson, $visited, $baseUrl);
213 $node['children'] = mergeChildren($folderChildren);
214
215 return $node;
216}
217
218function normalizeWikiPath(string $path): string
219{
220 $path = str_replace('\\', '/', $path);
221 if ($path === '')
222 return '';
223
224 if (!str_starts_with($path, '/'))
225 $path = '/' . $path;
226
227 return $path;
228}
229
230function getBaseUrl(): string
231{
232 $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
233 $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
234 $scriptName = $_SERVER['SCRIPT_NAME'] ?? '/dataIndex.php';
235 $dir = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
236 return $scheme . '://' . $host . ($dir === '' ? '' : $dir);
237}
238
239function normalizeDataRelPath(string $path): string
240{
241 $path = trim($path);
242 if ($path === '')
243 return '';
244
245 $path = str_replace('\\', '/', $path);
246 if (str_starts_with($path, '/data/'))
247 $path = substr($path, strlen('/data'));
248 if (str_starts_with($path, 'data/'))
249 $path = substr($path, strlen('data'));
250
251 if (!str_starts_with($path, '/'))
252 $path = '/' . $path;
253
254 return $path;
255}
256
257function extractFolderIncludes(mixed $value, array $skipKeys = []): array
258{
259 $folders = [];
260
261 if (is_array($value)) {
262 foreach ($value as $k => $v) {
263 if (in_array($k, $skipKeys, true))
264 continue;
265 $folders = array_merge($folders, extractFolderIncludes($v, $skipKeys));
266 }
267 return $folders;
268 }
269
270 if (is_string($value)) {
271 return extractFolderIncludesFromString($value);
272 }
273
274 return $folders;
275}
276
277function extractFolderIncludesFromString(string $text): array
278{
279 $folders = [];
280 $pattern = '/\[\[\[\s*([a-zA-Z0-9_.-]+)\s*\]\]\]/';
281
282 if (preg_match_all($pattern, $text, $matches, PREG_SET_ORDER)) {
283 foreach ($matches as $m) {
284 $folders[] = $m[1];
285 }
286 }
287
288 return $folders;
289}
290
291function mergeChildren(array ...$groups): array
292{
293 $merged = [];
294 $seen = [];
295
296 foreach ($groups as $children) {
297 foreach ($children as $child) {
298 if (!is_array($child))
299 continue;
300
301 $key = ($child['link'] ?? '') . '|' . ($child['name'] ?? '') . '|' . ($child['pageType'] ?? '');
302 if (isset($seen[$key]))
303 continue;
304
305 $seen[$key] = true;
306 $merged[] = $child;
307 }
308 }
309
310 return $merged;
311}