-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadmin_action.php
More file actions
802 lines (702 loc) · 29.1 KB
/
admin_action.php
File metadata and controls
802 lines (702 loc) · 29.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
<?php
declare(strict_types=1);
/**
* FlatFile Blog - Admin Actions
* Handles POST requests for create, update, delete operations
*/
require_once 'functions.php';
// Load SecurityHardener if available
$security_hardener_path = __DIR__ . '/libs/SecurityHardener.php';
if (file_exists($security_hardener_path)) {
require_once $security_hardener_path;
}
// Load OpenAIClient if available
$openai_client_path = __DIR__ . '/libs/OpenAIClient.php';
if (file_exists($openai_client_path)) {
require_once $openai_client_path;
}
// Load ImageUploader if available
$image_uploader_path = __DIR__ . '/libs/ImageUploader.php';
if (file_exists($image_uploader_path)) {
require_once $image_uploader_path;
}
// Load AdminLogger if available
$admin_logger_path = __DIR__ . '/libs/AdminLogger.php';
if (file_exists($admin_logger_path)) {
require_once $admin_logger_path;
}
// Initialize security system
if (class_exists('SecurityHardener')) {
SecurityHardener::init();
}
// Start session
session_start();
// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
header('HTTP/1.0 403 Forbidden');
die('Access denied. Please log in.');
}
// Security checks (only if SecurityHardener is available)
if (class_exists('SecurityHardener')) {
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$username = $_SESSION['admin_username'] ?? 'unknown';
// Check brute force protection
$brute_force_check = SecurityHardener::checkBruteForce($ip, $username);
if ($brute_force_check['blocked']) {
http_response_code(429);
die(json_encode(['error' => $brute_force_check['message']]));
}
// Check rate limiting
$rate_limit_check = SecurityHardener::checkRateLimit($ip);
if ($rate_limit_check['blocked']) {
http_response_code(429);
die(json_encode(['error' => $rate_limit_check['message']]));
}
}
// Handle GET requests for AJAX
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action'])) {
$action = $_GET['action'];
if ($action === 'get_post' && isset($_GET['slug'])) {
$slug = $_GET['slug'];
$post = load_post($slug);
if ($post) {
header('Content-Type: application/json');
echo json_encode(['success' => true, 'post' => $post]);
} else {
header('Content-Type: application/json');
echo json_encode(['success' => false, 'error' => 'Post not found']);
}
exit;
}
// Generate AI post content
if ($action === 'generate_ai_post') {
header('Content-Type: application/json');
// Avoid leaking PHP warnings/notices into JSON
if (function_exists('ob_get_level') && ob_get_level() > 0) {
ob_clean();
}
ini_set('display_errors', '0');
if (!extension_loaded('curl')) {
echo json_encode(['success' => false, 'error' => 'Server missing PHP cURL extension. Enable it in php.ini and restart Apache.']);
exit;
}
$topic = trim($_GET['topic'] ?? '');
if ($topic === '') {
echo json_encode(['success' => false, 'error' => 'Topic is required']);
exit;
}
$settings = load_settings();
$businessInfo = trim($settings['business_info'] ?? '');
try {
if (!class_exists('OpenAIClient')) {
echo json_encode(['success' => false, 'error' => 'AI client is unavailable on this server.']);
exit;
}
$openaiKey = trim($settings['openai_api_key'] ?? '');
$openaiModel = trim($settings['openai_model'] ?? 'openai/gpt-4o-mini');
$openaiEndpoint = trim($settings['openai_endpoint'] ?? 'https://models.github.ai/inference');
// Check for API key from environment variables as fallback
if ($openaiKey === '') {
$openaiKey = getenv('OPENAI_API_KEY') ?: getenv('GITHUB_MODELS_TOKEN') ?: getenv('GITHUB_TOKEN') ?: '';
}
// Clean the API key - remove any hidden characters
$openaiKey = preg_replace('/\s+/', '', $openaiKey);
if ($openaiKey === '') {
echo json_encode(['success' => false, 'error' => 'OpenAI API key not configured. Please add it in Settings > AI Settings, or set OPENAI_API_KEY environment variable.']);
exit;
}
// Validate API key format (GitHub tokens are usually 40+ chars or start with ghp_)
if (strlen($openaiKey) < 20 && substr($openaiKey, 0, 4) !== 'ghp_') {
echo json_encode(['success' => false, 'error' => 'API key appears invalid (too short). GitHub tokens are usually 40+ characters or start with "ghp_".']);
exit;
}
// Debug: Log key length and first few chars (for troubleshooting, remove in production)
// $keyPreview = substr($openaiKey, 0, 8) . '...' . substr($openaiKey, -4);
// error_log("AI Generation: Key length=" . strlen($openaiKey) . ", starts with: " . substr($openaiKey, 0, 4) . ", endpoint: " . $openaiEndpoint);
$client = new OpenAIClient($openaiKey, $openaiModel, $openaiEndpoint);
$result = $client->generateBlogContent($topic, $businessInfo);
} catch (Throwable $e) {
echo json_encode(['success' => false, 'error' => 'Server error: ' . $e->getMessage()]);
exit;
}
if (!($result['success'] ?? false)) {
$errorMsg = $result['error'] ?? 'AI generation failed';
// Preserve detailed error messages from API - don't overwrite with generic message
// The OpenAIClient already provides detailed 401 errors with API response details
// Only show generic message if the error doesn't contain useful details
if (
(strpos($errorMsg, '401') !== false || strpos($errorMsg, 'Unauthorized') !== false)
&& strpos($errorMsg, 'API says:') === false
&& strpos($errorMsg, 'Response:') === false
&& strpos($errorMsg, 'Warning:') === false
) {
// Generic fallback only if no details available
$errorMsg = 'Invalid API key. Please check your OpenAI API key in Settings > AI Settings and ensure it is correct.';
}
echo json_encode(['success' => false, 'error' => $errorMsg]);
exit;
}
$slug = isset($result['title']) ? slugify($result['title']) : '';
$preview_post = [
'slug' => $slug,
'title' => $result['title'] ?? '',
'excerpt' => $result['excerpt'] ?? '',
'content_html' => $result['content_html'] ?? '',
'content_type' => 'html',
];
echo json_encode([
'success' => true,
'title' => $result['title'] ?? '',
'excerpt' => $result['excerpt'] ?? '',
'meta_title' => $result['meta_title'] ?? '',
'meta_description' => $result['meta_description'] ?? '',
'og_title' => $result['og_title'] ?? '',
'og_description' => $result['og_description'] ?? '',
'tags' => array_values($result['tags'] ?? []),
'categories' => array_values($result['categories'] ?? []),
'faq' => array_values($result['faq'] ?? []),
'slug' => $slug,
'content_html' => $result['content_html'] ?? '',
'content_type' => 'html',
'word_count' => post_word_count($preview_post),
'read_time' => post_read_time_minutes($preview_post),
'canonical_preview' => $slug !== '' ? absolute_url(rawurlencode($slug)) : '',
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
}
// Verify CSRF token for POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_SESSION['csrf_token'], $_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
header('HTTP/1.0 403 Forbidden');
die('Invalid security token.');
}
$early_action = $_POST['action'] ?? '';
if ($early_action === 'upload_content_image') {
header('Content-Type: application/json');
if (!class_exists('ImageUploader')) {
echo json_encode(['success' => false, 'error' => 'Image upload service is unavailable.']);
exit;
}
if (!isset($_FILES['content_image']) || $_FILES['content_image']['error'] !== UPLOAD_ERR_OK) {
echo json_encode(['success' => false, 'error' => 'No image uploaded.']);
exit;
}
$upload_result = ImageUploader::upload($_FILES['content_image'], 'content');
echo json_encode($upload_result['success']
? ['success' => true, 'url' => $upload_result['url']]
: ['success' => false, 'error' => $upload_result['error'] ?? 'Upload failed']);
exit;
}
}
$action = $_POST['action'] ?? '';
$success_message = '';
$error_message = '';
switch ($action) {
case 'create':
$result = handle_create_post();
if ($result['success']) {
$success_message = 'Post created successfully!';
if (class_exists('AdminLogger')) {
AdminLogger::log('post_created', [
'slug' => $result['slug'] ?? 'unknown',
'title' => $_POST['title'] ?? 'unknown'
]);
}
} else {
$error_message = $result['error'];
if (class_exists('AdminLogger')) {
AdminLogger::log('post_create_failed', [
'error' => $result['error'],
'title' => $_POST['title'] ?? 'unknown'
]);
}
}
break;
case 'update':
$result = handle_update_post();
if ($result['success']) {
$success_message = 'Post updated successfully!';
if (class_exists('AdminLogger')) {
AdminLogger::log('post_updated', [
'slug' => $_POST['slug'] ?? 'unknown',
'title' => $_POST['title'] ?? 'unknown'
]);
}
} else {
$error_message = $result['error'];
if (class_exists('AdminLogger')) {
AdminLogger::log('post_update_failed', [
'error' => $result['error'],
'slug' => $_POST['slug'] ?? 'unknown'
]);
}
}
break;
case 'delete':
$result = handle_delete_post();
if ($result['success']) {
$success_message = 'Post deleted successfully!';
if (class_exists('AdminLogger')) {
AdminLogger::log('post_deleted', [
'slug' => $_POST['slug'] ?? 'unknown'
]);
}
} else {
$error_message = $result['error'];
if (class_exists('AdminLogger')) {
AdminLogger::log('post_delete_failed', [
'error' => $result['error'],
'slug' => $_POST['slug'] ?? 'unknown'
]);
}
}
break;
case 'delete_install_file':
$install_path = __DIR__ . '/install.php';
if (!file_exists($install_path)) {
$error_message = 'install.php was not found.';
if (class_exists('AdminLogger')) {
AdminLogger::log('install_delete_missing', []);
}
break;
}
if (!is_writable($install_path)) {
$error_message = 'install.php is not writable. Delete manually.';
if (class_exists('AdminLogger')) {
AdminLogger::log('install_delete_not_writable', []);
}
break;
}
if (@unlink($install_path)) {
$success_message = 'install.php deleted successfully.';
if (class_exists('AdminLogger')) {
AdminLogger::log('install_deleted', []);
}
} else {
$error_message = 'Failed to delete install.php. Check permissions.';
if (class_exists('AdminLogger')) {
AdminLogger::log('install_delete_failed', []);
}
}
break;
default:
$error_message = 'Invalid action.';
if (class_exists('AdminLogger')) {
AdminLogger::log('invalid_action', [
'action' => $action
]);
}
}
// Set cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// Redirect back to appropriate page with message
$redirect_url = BASE_URL . 'admin/';
// Handle different redirects based on action
if ($action === 'update') {
$slug = $_POST['slug'] ?? '';
// Add cache-busting parameter to force reload
$cache_buster = '&_t=' . time();
$redirect_url = BASE_URL . 'admin/edit-post?slug=' . urlencode($slug) . $cache_buster;
} elseif ($action === 'create') {
// Keep user on create form on errors; send to dashboard on success
if ($error_message) {
$redirect_url = BASE_URL . 'admin/new-post?_t=' . time();
} else {
$redirect_url = BASE_URL . 'admin/?_t=' . time();
}
}
if ($success_message) {
$redirect_url .= (strpos($redirect_url, '?') !== false ? '&' : '?') . 'success=' . urlencode($success_message);
} elseif ($error_message) {
$redirect_url .= (strpos($redirect_url, '?') !== false ? '&' : '?') . 'error=' . urlencode($error_message);
}
header('Location: ' . $redirect_url);
exit;
/**
* Handle create post action
*/
function handle_create_post()
{
// Validate required fields
$title = trim($_POST['title'] ?? '');
$content = trim($_POST['content'] ?? '');
if (empty($title)) {
return ['success' => false, 'error' => 'Title is required.'];
}
if (empty($content)) {
return ['success' => false, 'error' => 'Content is required.'];
}
if (is_duplicate_title($title)) {
return ['success' => false, 'error' => 'A post with this title already exists. Please use a unique title.'];
}
// Sanitize and validate data
$slug = trim($_POST['slug'] ?? '');
if (empty($slug)) {
$slug = slugify($title);
} else {
$slug = slugify($slug);
}
if (!is_valid_slug($slug)) {
return ['success' => false, 'error' => 'Invalid slug format. Use only letters, numbers, and hyphens.'];
}
// Check if slug already exists
if (load_post($slug)) {
$slug = $slug . '-' . time();
}
$excerpt = trim($_POST['excerpt'] ?? '');
$status = in_array($_POST['status'] ?? '', ['published', 'draft']) ? $_POST['status'] : 'published';
// Date handling: accept datetime-local (YYYY-MM-DDTHH:MM) or ISO and convert to ISO8601
$date_input = trim($_POST['date'] ?? '');
$date_ts = $date_input !== '' ? strtotime($date_input) : time();
$date = date('c', $date_ts);
// Updated handling: allow override; default to publish date/time
$updated_input = trim($_POST['updated'] ?? '');
$updated_ts = $updated_input !== '' ? strtotime($updated_input) : $date_ts;
$updated = date('c', $updated_ts);
$author = trim($_POST['author'] ?? 'Admin');
$tags = parse_tags_from_post();
$categories = parse_categories_from_post();
// Handle featured image upload
$featured_image = '';
if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
if (!class_exists('ImageUploader')) {
return ['success' => false, 'error' => 'Image upload service is unavailable.'];
}
$upload_result = ImageUploader::upload($_FILES['featured_image'], 'featured');
if ($upload_result['success']) {
$featured_image = $upload_result['url'];
}
}
$content_type = $_POST['content_type'] ?? 'html';
$post_data = array_merge($post_data, [
'slug' => $slug,
'title' => $title,
'content_type' => $content_type,
'excerpt' => $excerpt,
'status' => $status,
'date' => $date,
'updated' => $updated,
'author' => $author,
'tags' => $tags,
'categories' => $categories,
'meta' => [
'image' => $featured_image,
'image_alt' => trim($_POST['featured_image_alt'] ?? '')
]
]);
if ($content_type === 'html') {
$post_data['content_html'] = $content;
unset($post_data['content_markdown']);
} else {
$post_data['content_markdown'] = $content;
unset($post_data['content_html']);
}
apply_cms_fields_to_post($post_data);
if (save_post($post_data)) {
// Force clear any opcache if enabled
if (function_exists('opcache_invalidate')) {
$post_file = CONTENT_DIR . 'posts/' . $slug . '.json';
opcache_invalidate($post_file, true);
}
return ['success' => true];
} else {
return ['success' => false, 'error' => 'Failed to save post. Check file permissions.'];
}
}
/**
* Delete a featured image file from disk if URL points inside this site's uploads directory.
*/
function delete_featured_image_file_if_local(string $image_url): void
{
if ($image_url === '') {
return;
}
$base = rtrim((string) BASE_URL, '/');
if (!str_starts_with($image_url, $base)) {
return;
}
$relative = ltrim(substr($image_url, strlen($base)), '/');
if ($relative === '' || str_contains($relative, '..')) {
return;
}
if (!defined('UPLOADS_DIR')) {
return;
}
$uploads_root = realpath(rtrim(constant('UPLOADS_DIR'), '/\\'));
if ($uploads_root === false) {
return;
}
$candidate = realpath(__DIR__ . '/' . $relative);
if ($candidate === false || !str_starts_with($candidate, $uploads_root)) {
return;
}
if (is_file($candidate)) {
@unlink($candidate);
}
$dir = dirname($candidate);
$stem = pathinfo($candidate, PATHINFO_FILENAME);
$ext = pathinfo($candidate, PATHINFO_EXTENSION);
foreach (['_thumb', '_medium'] as $suffix) {
$variant = $dir . '/' . $stem . $suffix . '.' . $ext;
if (is_file($variant)) {
@unlink($variant);
}
}
}
/**
* Handle update post action
*/
function handle_update_post()
{
// Identify the post to update by its original slug (stable identifier)
$original_slug = trim($_POST['original_slug'] ?? '');
$slug = trim($_POST['slug'] ?? '');
if (empty($original_slug)) {
return ['success' => false, 'error' => 'Original post slug is required.'];
}
if (!is_valid_slug($original_slug)) {
return ['success' => false, 'error' => 'Invalid original slug format.'];
}
// Load existing post
$existing_post = load_post($original_slug);
if (!$existing_post) {
return ['success' => false, 'error' => 'Post not found.'];
}
// Validate required fields
$title = trim($_POST['title'] ?? '');
$content = trim($_POST['content'] ?? '');
if (empty($title)) {
return ['success' => false, 'error' => 'Title is required.'];
}
if (empty($content)) {
return ['success' => false, 'error' => 'Content is required.'];
}
if (is_duplicate_title($title, $original_slug)) {
return ['success' => false, 'error' => 'A post with this title already exists. Please use a unique title.'];
}
// Get content type
$content_type = $_POST['content_type'] ?? ($existing_post['content_type'] ?? 'markdown');
// Update post data (allow title change and optional slug change)
$existing_post['title'] = $title;
// If slug field was changed, ensure uniqueness and rename the file
if (!empty($slug) && $slug !== $original_slug) {
$new_slug = slugify($slug);
if (!is_valid_slug($new_slug)) {
return ['success' => false, 'error' => 'Invalid slug format. Use only letters, numbers, and hyphens.'];
}
if ($new_slug !== $original_slug) {
// If target slug exists, make it unique
if (load_post($new_slug)) {
$new_slug = $new_slug . '-' . time();
}
// Rename file on disk if present
$old_path = CONTENT_DIR . 'posts/' . $original_slug . '.json';
$new_path = CONTENT_DIR . 'posts/' . $new_slug . '.json';
if (file_exists($old_path)) {
@rename($old_path, $new_path);
// Reload the existing post data from new path if rename succeeded
if (file_exists($new_path)) {
$existing_post['slug'] = $new_slug;
}
} else {
$existing_post['slug'] = $new_slug;
}
}
}
$existing_post['content_type'] = $content_type;
$existing_post['excerpt'] = trim($_POST['excerpt'] ?? '');
$existing_post['status'] = in_array($_POST['status'] ?? '', ['published', 'draft']) ? $_POST['status'] : $existing_post['status'];
$existing_post['author'] = trim($_POST['author'] ?? $existing_post['author']);
// Optional date override
if (isset($_POST['date']) && trim($_POST['date']) !== '') {
$date_ts = strtotime(trim($_POST['date']));
if ($date_ts !== false) {
$existing_post['date'] = date('c', $date_ts);
}
}
// Updated time: allow override, else default to now
if (isset($_POST['updated']) && trim($_POST['updated']) !== '') {
$updated_ts = strtotime(trim($_POST['updated']));
$existing_post['updated'] = $updated_ts !== false ? date('c', $updated_ts) : date('c');
} else {
$existing_post['updated'] = date('c');
}
// Store content based on type
if ($content_type === 'html') {
$existing_post['content_html'] = $content;
unset($existing_post['content_markdown']);
} else {
$existing_post['content_markdown'] = $content;
unset($existing_post['content_html']);
}
$existing_post['tags'] = parse_tags_from_post();
$existing_post['categories'] = parse_categories_from_post();
if (!isset($existing_post['meta']) || !is_array($existing_post['meta'])) {
$existing_post['meta'] = [];
}
$featured_alt = trim($_POST['featured_image_alt'] ?? '');
if ($featured_alt !== '') {
$existing_post['meta']['image_alt'] = $featured_alt;
}
$new_featured_upload = isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK;
$remove_featured_image = !empty($_POST['remove_featured_image']);
if ($new_featured_upload) {
if (!class_exists('ImageUploader')) {
return ['success' => false, 'error' => 'Image upload service is unavailable.'];
}
$upload_result = ImageUploader::upload($_FILES['featured_image'], 'featured');
if ($upload_result['success']) {
$existing_post['meta']['image'] = $upload_result['url'];
}
} elseif ($remove_featured_image) {
$old_image_url = (string) ($existing_post['meta']['image'] ?? '');
if ($old_image_url !== '') {
delete_featured_image_file_if_local($old_image_url);
}
unset($existing_post['meta']['image']);
unset($existing_post['meta']['image_alt']);
}
apply_cms_fields_to_post($existing_post);
// Save updated post
if (save_post($existing_post)) {
// Force clear any opcache if enabled
if (function_exists('opcache_invalidate')) {
$post_file = CONTENT_DIR . 'posts/' . $existing_post['slug'] . '.json';
opcache_invalidate($post_file, true);
}
return ['success' => true];
} else {
return ['success' => false, 'error' => 'Failed to update post. Check file permissions.'];
}
}
/**
* Handle delete post action
*/
function handle_delete_post()
{
$slug = trim($_POST['slug'] ?? '');
if (empty($slug)) {
return ['success' => false, 'error' => 'Post slug is required.'];
}
if (!is_valid_slug($slug)) {
return ['success' => false, 'error' => 'Invalid slug format.'];
}
// Check if post exists
if (!load_post($slug)) {
return ['success' => false, 'error' => 'Post not found.'];
}
// Delete post
if (delete_post($slug)) {
return ['success' => true];
} else {
return ['success' => false, 'error' => 'Failed to delete post. Check file permissions.'];
}
}
function is_valid_slug($slug)
{
return is_string($slug) && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug);
}
function parse_tags_from_post(): array
{
if (!empty($_POST['tags'])) {
return array_values(array_filter(array_map('trim', explode(',', (string) $_POST['tags']))));
}
return [];
}
function parse_categories_from_post(): array
{
$categories = [];
if (!empty($_POST['categories']) && is_array($_POST['categories'])) {
$categories = array_values(array_filter(array_map('trim', $_POST['categories'])));
} elseif (!empty($_POST['categories'])) {
$categories = array_values(array_filter(array_map('trim', explode(',', (string) $_POST['categories']))));
}
$new_cat = trim($_POST['new_category'] ?? '');
if ($new_cat !== '') {
$categories[] = $new_cat;
}
return array_values(array_unique($categories));
}
function apply_cms_fields_to_post(array &$post_data): void
{
$meta_title = trim($_POST['meta_title'] ?? '');
$meta_description = trim($_POST['meta_description'] ?? '');
$canonical_url = trim($_POST['canonical_url'] ?? '');
if ($canonical_url !== '') {
$slug_path = !empty($post_data['slug']) ? rawurlencode((string) $post_data['slug']) : '';
$canonical_url = normalize_absolute_url($canonical_url, $slug_path);
}
$robots_index = !empty($_POST['robots_index']);
$post_data['seo'] = [
'meta_title' => $meta_title,
'meta_description' => $meta_description,
'canonical_url' => $canonical_url,
'robots' => $robots_index ? 'index' : 'noindex'
];
$preserve_og = is_array($post_data['og'] ?? null) ? $post_data['og'] : [];
$og = [
'title' => trim($_POST['og_title'] ?? ''),
'description' => trim($_POST['og_description'] ?? ''),
'twitter_card' => !empty($_POST['twitter_card']),
'image' => trim((string) ($preserve_og['image'] ?? '')),
'image_custom' => !empty($preserve_og['image_custom'])
];
if (isset($_FILES['og_image']) && $_FILES['og_image']['error'] === UPLOAD_ERR_OK && class_exists('ImageUploader')) {
$og_upload = ImageUploader::upload($_FILES['og_image'], 'og');
if ($og_upload['success']) {
$og['image'] = $og_upload['url'];
$og['image_custom'] = true;
}
} elseif ($og['image'] === '' || !$og['image_custom']) {
// No dedicated OG image — do not store featured URL here; post_og_image() uses thumbnail at render time
$og['image'] = '';
$og['image_custom'] = false;
}
$post_data['og'] = $og;
$faq = [];
$questions = $_POST['faq_question'] ?? [];
$answers = $_POST['faq_answer'] ?? [];
if (is_array($questions)) {
foreach ($questions as $i => $q) {
$q = trim((string) $q);
$a = trim((string) ($answers[$i] ?? ''));
if ($q !== '' && $a !== '') {
$faq[] = ['question' => $q, 'answer' => $a];
}
}
}
$post_data['schema'] = [
'article' => !empty($_POST['schema_article']),
'breadcrumb' => !empty($_POST['schema_breadcrumb']),
'faq' => $faq
];
$priority = $_POST['sitemap_priority'] ?? 0.9;
$post_data['sitemap_priority'] = max(0.1, min(1.0, (float) $priority));
$related = $_POST['related_posts'] ?? [];
$post_data['related_posts'] = is_array($related) ? array_slice(array_values(array_filter(array_map('trim', $related))), 0, 3) : [];
$post_data['word_count'] = post_word_count($post_data);
$post_data['read_time'] = post_read_time_minutes($post_data);
normalize_post_stored_urls($post_data);
}
function is_duplicate_title(string $title, string $exclude_slug = ''): bool
{
$needle = mb_strtolower(trim($title));
if ($needle === '') {
return false;
}
$posts = all_posts();
foreach ($posts as $post) {
$post_slug = (string) ($post['slug'] ?? '');
if ($exclude_slug !== '' && $post_slug === $exclude_slug) {
continue;
}
$existing_title = mb_strtolower(trim((string) ($post['title'] ?? '')));
if ($existing_title !== '' && $existing_title === $needle) {
return true;
}
}
return false;
}