-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-post.php
More file actions
527 lines (462 loc) · 20.8 KB
/
create-post.php
File metadata and controls
527 lines (462 loc) · 20.8 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
<?php
session_start();
require_once 'includes/dbh.inc.php';
require_once 'includes/category-functions.inc.php';
// Check if user is logged in and has appropriate role
if (!isset($_SESSION["userid"]) || !in_array($_SESSION["role"], ["admin", "editor"])) {
header("location: login.php");
exit();
}
// Fetch all categories
$categories = getAllCategories($pdo);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create New Post - Blog CMS</title>
<link rel="stylesheet" href="css/admin-style.css">
<!-- Quill CSS -->
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<!-- Tagify CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/tagify/4.17.9/tagify.css" rel="stylesheet">
<link rel="stylesheet" href="css/create-post.css">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<div class="admin-container">
<nav class="admin-nav">
<div class="logo">Blog CMS</div>
<ul>
<li><a href="admin.php">Dashboard</a></li>
<li><a href="admin.php#posts">Posts</a></li>
<li><a href="logout.php">Logout</a></li>
</ul>
</nav>
<main class="admin-main">
<div class="post-form">
<h1>Create New Post</h1>
<form id="createPostForm" onsubmit="return submitPost(event)">
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" id="title" name="title" required>
</div>
<div class="form-group">
<label for="category">Category</label>
<select id="category" name="category" required>
<option value="">Select a category</option>
<?php foreach ($categories as $category): ?>
<option value="<?php echo htmlspecialchars($category['CategoryID']); ?>">
<?php echo htmlspecialchars($category['Name']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="tags">Tags</label>
<input id="tags" name="tags">
</div>
<div class="form-group">
<label>Featured Image</label>
<div class="featured-image-container">
<div class="upload-controls">
<input type="file" id="featuredImageFile" accept="image/*" style="display: none;">
<button type="button" class="btn-secondary" onclick="document.getElementById('featuredImageFile').click()">
Choose Image
</button>
<input type="text" id="featuredImage" name="featuredImage" readonly
placeholder="Upload an image or enter URL">
</div>
<figure id="imagePreviewWrapper" class="blog-image-wrapper medium center" style="display: none;">
<img id="imagePreview" class="blog-content-image" alt="Preview">
<figcaption id="imageCaption" class="blog-image-caption"></figcaption>
</figure>
</div>
</div>
<div class="form-group">
<label>Content</label>
<div class="editor-container">
<div id="editor"></div>
</div>
</div>
<div class="buttons-container">
<button type="button" class="btn-secondary" onclick="saveDraft()">Save as Draft</button>
<button type="submit" class="btn-primary">Publish Post</button>
</div>
</form>
</div>
</main>
</div>
<script src="/js/image-modal.js"></script>
<!-- Quill JS -->
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<!-- Tagify JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tagify/4.17.9/tagify.min.js"></script>
<script>
// Define custom image blot with additional features
const Inline = Quill.import('blots/inline');
const Block = Quill.import('blots/block');
const BlockEmbed = Quill.import('blots/block/embed');
const Parchment = Quill.import('parchment');
class BlogImageBlot extends BlockEmbed {
static create(value) {
// Create figure element (since that's our tagName)
const node = super.create();
node.className = `blog-image-wrapper ${value.size || 'medium'} ${value.alignment || 'center'}`;
if (value.enlargeable !== false) {
node.setAttribute('data-enlargeable', 'true');
}
// Create and append image
const img = document.createElement('img');
img.setAttribute('src', value.src);
img.setAttribute('class', 'blog-content-image');
img.setAttribute('alt', value.alt || '');
node.appendChild(img);
// Add caption if provided
if (value.caption) {
const caption = document.createElement('figcaption');
caption.textContent = value.caption;
caption.className = 'blog-image-caption';
node.appendChild(caption);
}
return node;
}
static value(node) {
const img = node.querySelector('.blog-content-image');
const caption = node.querySelector('.blog-image-caption');
return {
src: img.getAttribute('src'),
alt: img.getAttribute('alt'),
caption: caption ? caption.textContent : null,
size: node.className.match(/\b(small|medium|large|full)\b/)?.[0] || 'medium',
alignment: node.className.match(/\b(left|center|right)\b/)?.[0] || 'center',
enlargeable: node.getAttribute('data-enlargeable') === 'true'
};
}
}
BlogImageBlot.blotName = 'blog-image';
BlogImageBlot.tagName = 'figure';
// Register the custom blot
Quill.register(BlogImageBlot);
// Image toolbar handlers
function imageHandler() {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
input.onchange = async () => {
const file = input.files[0];
const formData = new FormData();
formData.append('image', file);
try {
const response = await fetch('includes/upload-image.inc.php', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
// Show image options dialog
showImageOptionsDialog(result.url);
} else {
alert('Failed to upload image');
}
} catch (error) {
console.error('Error:', error);
alert('Error uploading image');
}
};
}
function showImageOptionsDialog(imageUrl) {
// Create dialog
const dialog = document.createElement('div');
dialog.className = 'image-options-dialog';
dialog.innerHTML = `
<div class="dialog-content">
<h3>Image Options</h3>
<div class="form-group">
<label>Alt Text:</label>
<input type="text" id="image-alt" placeholder="Describe the image">
</div>
<div class="form-group">
<label>Caption:</label>
<input type="text" id="image-caption" placeholder="Optional caption">
</div>
<div class="form-group">
<label>Size:</label>
<select id="image-size">
<option value="small">Small</option>
<option value="medium" selected>Medium</option>
<option value="large">Large</option>
<option value="full">Full Width</option>
</select>
</div>
<div class="form-group">
<label>Alignment:</label>
<select id="image-alignment">
<option value="left">Left</option>
<option value="center" selected>Center</option>
<option value="right">Right</option>
</select>
</div>
<div class="form-group">
<label>
<input type="checkbox" id="image-enlargeable" checked>
Enable click to enlarge
</label>
</div>
<div class="dialog-buttons">
<button class="btn-cancel">Cancel</button>
<button class="btn-insert">Insert Image</button>
</div>
</div>
`;
document.body.appendChild(dialog);
// Handle dialog buttons
const cancelBtn = dialog.querySelector('.btn-cancel');
const insertBtn = dialog.querySelector('.btn-insert');
cancelBtn.onclick = () => document.body.removeChild(dialog);
insertBtn.onclick = () => {
const range = quill.getSelection(true);
const imageData = {
src: imageUrl,
alt: document.getElementById('image-alt').value,
caption: document.getElementById('image-caption').value,
size: document.getElementById('image-size').value,
alignment: document.getElementById('image-alignment').value,
enlargeable: document.getElementById('image-enlargeable').checked
};
quill.insertEmbed(range.index, 'blog-image', imageData, Quill.sources.USER);
quill.setSelection(range.index + 1, Quill.sources.SILENT);
document.body.removeChild(dialog);
};
}
// Register custom YouTube blot
class YouTubeBlot extends BlockEmbed {
static create(value) {
const node = super.create();
node.className = 'blog-video-wrapper';
// Create iframe with safe YouTube embed
const iframe = document.createElement('iframe');
iframe.setAttribute('src', value.src);
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', 'true');
iframe.setAttribute('width', '100%');
iframe.setAttribute('height', '400');
node.appendChild(iframe);
return node;
}
static value(node) {
const iframe = node.querySelector('iframe');
return {
src: iframe.getAttribute('src')
};
}
}
YouTubeBlot.blotName = 'youtube-video';
YouTubeBlot.tagName = 'div';
// Register the custom blot
Quill.register(YouTubeBlot);
const YouTubeFormat = new Parchment.Attributor.Class('youtube', 'ql-youtube', {
scope: Parchment.Scope.INLINE
});
Quill.register(YouTubeFormat);
// Add YouTube handler function
function youtubeHandler() {
const url = prompt('Enter YouTube video URL:');
if (url) {
// Extract video ID from URL
const videoId = extractYouTubeId(url);
if (videoId) {
const embedUrl = `https://www.youtube.com/embed/${videoId}`;
const range = quill.getSelection(true);
quill.insertEmbed(range.index, 'youtube-video', {
src: embedUrl
}, Quill.sources.USER);
quill.setSelection(range.index + 1, Quill.sources.SILENT);
} else {
alert('Invalid YouTube URL');
}
}
}
// Helper function to extract YouTube video ID
function extractYouTubeId(url) {
const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
const match = url.match(regExp);
return (match && match[2].length === 11) ? match[2] : null;
}
// Initialize Quill with YouTube support
var quill = new Quill('#editor', {
theme: 'snow',
modules: {
toolbar: {
container: [
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
['bold', 'italic', 'underline', 'strike'],
['blockquote', 'code-block'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script': 'sub'}, { 'script': 'super' }],
[{ 'indent': '-1'}, { 'indent': '+1' }],
[{ 'color': [] }, { 'background': [] }],
['link', 'image'],
[{ 'youtube': 'YouTube' }],
['clean']
],
handlers: {
'image': imageHandler,
'youtube': youtubeHandler
}
}
}
});
// Initialize Tagify
var input = document.querySelector('input[name=tags]');
var tagify = new Tagify(input, {
maxTags: 10,
dropdown: {
maxItems: 20,
classname: "tags-look",
enabled: 0,
closeOnSelect: false
}
});
function previewImage(url) {
const preview = document.getElementById('imagePreview');
if (url) {
preview.src = url;
preview.style.display = 'block';
} else {
preview.style.display = 'none';
}
}
function submitPost(event) {
event.preventDefault();
const formData = new FormData(event.target);
formData.append('content', quill.root.innerHTML);
formData.append('status', 'published');
formData.append('action', 'create'); // Add this line
// Get featured image caption if it exists
const captionElement = document.getElementById('imageCaption');
if (captionElement && captionElement.textContent) {
formData.append('featuredImageCaption', captionElement.textContent);
}
// Get tags as array
const tags = tagify.value.map(tag => tag.value);
formData.append('tags', JSON.stringify(tags));
fetch('includes/manage-post.inc.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
window.location.href = 'admin.php#posts';
} else {
alert(data.error || 'An error occurred while saving the post');
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while saving the post');
});
return false;
}
function saveDraft() {
const form = document.getElementById('createPostForm');
const formData = new FormData(form);
formData.append('content', quill.root.innerHTML);
formData.append('status', 'draft');
formData.append('action', 'create'); // Add this line
// Get featured image caption if it exists
const captionElement = document.getElementById('imageCaption');
if (captionElement && captionElement.textContent) {
formData.append('featuredImageCaption', captionElement.textContent);
}
const tags = tagify.value.map(tag => tag.value);
formData.append('tags', JSON.stringify(tags));
fetch('includes/manage-post.inc.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('Post saved as draft');
window.location.href = 'admin.php#posts';
} else {
alert(data.error || 'An error occurred while saving the draft');
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while saving the draft');
});
}
</script>
<script>
// Featured Image Upload Handler
document.getElementById('featuredImageFile').addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) return;
const formData = new FormData();
formData.append('image', file);
try {
const response = await fetch('includes/upload-image.inc.php', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
showFeaturedImageOptions(result.url);
} else {
alert('Failed to upload image');
}
} catch (error) {
console.error('Error:', error);
alert('Error uploading image');
}
});
function showFeaturedImageOptions(imageUrl) {
// Create dialog
const dialog = document.createElement('div');
dialog.className = 'image-options-dialog';
dialog.innerHTML = `
<div class="dialog-content">
<h3>Featured Image Options</h3>
<div class="form-group">
<label>Alt Text:</label>
<input type="text" id="featured-image-alt" placeholder="Describe the image">
</div>
<div class="form-group">
<label>Caption:</label>
<input type="text" id="featured-image-caption" placeholder="Optional caption">
</div>
<div class="dialog-buttons">
<button class="btn-cancel">Cancel</button>
<button class="btn-insert">Set Featured Image</button>
</div>
</div>
`;
document.body.appendChild(dialog);
// Handle dialog buttons
const cancelBtn = dialog.querySelector('.btn-cancel');
const insertBtn = dialog.querySelector('.btn-insert');
cancelBtn.onclick = () => document.body.removeChild(dialog);
insertBtn.onclick = () => {
const altText = document.getElementById('featured-image-alt').value;
const caption = document.getElementById('featured-image-caption').value;
// Update hidden input and preview
document.getElementById('featuredImage').value = imageUrl;
const preview = document.getElementById('imagePreview');
const previewWrapper = document.getElementById('imagePreviewWrapper');
const captionElement = document.getElementById('imageCaption');
preview.src = imageUrl;
preview.alt = altText;
captionElement.textContent = caption;
previewWrapper.style.display = caption ? 'block' : 'none';
document.body.removeChild(dialog);
};
}
</script>
</body>
</html>