/**
 * Store the comment made by a visitor in the database
 *
 * @access public
 * @param   int     The ID of an entry
 * @param   array   An array that holds the input data from the visitor
 * @param   string  The type of a comment (normal/trackback)
 * @param   string  Where did a comment come from? (internal|trackback|plugin)
 * @param   string  Additional plugin data (spamblock plugin etc.)
 * @return  boolean Returns true if the comment could be added
 */
function serendipity_insertComment($id, $commentInfo, $type = 'NORMAL', $source = 'internal', $ca = array())
{
    global $serendipity;
    if (!empty($ca['status'])) {
        $commentInfo['status'] = $ca['status'];
    }
    $title = serendipity_db_escape_string(isset($commentInfo['title']) ? $commentInfo['title'] : '');
    $comments = $commentInfo['comment'];
    $ip = serendipity_db_escape_string(isset($commentInfo['ip']) ? $commentInfo['ip'] : $_SERVER['REMOTE_ADDR']);
    $commentsFixed = serendipity_db_escape_string($commentInfo['comment']);
    $name = serendipity_db_escape_string($commentInfo['name']);
    $url = serendipity_db_escape_string($commentInfo['url']);
    $email = serendipity_db_escape_string($commentInfo['email']);
    $parentid = isset($commentInfo['parent_id']) && is_numeric($commentInfo['parent_id']) ? $commentInfo['parent_id'] : 0;
    $status = serendipity_db_escape_string(isset($commentInfo['status']) ? $commentInfo['status'] : (serendipity_db_bool($ca['moderate_comments']) ? 'pending' : 'approved'));
    $t = serendipity_db_escape_string(isset($commentInfo['time']) ? $commentInfo['time'] : time());
    $referer = substr(isset($_SESSION['HTTP_REFERER']) ? serendipity_db_escape_string($_SESSION['HTTP_REFERER']) : '', 0, 200);
    $query = "SELECT a.email, e.title, a.mail_comments, a.mail_trackbacks\n                FROM {$serendipity['dbPrefix']}entries AS e\n     LEFT OUTER JOIN {$serendipity['dbPrefix']}authors AS a\n                  ON a.authorid = e.authorid\n             WHERE e.id  = '" . (int) $id . "'\n               AND e.isdraft = 'false'";
    if (!serendipity_db_bool($serendipity['showFutureEntries'])) {
        $query .= " AND e.timestamp <= " . serendipity_db_time();
    }
    $row = serendipity_db_query($query, true);
    // Get info on author/entry
    if (!is_array($row) || empty($id)) {
        // No associated entry found.
        if ($GLOBALS['tb_logging']) {
            $fp = fopen('trackback2.log', 'a');
            fwrite($fp, '[' . date('d.m.Y H:i') . '] entry reference not found: ' . $query . "\n");
            fclose($fp);
        }
        return false;
    }
    $send_optin = false;
    if (isset($commentInfo['subscribe'])) {
        if (!isset($serendipity['allowSubscriptionsOptIn']) || $serendipity['allowSubscriptionsOptIn']) {
            $subscribe = 'false';
            $send_optin = true;
        } else {
            $subscribe = 'true';
        }
    } else {
        $subscribe = 'false';
    }
    $dbhash = md5(uniqid(rand(), true));
    if ($status == 'confirm') {
        $dbstatus = 'confirm' . $dbhash;
    } elseif ($status == 'confirm1') {
        $auth = serendipity_db_query("SELECT *\n                                        FROM {$serendipity['dbPrefix']}options\n                                       WHERE okey  = 'mail_confirm'\n                                         AND name  = '" . $email . "'\n                                         AND value = '" . $name . "'", true);
        if (!is_array($auth)) {
            serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}options (okey, name, value)\n                                       VALUES ('mail_confirm{$dbhash}', '{$email}', '{$name}')");
            $dbstatus = 'confirm' . $dbhash;
        } else {
            $serendipity['csuccess'] = 'true';
            $status = $dbstatus = 'approved';
        }
    } else {
        $dbstatus = $status;
    }
    $query = "INSERT INTO {$serendipity['dbPrefix']}comments (entry_id, parent_id, ip, author, email, url, body, type, timestamp, title, subscribed, status, referer)";
    $query .= " VALUES ('" . (int) $id . "', '{$parentid}', '{$ip}', '{$name}', '{$email}', '{$url}', '{$commentsFixed}', '{$type}', '{$t}', '{$title}', '{$subscribe}', '{$dbstatus}', '{$referer}')";
    if ($GLOBALS['tb_logging']) {
        $fp = fopen('trackback2.log', 'a');
        fwrite($fp, '[' . date('d.m.Y H:i') . '] SQL: ' . $query . "\n");
    }
    serendipity_db_query($query);
    $cid = serendipity_db_insert_id('comments', 'id');
    // Send mail to the author if he chose to receive these mails, or if the comment is awaiting moderation
    if ($status != 'confirm' && (serendipity_db_bool($ca['moderate_comments']) || $type == 'NORMAL' && serendipity_db_bool($row['mail_comments']) || $type == 'TRACKBACK' && serendipity_db_bool($row['mail_trackbacks']))) {
        serendipity_sendComment($cid, $row['email'], $name, $email, $url, $id, $row['title'], $comments, $type, serendipity_db_bool($ca['moderate_comments']));
    }
    // Approve with force, if moderation is disabled
    if ($GLOBALS['tb_logging']) {
        fwrite($fp, '[' . date('d.m.Y H:i') . '] status: ' . $status . ', moderate: ' . $ca['moderate_comments'] . "\n");
    }
    if ($status != 'confirm' && (empty($ca['moderate_comments']) || serendipity_db_bool($ca['moderate_comments']) == false)) {
        if ($GLOBALS['tb_logging']) {
            fwrite($fp, '[' . date('d.m.Y H:i') . '] Approving...' . "\n");
        }
        serendipity_approveComment($cid, $id, true);
    } elseif ($GLOBALS['tb_logging']) {
        fwrite($fp, '[' . date('d.m.Y H:i') . '] No need to approve...' . "\n");
    }
    if ($status == 'confirm') {
        $subject = sprintf(NEW_COMMENT_TO_SUBSCRIBED_ENTRY, $row['title']);
        $message = sprintf(CONFIRMATION_MAIL_ALWAYS, $name, $row['title'], $commentsFixed, $serendipity['baseURL'] . 'comment.php?c=' . $cid . '&hash=' . $dbhash);
        serendipity_sendMail($email, $subject, $message, $serendipity['blogMail']);
    } elseif ($status == 'confirm1') {
        $subject = sprintf(NEW_COMMENT_TO_SUBSCRIBED_ENTRY, $row['title']);
        $message = sprintf(CONFIRMATION_MAIL_ONCE, $name, $row['title'], $commentsFixed, $serendipity['baseURL'] . 'comment.php?c=' . $cid . '&hash=' . $dbhash);
        serendipity_sendMail($email, $subject, $message, $serendipity['blogMail']);
    }
    if ($send_optin) {
        $dupe_check = serendipity_db_query("SELECT count(entry_id) AS counter\n                                              FROM {$serendipity['dbPrefix']}comments\n                                             WHERE entry_id = " . (int) $id . "\n                                               AND email = '{$email}'\n                                               AND subscribed = 'true'", true);
        if (!is_array($dupe_check) || $dupe_check['counter'] < 1) {
            serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}options (okey, name, value)\n                                       VALUES ('commentsub_{$dbhash}', '" . time() . "', '{$cid}')");
            $subject = sprintf(NEW_COMMENT_TO_SUBSCRIBED_ENTRY, $row['title']);
            $message = sprintf(CONFIRMATION_MAIL_SUBSCRIPTION, $name, $row['title'], serendipity_archiveURL($id, $row['title'], 'baseURL'), $serendipity['baseURL'] . 'comment.php?optin=' . $dbhash);
            serendipity_sendMail($email, $subject, $message, $serendipity['blogMail']);
        }
    }
    serendipity_purgeEntry($id, $t);
    if ($GLOBALS['tb_logging']) {
        fclose($fp);
    }
    return $cid;
}
 function workComment($id, $commentInfo, $type = 'NORMAL', $source = 'internal')
 {
     global $serendipity;
     $query = "SELECT id, allow_comments, moderate_comments, last_modified, timestamp, title FROM {$serendipity['dbPrefix']}entries WHERE id = '" . (int) $id . "'";
     $ca = serendipity_db_query($query, true);
     $commentInfo['type'] = $type;
     $commentInfo['source'] = $source;
     // serendipity_plugin_api::hook_event('frontend_saveComment', $ca, $commentInfo);
     if (!is_array($ca) || serendipity_db_bool($ca['allow_comments'])) {
         $title = serendipity_db_escape_string(isset($commentInfo['title']) ? $commentInfo['title'] : '');
         $comments = $commentInfo['comment'];
         $ip = serendipity_db_escape_string(isset($commentInfo['ip']) ? $commentInfo['ip'] : $_SERVER['REMOTE_ADDR']);
         $commentsFixed = serendipity_db_escape_string($commentInfo['comment']);
         $name = serendipity_db_escape_string($commentInfo['name']);
         $url = serendipity_db_escape_string($commentInfo['url']);
         $email = serendipity_db_escape_string($commentInfo['email']);
         $parentid = isset($commentInfo['parent_id']) && is_numeric($commentInfo['parent_id']) ? $commentInfo['parent_id'] : 0;
         $status = serendipity_db_escape_string(isset($commentInfo['status']) ? $commentInfo['status'] : (serendipity_db_bool($ca['moderate_comments']) ? 'pending' : 'approved'));
         $t = serendipity_db_escape_string(isset($commentInfo['time']) ? $commentInfo['time'] : time());
         $referer = substr(isset($_SESSION['HTTP_REFERER']) ? serendipity_db_escape_string($_SESSION['HTTP_REFERER']) : '', 0, 200);
         $query = "SELECT a.email, e.title, a.mail_comments, a.mail_trackbacks\n                     FROM {$serendipity['dbPrefix']}entries e, {$serendipity['dbPrefix']}authors a\n                     WHERE e.id  = '" . (int) $id . "'\n                       AND e.isdraft = 'false'\n                       AND e.authorid = a.authorid";
         if (!serendipity_db_bool($serendipity['showFutureEntries'])) {
             $query .= " AND e.timestamp <= " . serendipity_db_time();
         }
         $row = serendipity_db_query($query, true);
         // Get info on author/entry
         if (!is_array($row) || empty($id)) {
             // No associated entry found.
             return false;
         }
         if (isset($commentInfo['subscribe'])) {
             $subscribe = 'true';
         } else {
             $subscribe = 'false';
         }
         $query = "INSERT INTO {$serendipity['dbPrefix']}comments (entry_id, parent_id, ip, author, email, url, body, type, timestamp, title, subscribed, status, referer)";
         $query .= " VALUES ('" . (int) $id . "', '{$parentid}', '{$ip}', '{$name}', '{$email}', '{$url}', '{$commentsFixed}', '{$type}', '{$t}', '{$title}', '{$subscribe}', '{$status}', '{$referer}')";
         serendipity_db_query($query);
         $cid = serendipity_db_insert_id('comments', 'id');
         // Send mail to the author if he chose to receive these mails, or if the comment is awaiting moderation
         if (serendipity_db_bool($ca['moderate_comments']) || $type == 'NORMAL' && serendipity_db_bool($row['mail_comments']) || $type == 'TRACKBACK' && serendipity_db_bool($row['mail_trackbacks'])) {
             serendipity_sendComment($cid, $row['email'], $name, $email, $url, $id, $row['title'], $comments, $type, serendipity_db_bool($ca['moderate_comments']));
         }
         serendipity_approveComment($cid, $id, true);
         serendipity_purgeEntry($id, $t);
         return $cid;
     } else {
         return false;
     }
 }