Repository navigation
Expand file tree
/
Copy pathrestore.php
More file actions
450 lines (422 loc) · 15.2 KB
/
Copy pathrestore.php
File metadata and controls
450 lines (422 loc) · 15.2 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
<?php
declare(strict_types=1);
// Basic configuration defaults (kept in sync conceptually with scan.php)
if (!defined('ACCESS_BITRIX')) {
define('ACCESS_BITRIX', true);
}
if (!defined('ACCESS_PASSWORD')) {
define('ACCESS_PASSWORD', '123456');
}
if (!defined('DEBUG_MODE')) {
define('DEBUG_MODE', false);
}
/**
* Renders a Bootstrap-based password login page and exits.
*
* @param string|null $errorMessage Optional error message to display above the form.
* @return void
*/
function renderPasswordForm(?string $errorMessage = null): void
{
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Access required</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
<div class="row justify-content-center">
<div class="col-md-4">
<div class="card shadow-sm">
<div class="card-body">
<h1 class="h4 mb-3 text-center">Enter password</h1>
<?php if ($errorMessage !== null): ?>
<div class="alert alert-danger py-2 mb-3">
<?=htmlspecialchars($errorMessage, ENT_QUOTES, 'UTF-8')?>
</div>
<?php endif; ?>
<form method="post">
<div class="mb-3">
<label for="access_password" class="form-label">Password</label>
<input
type="password"
name="access_password"
id="access_password"
class="form-control"
autocomplete="current-password"
required
>
</div>
<button type="submit" class="btn btn-primary w-100">Log in</button>
</form>
</div>
</div>
<p class="text-muted small mt-3 text-center">
Tip: change the ACCESS_PASSWORD constant in the script before using it on a real server.
</p>
</div>
</div>
</div>
</body>
</html>
<?php
exit;
}
/**
* Renders a blocking notice when the default password is still in use.
*
* @return void
*/
function renderDefaultPasswordWarning(): void
{
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Access blocked</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
<div class="row justify-content-center">
<div class="col-md-5">
<div class="card shadow-sm border-danger">
<div class="card-body">
<h1 class="h4 mb-3 text-center text-danger">Access blocked</h1>
<div class="alert alert-warning mb-0">
Please change the ACCESS_PASSWORD constant from the default value before using this tool.
</div>
</div>
</div>
<p class="text-muted small mt-3 text-center">
Update ACCESS_PASSWORD in restore.php and reload the page.
</p>
</div>
</div>
</div>
</body>
</html>
<?php
exit;
}
/**
* Authenticate user via Bitrix or password form.
*
* @return void
*/
function authenticateUser(): void
{
$docRoot = realpath($_SERVER['DOCUMENT_ROOT']) ?: $_SERVER['DOCUMENT_ROOT'];
$bitrixPrologPath = $docRoot ? $docRoot . '/bitrix/modules/main/include/prolog_before.php' : '';
$useBitrix = (defined('ACCESS_BITRIX') && ACCESS_BITRIX === true && $bitrixPrologPath && file_exists($bitrixPrologPath));
if ($useBitrix) {
require_once $bitrixPrologPath;
global $USER;
if (!$USER || !$USER->IsAdmin()) {
header('HTTP/1.1 403 Forbidden');
echo 'Access denied';
exit;
}
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
return;
}
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (ACCESS_PASSWORD === '123456') {
renderDefaultPasswordWarning();
}
if (empty($_SESSION['scan2json_authenticated']) || $_SESSION['scan2json_authenticated'] !== true) {
$errorMessage = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$password = $_POST['access_password'] ?? '';
if ($password === ACCESS_PASSWORD) {
$_SESSION['scan2json_authenticated'] = true;
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
$errorMessage = 'Invalid password.';
}
renderPasswordForm($errorMessage);
}
}
/**
* List available JSONL files in scan_tmp.
*
* @param string $scanTmpDir
* @return array<int, string>
*/
function getAvailableJsonlFiles(string $scanTmpDir): array
{
if (!is_dir($scanTmpDir)) {
return [];
}
$files = glob($scanTmpDir . '/*.jsonl');
if ($files === false) {
return [];
}
return array_map('basename', $files);
}
/**
* Normalize and validate relative path.
*
* @param string $path
* @return string|null
*/
function sanitizeRelativePath(string $path): ?string
{
$path = trim(str_replace(['\\', '//'], '/', $path));
$path = ltrim($path, '/');
if ($path === '' || str_contains($path, '..')) {
return null;
}
return $path;
}
/**
* Normalize a path without requiring it to exist.
*
* @param string $path
* @return string
*/
function normalizePath(string $path): string
{
$parts = [];
foreach (explode(DIRECTORY_SEPARATOR, str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path)) as $segment) {
if ($segment === '' || $segment === '.') {
continue;
}
if ($segment === '..') {
array_pop($parts);
continue;
}
$parts[] = $segment;
}
return DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $parts);
}
/**
* Check if full path stays inside base.
*
* @param string $baseDir
* @param string $fullPath
* @return bool
*/
function isPathInsideBase(string $baseDir, string $fullPath): bool
{
$baseReal = realpath($baseDir);
if ($baseReal === false) {
return false;
}
$candidate = normalizePath($fullPath);
$baseNormalized = rtrim(normalizePath($baseReal), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
return str_starts_with($candidate . DIRECTORY_SEPARATOR, $baseNormalized);
}
/**
* Restore files from JSONL snapshot.
*
* @param string $sourceFile
* @param string $targetDir
* @param bool $dryRun
* @param bool $overwrite
* @return array<string, int>
*/
function restoreFromJsonl(string $sourceFile, string $targetDir, bool $dryRun, bool $overwrite): array
{
$counters = [
'totalLines' => 0,
'validRecords' => 0,
'created' => 0,
'overwritten' => 0,
'skipped' => 0,
'invalid' => 0,
'errors' => 0,
];
$handle = fopen($sourceFile, 'rb');
if ($handle === false) {
throw new RuntimeException('Unable to open source file');
}
$baseReal = realpath($targetDir);
if ($baseReal === false && !$dryRun) {
if (!mkdir($targetDir, 0775, true) && !is_dir($targetDir)) {
fclose($handle);
throw new RuntimeException('Unable to create target directory');
}
$baseReal = realpath($targetDir);
}
if ($baseReal === false) {
$baseReal = $targetDir;
}
while (($line = fgets($handle)) !== false) {
$counters['totalLines']++;
$line = trim($line);
if ($line === '') {
continue;
}
$record = json_decode($line, true);
if (!is_array($record) || !isset($record['file'], $record['content']) || !is_string($record['file']) || !is_string($record['content'])) {
$counters['invalid']++;
continue;
}
$sanitized = sanitizeRelativePath($record['file']);
if ($sanitized === null) {
$counters['invalid']++;
continue;
}
$fullPath = $baseReal . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $sanitized);
if (!isPathInsideBase($baseReal, $fullPath)) {
$counters['invalid']++;
continue;
}
$counters['validRecords']++;
if ($dryRun) {
if (file_exists($fullPath)) {
$overwrite ? $counters['overwritten']++ : $counters['skipped']++;
} else {
$counters['created']++;
}
continue;
}
$dirName = dirname($fullPath);
if (!is_dir($dirName) && !mkdir($dirName, 0775, true) && !is_dir($dirName)) {
$counters['errors']++;
continue;
}
if (file_exists($fullPath)) {
if (!$overwrite) {
$counters['skipped']++;
continue;
}
$written = file_put_contents($fullPath, $record['content']);
if ($written === false) {
$counters['errors']++;
} else {
$counters['overwritten']++;
}
} else {
$written = file_put_contents($fullPath, $record['content']);
if ($written === false) {
$counters['errors']++;
} else {
$counters['created']++;
}
}
}
fclose($handle);
return $counters;
}
authenticateUser();
$docRoot = realpath($_SERVER['DOCUMENT_ROOT']) ?: $_SERVER['DOCUMENT_ROOT'];
$scanTmpDir = $docRoot . '/scan_tmp';
$availableFiles = getAvailableJsonlFiles($scanTmpDir);
$message = '';
$messageType = 'info';
$resultCounters = null;
$selectedFile = $_POST['source_file'] ?? '';
$customFile = trim($_POST['source_file_custom'] ?? '');
$targetDirInput = trim($_POST['target_dir'] ?? 'restored_project');
$dryRun = isset($_POST['dry_run']);
$overwrite = isset($_POST['overwrite']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sourcePath = '';
if ($customFile !== '') {
$sourcePath = $customFile;
} elseif ($selectedFile !== '') {
$sourcePath = $scanTmpDir . '/' . $selectedFile;
}
if ($sourcePath === '') {
$message = 'Source JSONL file is required.';
$messageType = 'danger';
} elseif (!is_file($sourcePath) || !is_readable($sourcePath)) {
$message = 'Source file not found or unreadable.';
$messageType = 'danger';
} else {
$targetDirInput = trim($targetDirInput, " \\/");
if ($targetDirInput === '' || str_contains($targetDirInput, '..')) {
$message = 'Invalid target directory.';
$messageType = 'danger';
} else {
$targetDir = $docRoot . DIRECTORY_SEPARATOR . $targetDirInput;
if (!isPathInsideBase($docRoot, $targetDir . DIRECTORY_SEPARATOR . 'dummy')) {
$message = 'Target directory must be under DOCUMENT_ROOT.';
$messageType = 'danger';
} else {
try {
$resultCounters = restoreFromJsonl($sourcePath, $targetDir, $dryRun, $overwrite);
$messageType = ($resultCounters['errors'] === 0 && $resultCounters['invalid'] === 0) ? 'success' : 'warning';
$message = 'Restore completed.';
} catch (RuntimeException $e) {
$message = $e->getMessage();
$messageType = 'danger';
}
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Project Restore from JSONL</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-4">
<h1 class="mb-3">Project Restore from JSONL</h1>
<p class="text-muted">Reconstruct files from a JSONL snapshot produced by scan.php. Files will be recreated under the selected target directory inside DOCUMENT_ROOT.</p>
<?php if ($message !== ''): ?>
<div class="alert alert-<?=$messageType?>">
<?=htmlspecialchars($message, ENT_QUOTES, 'UTF-8')?>
<?php if ($resultCounters): ?>
<div class="mt-2 small">
<div>Total lines: <?=$resultCounters['totalLines']?></div>
<div>Valid records: <?=$resultCounters['validRecords']?></div>
<div>Created: <?=$resultCounters['created']?></div>
<div>Overwritten: <?=$resultCounters['overwritten']?></div>
<div>Skipped: <?=$resultCounters['skipped']?></div>
<div>Invalid: <?=$resultCounters['invalid']?></div>
<div>Errors: <?=$resultCounters['errors']?></div>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<form method="post" class="card card-body">
<div class="mb-3">
<label class="form-label">Source JSONL (from scan_tmp)</label>
<select name="source_file" class="form-select">
<option value="">-- Select a file --</option>
<?php foreach ($availableFiles as $f): ?>
<option value="<?=htmlspecialchars($f, ENT_QUOTES, 'UTF-8')?>" <?=($f === $selectedFile) ? 'selected' : ''?>><?=$f?></option>
<?php endforeach; ?>
</select>
<div class="form-text">Or specify a relative path manually below.</div>
</div>
<div class="mb-3">
<label class="form-label">Custom source path (relative or absolute)</label>
<input type="text" name="source_file_custom" class="form-control" value="<?=htmlspecialchars($customFile, ENT_QUOTES, 'UTF-8')?>">
</div>
<div class="mb-3">
<label class="form-label">Target directory (under DOCUMENT_ROOT)</label>
<input type="text" name="target_dir" class="form-control" value="<?=htmlspecialchars($targetDirInput, ENT_QUOTES, 'UTF-8')?>" required>
<div class="form-text">Example: restored_project</div>
</div>
<div class="form-check mb-2">
<input class="form-check-input" type="checkbox" name="dry_run" id="dryRun" <?= $dryRun ? 'checked' : '' ?>>
<label class="form-check-label" for="dryRun">Dry run (simulate only)</label>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" name="overwrite" id="overwrite" <?= $overwrite ? 'checked' : '' ?>>
<label class="form-check-label" for="overwrite">Overwrite existing files</label>
</div>
<button type="submit" class="btn btn-primary">Start restore</button>
</form>
</div>
</body>
</html>