-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.php
More file actions
686 lines (576 loc) · 22.3 KB
/
Copy pathsetup.php
File metadata and controls
686 lines (576 loc) · 22.3 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
<?php
/**
* Portfolio Hub V2 - Setup Wizard
* Just upload and visit to get started!
*/
session_start();
// Check if already installed
$configFile = __DIR__ . '/config/config.php';
$isInstalled = file_exists($configFile) && filesize($configFile) > 500;
if ($isInstalled && !isset($_GET['reinstall'])) {
header('Location: /');
exit;
}
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['step'])) {
$_SESSION['setup'] = $_SESSION['setup'] ?? [];
$step = (int)$_POST['step'];
switch ($step) {
case 1: // Site Info
$_SESSION['setup']['site_title'] = trim($_POST['site_title'] ?? '');
$_SESSION['setup']['site_url'] = rtrim(trim($_POST['site_url'] ?? ''), '/');
$_SESSION['setup']['hero_text'] = trim($_POST['hero_text'] ?? '');
$_SESSION['setup']['hero_subtext'] = trim($_POST['hero_subtext'] ?? '');
break;
case 2: // Admin Account
$_SESSION['setup']['admin_email'] = trim($_POST['admin_email'] ?? '');
$_SESSION['setup']['admin_password'] = $_POST['admin_password'] ?? '';
break;
case 3: // Theme
$_SESSION['setup']['primary_color'] = $_POST['primary_color'] ?? '#6366f1';
$_SESSION['setup']['secondary_color'] = $_POST['secondary_color'] ?? '#8b5cf6';
break;
case 4: // Complete Setup
$result = completeSetup($_SESSION['setup']);
header('Content-Type: application/json');
if ($result) {
$_SESSION['setup_complete'] = true;
unset($_SESSION['setup']);
echo json_encode(['success' => true, 'redirect' => '/admin/login.php']);
} else {
echo json_encode(['success' => false, 'error' => 'Setup failed. Check data/setup-error.log']);
}
exit;
}
// Return JSON for AJAX
header('Content-Type: application/json');
echo json_encode(['success' => true]);
exit;
}
function completeSetup($data) {
// Create directories
$dirs = [
__DIR__ . '/config',
__DIR__ . '/data',
__DIR__ . '/uploads',
__DIR__ . '/backups',
];
foreach ($dirs as $dir) {
if (!is_dir($dir)) {
if (!mkdir($dir, 0775, true)) {
error_log("Failed to create directory: $dir");
return false;
}
}
}
// Determine if HTTPS
$sessionSecure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'true' : 'false';
// Create config file
$config = <<<PHP
<?php
/**
* Portfolio Hub Configuration
* Auto-generated by setup wizard
*/
return [
'APP_ENV' => 'production',
'APP_URL' => '{$data['site_url']}',
'APP_NAME' => '{$data['site_title']}',
'DB_PATH' => __DIR__ . '/../data/site.db',
'SESSION_SECURE' => $sessionSecure,
'SESSION_NAME' => 'portfolio_session',
'CSRF_TOKEN_NAME' => 'csrf_token',
'CSP_REPORT_ONLY' => false,
'CSP_REPORT_URI' => null,
'UPLOAD_MAX_MB' => 10,
'UPLOAD_PATH' => __DIR__ . '/../uploads',
'UPLOAD_ALLOWED_TYPES' => ['image/jpeg', 'image/png', 'image/webp'],
'IMAGE_QUALITY' => 75,
'IMAGE_SIZES' => [480, 768, 1080, 1440, 1920],
'IMAGE_ASPECT_RATIO' => 0.75,
'RATE_LIMIT_LOGIN' => 5,
'RATE_LIMIT_MEDIA' => 20,
'BACKUP_PATH' => __DIR__ . '/../backups',
'BACKUP_KEEP_DAYS' => 14,
'ANALYTICS_ID' => '',
'RESPECT_DNT' => true,
];
PHP;
if (!file_put_contents(__DIR__ . '/config/config.php', $config)) {
error_log("Failed to write config file");
return false;
}
// Initialize database
try {
require_once __DIR__ . '/app/bootstrap.php';
$db = getDatabase();
// Create tables
$db->exec("
CREATE TABLE IF NOT EXISTS tiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
blurb TEXT,
cta_label TEXT DEFAULT 'Visit',
target_url TEXT NOT NULL,
bg_media_id INTEGER,
accent_hex TEXT,
order_index INTEGER DEFAULT 0,
visible INTEGER DEFAULT 1,
publish_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (bg_media_id) REFERENCES media(id) ON DELETE SET NULL
)");
$db->exec("
CREATE TABLE IF NOT EXISTS media (
id INTEGER PRIMARY KEY AUTOINCREMENT,
original_name TEXT NOT NULL,
path_original TEXT NOT NULL,
path_webp TEXT NOT NULL,
width INTEGER,
height INTEGER,
sizes_json TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");
$db->exec("
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT CHECK(role IN ('admin', 'editor')) DEFAULT 'admin',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_login_at DATETIME
)");
$db->exec("
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
)");
$db->exec("
CREATE TABLE IF NOT EXISTS activity_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
action TEXT NOT NULL,
entity_type TEXT,
entity_id INTEGER,
details TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
)");
$db->exec("
CREATE TABLE IF NOT EXISTS rate_limits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");
// Create indexes
$db->exec("CREATE INDEX IF NOT EXISTS idx_tiles_visible ON tiles(visible, publish_at)");
$db->exec("CREATE INDEX IF NOT EXISTS idx_tiles_order ON tiles(order_index)");
$db->exec("CREATE INDEX IF NOT EXISTS idx_rate_limits_key ON rate_limits(key, created_at)");
// Create admin user
$passwordHash = password_hash($data['admin_password'], PASSWORD_ARGON2ID);
$stmt = $db->prepare("INSERT INTO users (email, password_hash, role) VALUES (?, ?, 'admin')");
$stmt->execute([$data['admin_email'], $passwordHash]);
// Insert settings
$settings = [
'site_title' => $data['site_title'],
'site_description' => 'Explore my work across multiple domains',
'hero_text' => $data['hero_text'],
'hero_subtext' => $data['hero_subtext'],
'brand_primary' => $data['primary_color'],
'brand_secondary' => $data['secondary_color'],
'autoplay_enabled' => '1',
'autoplay_interval' => '7',
'animation_speed' => 'normal',
'open_links_new_tab' => '0',
];
$stmt = $db->prepare("INSERT INTO settings (key, value) VALUES (?, ?)");
foreach ($settings as $key => $value) {
$stmt->execute([$key, $value]);
}
return true;
} catch (Exception $e) {
$errorMsg = date('Y-m-d H:i:s') . " - " . $e->getMessage() . "\n" . $e->getTraceAsString() . "\n\n";
@file_put_contents(__DIR__ . '/data/setup-error.log', $errorMsg, FILE_APPEND);
error_log("Database setup failed: " . $e->getMessage());
return false;
}
}
// Detect site URL
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$detectedUrl = "$protocol://$host";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Portfolio Hub - Setup Wizard</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.wizard-container {
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
width: 100%;
max-width: 600px;
overflow: hidden;
}
.wizard-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 40px;
text-align: center;
}
.wizard-header h1 {
font-size: 32px;
margin-bottom: 10px;
}
.wizard-header p {
opacity: 0.9;
font-size: 16px;
}
.progress-bar {
height: 4px;
background: rgba(255, 255, 255, 0.3);
}
.progress-fill {
height: 100%;
background: white;
width: 25%;
transition: width 0.3s ease;
}
.wizard-body {
padding: 40px;
}
.step {
display: none;
}
.step.active {
display: block;
animation: fadeIn 0.3s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.form-group {
margin-bottom: 24px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 500;
color: #333;
}
input[type="text"],
input[type="email"],
input[type="password"],
input[type="url"],
input[type="color"] {
width: 100%;
padding: 12px 16px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 16px;
transition: all 0.2s;
}
input[type="color"] {
height: 50px;
cursor: pointer;
}
input:focus {
outline: none;
border-color: #667eea;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
}
.wizard-footer {
display: flex;
justify-content: space-between;
margin-top: 32px;
padding-top: 24px;
border-top: 1px solid #e0e0e0;
}
button {
padding: 12px 32px;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
}
.btn-primary:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-secondary {
background: #f0f0f0;
color: #666;
}
.btn-secondary:hover {
background: #e0e0e0;
}
.installing {
text-align: center;
padding: 40px 20px;
}
.spinner {
width: 60px;
height: 60px;
border: 4px solid #f0f0f0;
border-top: 4px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 20px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.error-message {
background: #fee;
color: #c33;
padding: 12px;
border-radius: 8px;
margin-top: 16px;
font-size: 14px;
}
@media (max-width: 600px) {
.form-row {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="wizard-container">
<div class="wizard-header">
<h1>🎨 Portfolio Hub</h1>
<p>Let's set up your portfolio in 3 easy steps</p>
</div>
<div class="progress-bar">
<div class="progress-fill" id="progressFill"></div>
</div>
<div class="wizard-body">
<!-- Step 1: Site Information -->
<div class="step active" data-step="1">
<h2 style="margin-bottom: 24px;">Site Information</h2>
<div class="form-group">
<label for="site_title">Site Title *</label>
<input type="text" id="site_title" name="site_title" required
placeholder="Your Name - Portfolio Hub">
</div>
<div class="form-group">
<label for="site_url">Site URL *</label>
<input type="url" id="site_url" name="site_url" required
value="<?= htmlspecialchars($detectedUrl) ?>">
</div>
<div class="form-group">
<label for="hero_text">Hero Text *</label>
<input type="text" id="hero_text" name="hero_text" required
placeholder="Your Name">
</div>
<div class="form-group">
<label for="hero_subtext">Hero Subtext *</label>
<input type="text" id="hero_subtext" name="hero_subtext" required
placeholder="Designer • Developer • Creator">
</div>
</div>
<!-- Step 2: Admin Account -->
<div class="step" data-step="2">
<h2 style="margin-bottom: 24px;">Admin Account</h2>
<div class="form-group">
<label for="admin_email">Email Address *</label>
<input type="email" id="admin_email" name="admin_email" required
placeholder="admin@example.com">
</div>
<div class="form-group">
<label for="admin_password">Password *</label>
<input type="password" id="admin_password" name="admin_password" required
placeholder="At least 8 characters">
</div>
<div class="form-group">
<label for="admin_password_confirm">Confirm Password *</label>
<input type="password" id="admin_password_confirm" name="admin_password_confirm" required
placeholder="Re-enter your password">
</div>
</div>
<!-- Step 3: Theme -->
<div class="step" data-step="3">
<h2 style="margin-bottom: 24px;">Choose Your Colors</h2>
<div class="form-row">
<div class="form-group">
<label for="primary_color">Primary Color</label>
<input type="color" id="primary_color" name="primary_color" value="#6366f1">
</div>
<div class="form-group">
<label for="secondary_color">Secondary Color</label>
<input type="color" id="secondary_color" name="secondary_color" value="#8b5cf6">
</div>
</div>
</div>
<!-- Step 4: Installing -->
<div class="step" data-step="4">
<div class="installing">
<div class="spinner"></div>
<h2>Setting up your portfolio...</h2>
<p style="color: #666; margin-top: 12px;">This will only take a moment</p>
<div id="errorContainer"></div>
</div>
</div>
<div class="wizard-footer">
<button type="button" class="btn-secondary" id="prevBtn" style="display: none;">
← Back
</button>
<button type="button" class="btn-primary" id="nextBtn">
Next →
</button>
</div>
</div>
</div>
<script>
let currentStep = 1;
const totalSteps = 4;
function updateProgress() {
const progress = (currentStep / totalSteps) * 100;
document.getElementById('progressFill').style.width = progress + '%';
}
function showStep(step) {
document.querySelectorAll('.step').forEach(s => s.classList.remove('active'));
document.querySelector(`[data-step="${step}"]`).classList.add('active');
document.getElementById('prevBtn').style.display = step > 1 && step < 4 ? 'block' : 'none';
document.getElementById('nextBtn').style.display = step < 4 ? 'block' : 'none';
if (step < 4) {
document.getElementById('nextBtn').textContent = step === 3 ? 'Complete Setup' : 'Next →';
}
updateProgress();
}
function validateStep(step) {
const inputs = document.querySelectorAll(`[data-step="${step}"] input[required]`);
let valid = true;
inputs.forEach(input => {
if (!input.value.trim()) {
valid = false;
input.style.borderColor = '#ef4444';
} else {
input.style.borderColor = '#e0e0e0';
}
});
if (step === 2) {
const pass = document.getElementById('admin_password').value;
const confirm = document.getElementById('admin_password_confirm').value;
if (pass !== confirm) {
alert('Passwords do not match!');
return false;
}
if (pass.length < 8) {
alert('Password must be at least 8 characters!');
return false;
}
}
if (!valid) {
alert('Please fill in all required fields');
}
return valid;
}
async function saveStep(step) {
const formData = new FormData();
formData.append('step', step);
const inputs = document.querySelectorAll(`[data-step="${step}"] input:not([name$="_confirm"])`);
inputs.forEach(input => {
if (input.name) {
formData.append(input.name, input.value);
}
});
try {
const response = await fetch('setup.php', {
method: 'POST',
body: formData
});
const data = await response.json();
return data;
} catch (error) {
console.error('Save failed:', error);
return { success: false, error: error.message };
}
}
document.getElementById('nextBtn').addEventListener('click', async () => {
if (!validateStep(currentStep)) {
return;
}
const nextBtn = document.getElementById('nextBtn');
nextBtn.disabled = true;
const result = await saveStep(currentStep);
if (!result.success) {
alert('Failed to save. Please try again.');
nextBtn.disabled = false;
return;
}
if (currentStep < 3) {
currentStep++;
showStep(currentStep);
nextBtn.disabled = false;
} else if (currentStep === 3) {
currentStep = 4;
showStep(currentStep);
const installResult = await saveStep(4);
if (installResult.success && installResult.redirect) {
document.querySelector('[data-step="4"] .installing').innerHTML = `
<div style="font-size: 60px; margin-bottom: 20px;">✅</div>
<h2>Setup Complete!</h2>
<p style="color: #666; margin-top: 12px;">Redirecting to login...</p>
`;
setTimeout(() => {
window.location.href = installResult.redirect;
}, 1500);
} else {
const errorMsg = installResult.error || 'Setup failed. Check server logs.';
document.getElementById('errorContainer').innerHTML = `
<div class="error-message">${errorMsg}</div>
`;
setTimeout(() => {
currentStep = 3;
showStep(currentStep);
nextBtn.disabled = false;
}, 3000);
}
}
});
document.getElementById('prevBtn').addEventListener('click', () => {
if (currentStep > 1) {
currentStep--;
showStep(currentStep);
}
});
updateProgress();
</script>
</body>
</html>