submit_comment.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. // Start session for captcha verification
  3. if (session_status() === PHP_SESSION_NONE) {
  4. session_start();
  5. }
  6. require_once '../includes/config.php';
  7. require_once '../includes/database.php';
  8. require_once '../includes/comment.php';
  9. require_once '../includes/captcha.php';
  10. require_once '../includes/translation.php';
  11. // Translation system is auto-initialized when translation.php is included
  12. header('Content-Type: application/json');
  13. $response = ['success' => false, 'message' => ''];
  14. // Handle captcha refresh
  15. if ($_GET['action'] === 'refresh_captcha') {
  16. $response['success'] = true;
  17. $response['question'] = Captcha::getAjaxCaptcha()['question'];
  18. echo json_encode($response);
  19. exit;
  20. }
  21. try {
  22. // Only accept POST requests
  23. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  24. throw new Exception('Invalid request method');
  25. }
  26. // Get and validate input
  27. $publicationId = (int)($_POST['publication_id'] ?? 0);
  28. $parent_id = (int)($_POST['parent_id'] ?? 0);
  29. $name = trim($_POST['name'] ?? '');
  30. $email = trim($_POST['email'] ?? '');
  31. $content = trim($_POST['content'] ?? '');
  32. $captchaAnswer = $_POST['captcha_answer'] ?? '';
  33. // Verify captcha
  34. if (!Captcha::verify($captchaAnswer)) {
  35. throw new Exception(t('captcha_invalid'));
  36. }
  37. // Prepare comment data
  38. $commentData = [
  39. 'publication_id' => $publicationId,
  40. 'parent_id' => $parent_id ?: null,
  41. 'name' => $name,
  42. 'email' => $email ?: null,
  43. 'content' => $content
  44. ];
  45. // Create comment instance
  46. $comment = new Comment();
  47. // Validate comment data
  48. $errors = $comment->validate($commentData, false);
  49. if (!empty($errors)) {
  50. throw new Exception(implode(', ', $errors));
  51. }
  52. // Create comment
  53. if ($comment->create($commentData)) {
  54. $response['success'] = true;
  55. $response['message'] = t('comment_submitted_success');
  56. $response['comment_count'] = $comment->getCountByPublication($publicationId);
  57. } else {
  58. throw new Exception(t('comment_submit_error'));
  59. }
  60. } catch (Exception $e) {
  61. $response['message'] = $e->getMessage();
  62. // Log error for debugging
  63. error_log('Comment submission error: ' . $e->getMessage());
  64. }
  65. echo json_encode($response);