-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
1023 lines (890 loc) · 43.1 KB
/
Copy pathindex.php
File metadata and controls
1023 lines (890 loc) · 43.1 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
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* ReadIn52 - Main Router
*
* All requests are routed through this file.
*/
// Load configuration
require_once __DIR__ . '/config/config.php';
// Check if app is installed
if (!Database::isInstalled()) {
// Redirect to install script if exists
if (file_exists(__DIR__ . '/install.php')) {
header('Location: /install.php');
exit;
}
die('Application not installed. Please run install.php');
}
// Run database migrations (for updates)
Database::migrate();
// Start session
Auth::startSession();
// Get route
$route = trim($_GET['route'] ?? '', '/');
$method = $_SERVER['REQUEST_METHOD'];
// Route handling
try {
switch ($route) {
// ============ Public Routes ============
case '':
case 'home':
if (Auth::isLoggedIn()) {
redirect('/?route=dashboard');
}
render('home');
break;
case 'login':
if (Auth::isLoggedIn()) {
redirect('/?route=dashboard');
}
if ($method === 'POST') {
if (!validateCsrf()) {
render('login', ['error' => 'Invalid request. Please try again.']);
break;
}
if (!verifyTurnstile()) {
render('login', ['error' => 'Human verification failed. Please try again.']);
break;
}
$email = trim(post('email', ''));
$password = post('password', '');
$result = Auth::login($email, $password);
if ($result['success']) {
// Check if user must change password on first login
if (User::mustChangePassword(Auth::getUserId())) {
redirect('/?route=setup-credentials');
} else {
setFlash('success', 'Welcome back!');
redirect('/?route=dashboard');
}
} else {
render('login', [
'error' => $result['error'],
'email' => $email
]);
}
} else {
render('login');
}
break;
case 'register':
if (Auth::isLoggedIn()) {
redirect('/?route=dashboard');
}
if (!Auth::isRegistrationEnabled()) {
setFlash('error', 'Registration is currently disabled.');
redirect('/?route=login');
}
if ($method === 'POST') {
if (!validateCsrf()) {
render('register', ['error' => 'Invalid request. Please try again.']);
break;
}
if (!verifyTurnstile()) {
render('register', ['error' => 'Human verification failed. Please try again.']);
break;
}
$name = trim(post('name', ''));
$email = trim(post('email', ''));
$password = post('password', '');
$passwordConfirm = post('password_confirm', '');
$acceptTerms = post('accept_terms', '');
if (!$acceptTerms) {
render('register', [
'error' => 'You must accept the Terms & Conditions to create an account.',
'name' => $name,
'email' => $email
]);
break;
}
if ($password !== $passwordConfirm) {
render('register', [
'error' => 'Passwords do not match.',
'name' => $name,
'email' => $email
]);
break;
}
$result = Auth::register($name, $email, $password);
if ($result['success']) {
setFlash('success', 'Account created! Please sign in.');
redirect('/?route=login');
} else {
render('register', [
'error' => $result['error'],
'name' => $name,
'email' => $email
]);
}
} else {
render('register');
}
break;
case 'logout':
Auth::logout();
setFlash('success', 'You have been logged out.');
redirect('/');
break;
case 'privacy':
render('privacy');
break;
case 'terms':
render('terms');
break;
case 'about':
render('about');
break;
case 'forgot-password':
if (Auth::isLoggedIn()) {
redirect('/?route=dashboard');
}
if ($method === 'POST') {
if (!validateCsrf()) {
render('forgot-password', ['error' => 'Invalid request. Please try again.']);
break;
}
if (!verifyTurnstile()) {
render('forgot-password', ['error' => 'Human verification failed. Please try again.']);
break;
}
$email = trim(post('email', ''));
// Always show success message to prevent email enumeration
$successMessage = 'If an account exists with this email, you will receive a password reset link shortly.';
if (!empty($email)) {
$resetData = User::createPasswordResetToken($email);
if ($resetData && Email::isConfigured()) {
Email::sendPasswordReset(
$resetData['user']['email'],
$resetData['user']['name'],
$resetData['token']
);
}
}
render('forgot-password', ['success' => $successMessage]);
} else {
render('forgot-password');
}
break;
case 'reset-password':
if (Auth::isLoggedIn()) {
redirect('/?route=dashboard');
}
$token = $_GET['token'] ?? post('token', '');
if ($method === 'POST') {
if (!validateCsrf()) {
render('reset-password', ['error' => 'Invalid request. Please try again.', 'validToken' => false]);
break;
}
$password = post('password', '');
$passwordConfirm = post('password_confirm', '');
if (strlen($password) < 6) {
render('reset-password', [
'error' => 'Password must be at least 6 characters.',
'validToken' => true,
'token' => $token
]);
} elseif ($password !== $passwordConfirm) {
render('reset-password', [
'error' => 'Passwords do not match.',
'validToken' => true,
'token' => $token
]);
} elseif (User::resetPasswordWithToken($token, $password)) {
render('reset-password', ['success' => 'Your password has been reset successfully. You can now sign in.']);
} else {
render('reset-password', ['error' => 'This reset link is invalid or has expired.', 'validToken' => false]);
}
} else {
$resetData = User::validatePasswordResetToken($token);
render('reset-password', [
'validToken' => $resetData !== null,
'token' => $token
]);
}
break;
case 'verify-email':
$token = $_GET['token'] ?? '';
$result = User::completeEmailChange($token);
if ($result) {
setFlash('success', 'Your email has been changed to ' . $result['new_email']);
// If logged in, refresh session
if (Auth::isLoggedIn() && Auth::getUserId() === $result['user_id']) {
// User session will pick up new email on next page load
}
} else {
setFlash('error', 'This verification link is invalid or has expired.');
}
redirect(Auth::isLoggedIn() ? '/?route=settings' : '/?route=login');
break;
case 'setup-credentials':
Auth::requireAuth();
// Only show if user must change password
if (!User::mustChangePassword(Auth::getUserId())) {
redirect('/?route=dashboard');
}
$data = [];
if ($method === 'POST') {
if (!validateCsrf()) {
$data['error'] = 'Invalid request. Please try again.';
} else {
$newName = trim(post('name', ''));
$newEmail = trim(post('email', ''));
$newPassword = post('password', '');
$confirmPassword = post('password_confirm', '');
$userId = Auth::getUserId();
// Validate inputs
if (empty($newName) || strlen($newName) < 2) {
$data['error'] = 'Please enter your name (at least 2 characters).';
} elseif (!filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
$data['error'] = 'Please enter a valid email address.';
} elseif (strlen($newPassword) < 6) {
$data['error'] = 'Password must be at least 6 characters.';
} elseif ($newPassword !== $confirmPassword) {
$data['error'] = 'Passwords do not match.';
} else {
// Check if email is already in use by another user
$existingUser = User::findByEmail($newEmail);
if ($existingUser && $existingUser['id'] !== $userId) {
$data['error'] = 'This email is already in use.';
} else {
// Update name, email and password
User::update($userId, ['name' => $newName, 'email' => $newEmail]);
User::updatePassword($userId, $newPassword);
User::clearMustChangePassword($userId);
setFlash('success', 'Your account has been set up. Welcome to ' . ReadingPlan::getAppName() . '!');
redirect('/?route=dashboard');
}
}
}
}
render('setup-credentials', $data);
break;
// ============ Authenticated Routes ============
case 'dashboard':
Auth::requireAuth();
render('dashboard');
break;
case 'profile':
Auth::requireAuth();
render('profile');
break;
case 'books':
Auth::requireAuth();
render('books');
break;
case 'notes':
Auth::requireAuth();
render('notes');
break;
case 'notes/save':
Auth::requireAuth();
if ($method === 'POST') {
// Check if AJAX request - look for ajax parameter or XHR header
$isAjax = isAjax() || post('ajax') === '1' || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
if (!validateCsrf()) {
if ($isAjax) {
jsonResponse(['success' => false, 'error' => 'Invalid CSRF token'], 403);
}
setFlash('error', 'Invalid request.');
redirect('/?route=dashboard');
}
$noteId = post('note_id', '');
$data = [
'title' => post('title', ''),
'content' => post('content', ''),
'color' => post('color', 'default'),
'week_number' => post('week_number', ''),
'category' => post('category', ''),
'book' => post('book', ''),
'chapter' => post('chapter', ''),
];
try {
if ($noteId) {
Note::update((int) $noteId, Auth::getUserId(), $data);
$message = 'Note updated.';
} else {
Note::create(Auth::getUserId(), $data);
$message = 'Note created.';
}
if ($isAjax) {
jsonResponse(['success' => true, 'message' => $message]);
}
setFlash('success', $message);
} catch (Exception $e) {
if ($isAjax) {
jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}
setFlash('error', 'Failed to save note.');
}
}
// Redirect back - form submission reloads page in reader
redirect('/?route=dashboard');
break;
case 'notes/delete':
Auth::requireAuth();
header('Content-Type: application/json');
if ($method === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_encode(['success' => false, 'error' => 'Invalid JSON']);
exit;
}
// Validate CSRF token
$csrfToken = $input['csrf_token'] ?? '';
if (!Auth::verifyCsrfToken($csrfToken)) {
echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
exit;
}
$noteId = (int) ($input['note_id'] ?? 0);
if ($noteId && Note::delete($noteId, Auth::getUserId())) {
echo json_encode(['success' => true]);
} else {
echo json_encode(['success' => false, 'error' => 'Failed to delete']);
}
} else {
echo json_encode(['success' => false, 'error' => 'Invalid method']);
}
exit;
case 'settings':
Auth::requireAuth();
$data = [];
if ($method === 'POST') {
if (!validateCsrf()) {
$data['error'] = 'Invalid request. Please try again.';
} else {
$action = post('action', 'save_preferences');
$userId = Auth::getUserId();
if ($action === 'update_name') {
$name = trim(post('name', ''));
if (empty($name)) {
$data['nameError'] = 'Name is required.';
} elseif (User::update($userId, ['name' => $name])) {
$data['nameSuccess'] = 'Name updated successfully.';
} else {
$data['nameError'] = 'Failed to update name.';
}
} elseif ($action === 'change_password') {
$currentPassword = post('current_password', '');
$newPassword = post('new_password', '');
$confirmPassword = post('confirm_password', '');
if (!User::verifyPassword($userId, $currentPassword)) {
$data['passwordError'] = 'Current password is incorrect.';
} elseif ($newPassword !== $confirmPassword) {
$data['passwordError'] = 'New passwords do not match.';
} elseif (strlen($newPassword) < 6) {
$data['passwordError'] = 'Password must be at least 6 characters.';
} elseif (User::updatePassword($userId, $newPassword)) {
$data['passwordSuccess'] = 'Password changed successfully.';
} else {
$data['passwordError'] = 'Failed to change password.';
}
} elseif ($action === 'change_email') {
$newEmail = trim(post('new_email', ''));
$password = post('password', '');
$currentUser = Auth::getUser();
if (!filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
$data['emailError'] = 'Please enter a valid email address.';
} elseif ($newEmail === $currentUser['email']) {
$data['emailError'] = 'New email is the same as your current email.';
} elseif (!User::verifyPassword($userId, $password)) {
$data['emailError'] = 'Incorrect password.';
} else {
$verifyData = User::createEmailVerificationToken($userId, $newEmail);
if (!$verifyData) {
$data['emailError'] = 'This email address is already in use.';
} elseif (!Email::isConfigured()) {
$data['emailError'] = 'Email service is not configured. Please contact support.';
} else {
$result = Email::sendEmailVerification($newEmail, $currentUser['name'], $verifyData['token']);
if ($result['success']) {
$data['emailSuccess'] = 'Verification email sent to ' . e($newEmail) . '. Please check your inbox.';
} else {
$data['emailError'] = 'Failed to send verification email. Please try again.';
}
}
}
} else {
// Default: save preferences (theme, translations)
$translation = post('preferred_translation', 'eng_kjv');
$secondaryTranslation = post('secondary_translation', '');
$theme = post('theme', 'auto');
// Validate theme value
if (!in_array($theme, ['light', 'dark', 'auto'])) {
$theme = 'auto';
}
// Set secondary to null if empty or same as primary
if ($secondaryTranslation === '' || $secondaryTranslation === $translation) {
$secondaryTranslation = null;
}
if (User::update($userId, [
'preferred_translation' => $translation,
'secondary_translation' => $secondaryTranslation,
'theme' => $theme
])) {
$data['prefsSuccess'] = 'Preferences saved successfully.';
} else {
$data['prefsError'] = 'Failed to save preferences.';
}
}
}
}
render('settings', $data);
break;
case 'settings/reset-progress':
Auth::requireAuth();
if ($method === 'POST') {
if (!validateCsrf()) {
setFlash('error', 'Invalid request. Please try again.');
} else {
$password = post('password', '');
$userId = Auth::getUserId();
if (!User::verifyPassword($userId, $password)) {
setFlash('error', 'Incorrect password.');
} elseif (Progress::deleteAllProgress($userId)) {
setFlash('success', 'Your reading progress has been reset.');
} else {
setFlash('error', 'Failed to reset progress. Please try again.');
}
}
}
redirect('/?route=settings');
break;
case 'settings/delete-account':
Auth::requireAuth();
if ($method === 'POST') {
if (!validateCsrf()) {
setFlash('error', 'Invalid request. Please try again.');
} else {
$password = post('password', '');
$userId = Auth::getUserId();
if (!User::verifyPassword($userId, $password)) {
setFlash('error', 'Incorrect password.');
redirect('/?route=settings');
} elseif (User::delete($userId)) {
Auth::logout();
setFlash('success', 'Your account has been deleted.');
redirect('/?route=login');
} else {
setFlash('error', 'Failed to delete account. Please try again.');
redirect('/?route=settings');
}
}
}
redirect('/?route=settings');
break;
// ============ API Routes ============
case 'api/progress':
Auth::requireAuth();
header('Content-Type: application/json');
if ($method === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_encode(['success' => false, 'error' => 'Invalid JSON']);
exit;
}
// Validate CSRF token
$csrfToken = $input['csrf_token'] ?? '';
if (!Auth::verifyCsrfToken($csrfToken)) {
echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
exit;
}
$week = intval($input['week'] ?? 0);
$category = $input['category'] ?? '';
$result = Progress::toggleProgress(Auth::getUserId(), $week, $category);
echo json_encode($result);
} elseif ($method === 'GET') {
$progress = Progress::getAllProgress(Auth::getUserId());
echo json_encode(['success' => true, 'progress' => $progress]);
}
exit;
case 'api/stats':
Auth::requireAuth();
header('Content-Type: application/json');
$stats = Progress::getStats(Auth::getUserId());
$chapterStats = Progress::getChapterStats(Auth::getUserId());
echo json_encode(['success' => true, 'stats' => $stats, 'chapterStats' => $chapterStats]);
exit;
case 'api/chapter-progress':
Auth::requireAuth();
header('Content-Type: application/json');
// Catch ALL errors including fatal ones
set_error_handler(function($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
try {
if ($method === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_encode(['success' => false, 'error' => 'Invalid JSON']);
exit;
}
// Validate CSRF token
$csrfToken = $input['csrf_token'] ?? '';
if (!Auth::verifyCsrfToken($csrfToken)) {
echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
exit;
}
$week = intval($input['week'] ?? 0);
$category = $input['category'] ?? '';
$book = $input['book'] ?? '';
$chapter = intval($input['chapter'] ?? 0);
$result = Progress::toggleChapter(Auth::getUserId(), $week, $category, $book, $chapter);
// Also get updated counts for UI refresh (wrap in try-catch to not fail the main operation)
if ($result['success']) {
try {
$userId = Auth::getUserId();
$result['weekCounts'] = Progress::getWeekChapterCounts($userId, $week);
$result['overallStats'] = Progress::getChapterStats($userId);
} catch (Throwable $e) {
// Log but don't fail - the main toggle succeeded
error_log('Error getting stats after chapter toggle: ' . $e->getMessage());
}
}
echo json_encode($result);
} elseif ($method === 'GET') {
$week = intval($_GET['week'] ?? 0);
if ($week > 0) {
$progress = Progress::getWeekChapterProgress(Auth::getUserId(), $week);
$counts = Progress::getWeekChapterCounts(Auth::getUserId(), $week);
echo json_encode(['success' => true, 'progress' => $progress, 'counts' => $counts]);
} else {
echo json_encode(['success' => false, 'error' => 'Week required']);
}
}
} catch (Throwable $e) {
error_log('API chapter-progress error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
echo json_encode(['success' => false, 'error' => 'Server error: ' . $e->getMessage()]);
}
restore_error_handler();
exit;
// ============ Notes API ============
// Handled in default section for dynamic route matching
// ============ Admin Routes ============
case 'admin':
Auth::requireAdmin();
render('admin/dashboard');
break;
case 'admin/user-progress':
Auth::requireAdmin();
render('admin/user-progress');
break;
case 'admin/users':
Auth::requireAdmin();
$data = [];
if ($method === 'POST') {
if (!validateCsrf()) {
$data['error'] = 'Invalid request.';
} else {
$action = post('action', '');
$userId = intval(post('user_id', 0));
if ($action === 'update' && $userId) {
$updateData = [
'name' => trim(post('name', '')),
'email' => trim(post('email', '')),
'role' => post('role', 'user'),
'preferred_translation' => post('preferred_translation', 'eng_kjv')
];
if (User::update($userId, $updateData)) {
$newPassword = post('new_password', '');
if ($newPassword && strlen($newPassword) >= 6) {
User::updatePassword($userId, $newPassword);
}
setFlash('success', 'User updated successfully.');
} else {
setFlash('error', 'Failed to update user.');
}
redirect('/?route=admin/users');
} elseif ($action === 'delete' && $userId) {
if ($userId === Auth::getUserId()) {
setFlash('error', 'You cannot delete your own account.');
} elseif (User::delete($userId)) {
setFlash('success', 'User deleted successfully.');
} else {
setFlash('error', 'Failed to delete user.');
}
redirect('/?route=admin/users');
}
}
}
render('admin/users', $data);
break;
case 'admin/reading-plan':
Auth::requireAdmin();
$data = [];
if ($method === 'POST') {
if (!validateCsrf()) {
$data['error'] = 'Invalid request.';
} else {
$week = intval(post('week', 0));
$readings = post('readings', []);
if ($week >= 1 && $week <= 52) {
$allSuccess = true;
$errorMsg = '';
foreach ($readings as $catId => $reading) {
$passages = json_decode($reading['passages'] ?? '[]', true);
if (json_last_error() !== JSON_ERROR_NONE) {
$allSuccess = false;
$errorMsg = "Invalid JSON format for $catId passages.";
break;
}
if (!ReadingPlan::updateReading($week, $catId, $reading['reference'] ?? '', $passages)) {
$allSuccess = false;
$errorMsg = "Failed to update $catId reading.";
break;
}
}
if ($allSuccess) {
$data['success'] = "Week $week updated successfully.";
} else {
$data['error'] = $errorMsg ?: 'Failed to save changes.';
}
}
}
}
render('admin/reading-plan', $data);
break;
case 'admin/reading-plan/export':
Auth::requireAdmin();
header('Content-Type: application/json');
header('Content-Disposition: attachment; filename="reading-plan-' . date('Y-m-d') . '.json"');
echo ReadingPlan::export();
exit;
case 'admin/reading-plan/import':
Auth::requireAdmin();
if ($method === 'POST' && validateCsrf()) {
if (isset($_FILES['json_file']) && $_FILES['json_file']['error'] === UPLOAD_ERR_OK) {
$json = file_get_contents($_FILES['json_file']['tmp_name']);
$result = ReadingPlan::import($json);
if ($result['success']) {
setFlash('success', 'Reading plan imported successfully.');
} else {
setFlash('error', $result['error']);
}
} else {
setFlash('error', 'Please select a valid JSON file.');
}
}
redirect('/?route=admin/reading-plan');
break;
case 'admin/settings':
Auth::requireAdmin();
$data = [];
if ($method === 'POST') {
if (!validateCsrf()) {
$data['error'] = 'Invalid request.';
} else {
$action = post('action', '');
if ($action === 'upload_logo') {
// Handle logo upload
$uploadDir = ROOT_PATH . '/uploads/logos/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
$file = $_FILES['logo'];
$maxSize = 500 * 1024; // 500KB
if ($file['size'] > $maxSize) {
$data['logoError'] = 'File too large. Maximum 500KB allowed.';
} else {
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = ['png', 'jpg', 'jpeg', 'svg'];
if (!in_array($ext, $allowed)) {
$data['logoError'] = 'Invalid file type. Use PNG, JPG, or SVG.';
} else {
// Delete old logo if exists
$oldLogo = Database::getSetting('app_logo', '');
if (!empty($oldLogo) && file_exists($uploadDir . $oldLogo)) {
unlink($uploadDir . $oldLogo);
}
// Generate unique filename
$filename = 'app_logo_' . time() . '.' . $ext;
$destPath = $uploadDir . $filename;
if (move_uploaded_file($file['tmp_name'], $destPath)) {
// Resize image if it's not SVG
if ($ext !== 'svg' && function_exists('imagecreatefrompng')) {
$maxWidth = 200;
$maxHeight = 100;
list($width, $height) = getimagesize($destPath);
if ($width > $maxWidth || $height > $maxHeight) {
$ratio = min($maxWidth / $width, $maxHeight / $height);
$newWidth = (int)($width * $ratio);
$newHeight = (int)($height * $ratio);
$thumb = imagecreatetruecolor($newWidth, $newHeight);
imagesavealpha($thumb, true);
$transparent = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
imagefill($thumb, 0, 0, $transparent);
if ($ext === 'png') {
$source = imagecreatefrompng($destPath);
} else {
$source = imagecreatefromjpeg($destPath);
}
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if ($ext === 'png') {
imagepng($thumb, $destPath);
} else {
imagejpeg($thumb, $destPath, 90);
}
imagedestroy($thumb);
imagedestroy($source);
}
}
Database::setSetting('app_logo', $filename);
$data['logoSuccess'] = 'Logo uploaded successfully.';
} else {
$data['logoError'] = 'Failed to upload file.';
}
}
}
} else {
$data['logoError'] = 'Please select a valid file.';
}
} elseif ($action === 'remove_logo') {
// Remove logo
$uploadDir = ROOT_PATH . '/uploads/logos/';
$oldLogo = Database::getSetting('app_logo', '');
if (!empty($oldLogo) && file_exists($uploadDir . $oldLogo)) {
unlink($uploadDir . $oldLogo);
}
Database::setSetting('app_logo', '');
$data['logoSuccess'] = 'Logo removed.';
} elseif ($action === 'sync_translations') {
$result = Database::syncTranslationsFromAPI();
if ($result['success']) {
$data['success'] = 'Synced ' . $result['imported'] . ' translations from HelloAO API.';
} else {
$data['error'] = $result['error'];
}
} elseif ($action === 'clear_progress') {
// Require password confirmation for dangerous actions
$password = post('confirm_password', '');
if (!User::verifyPassword(Auth::getUserId(), $password)) {
$data['error'] = 'Incorrect password. Action cancelled for security.';
} else {
$pdo = Database::getInstance();
$pdo->exec('DELETE FROM reading_progress');
$pdo->exec('DELETE FROM chapter_progress');
$data['success'] = 'All reading progress has been cleared.';
}
} elseif ($action === 'reset_settings') {
Database::insertDefaultSettings();
$data['success'] = 'Settings have been reset to defaults.';
} elseif ($action === 'save_turnstile') {
$siteKey = trim(post('turnstile_site_key', ''));
$secretKey = trim(post('turnstile_secret_key', ''));
$enabled = post('turnstile_enabled', '0') ? '1' : '0';
// Validate keys if enabling
if ($enabled === '1' && (empty($siteKey) || empty($secretKey))) {
$data['turnstileError'] = 'Both Site Key and Secret Key are required to enable Turnstile.';
} else {
Database::setSetting('turnstile_enabled', $enabled);
Database::setSetting('turnstile_site_key', $siteKey);
Database::setSetting('turnstile_secret_key', $secretKey);
$data['turnstileSuccess'] = 'Turnstile settings saved successfully.';
}
} else {
// Update settings
Database::setSetting('app_name', trim(post('app_name', 'ReadIn52')));
Database::setSetting('default_translation', post('default_translation', 'eng_kjv'));
Database::setSetting('registration_enabled', post('registration_enabled', '0') ? '1' : '0');
Database::setSetting('parent_site_name', trim(post('parent_site_name', '')));
Database::setSetting('parent_site_url', trim(post('parent_site_url', '')));
Database::setSetting('admin_email', trim(post('admin_email', '')));
Database::setSetting('github_repo_url', trim(post('github_repo_url', '')));
$data['success'] = 'Settings saved successfully.';
}
}
}
render('admin/settings', $data);
break;
// ============ Reader Routes ============
default:
// Check for reader route pattern: reader/{book}/{chapter}
if (preg_match('#^reader/([A-Z0-9]+)/(\d+)$#', $route, $matches)) {
Auth::requireAuth();
render('reader', [
'book' => $matches[1],
'chapter' => intval($matches[2])
]);
break;
}
// Check for API week route: api/week/{n}
if (preg_match('#^api/week/(\d+)$#', $route, $matches)) {
Auth::requireAuth();
header('Content-Type: application/json');
$weekNum = intval($matches[1]);
$week = ReadingPlan::getWeekWithDetails($weekNum);
$progress = Progress::getWeekProgress(Auth::getUserId(), $weekNum);
echo json_encode([
'success' => true,
'week' => $week,
'progress' => $progress
]);
exit;
}
// Check for API notes route: api/notes/{id}
if (preg_match('#^api/notes/(\d+)$#', $route, $matches)) {
Auth::requireAuth();
header('Content-Type: application/json');
$noteId = intval($matches[1]);
$note = Note::get($noteId, Auth::getUserId());
if ($note) {
echo json_encode(['success' => true, 'note' => $note]);
} else {
echo json_encode(['success' => false, 'error' => 'Note not found']);
}
exit;
}
// Check for API notes/chapter route
if ($route === 'api/notes/chapter') {
Auth::requireAuth();
header('Content-Type: application/json');
$book = $_GET['book'] ?? '';
$chapter = intval($_GET['chapter'] ?? 0);
if ($book && $chapter) {
$notes = Note::getForChapter(Auth::getUserId(), $book, $chapter);
echo json_encode(['success' => true, 'notes' => $notes]);
} else {
echo json_encode(['success' => false, 'error' => 'Book and chapter required']);
}
exit;
}
// 404 Not Found
http_response_code(404);
echo '<!DOCTYPE html>
<html>
<head><title>404 - Not Found</title>
<style>
body { font-family: sans-serif; text-align: center; padding: 50px; }
h1 { color: #5D4037; }
a { color: #1565C0; }
</style>
</head>
<body>
<h1>404 - Page Not Found</h1>
<p>The page you are looking for does not exist.</p>
<p><a href="/">Return to Home</a></p>
</body>
</html>';
break;