<?php
use Mnv\Core\Config;

if (!defined('SITE_URL')) {

    include_once('../includes/visitor.inc.php');
    global $smarty, $visitorIp, $visitorId;

    $errors = null;
    $success = null;

    $commentId   = request()->get('commentId');
    $commentCode = request()->get('commentCode');
		
    if (empty($commentId) || empty($commentCode)) die('Hacking attempt!');

    if ($comment = connect()->table('comments')->where('commentId',  $commentId)->where('status','=', 'unconfirmed')->get()) {

        /* load article */
        $article = connect()->table('article')->where('articleId',  $comment['articleId'])->get();
        $smarty->assign('article', $article);
        $smarty->assign('comment', $comment);
			
        if ($commentCode == substr(md5($comment->authorEmail.$comment->addedOn.AP_SERIAL.SITE_ROOT.'AbBra-cAda8Ra'), 0, 12)) {

            $comment->status = 'approved';
            /* apply HOLD filters to the comment */
            if(!Config::getValue('comments_must_be_approved') && !empty(Config::getValue('comments_hold_words'))){
                $holdWords = preg_split('/[\r\n]+/', Config::getValue('comments_hold_words'));
                $holdWords = array_map('preg_quote', $holdWords);
                $regex = '/'.implode('|', $holdWords).'/i';
                if(preg_match($regex, $comment->content) || preg_match($regex, $comment->authorIp) || preg_match($regex, $comment->authorEmail) || preg_match($regex, $comment->authorName)){
                    $comment->status = 'pending';
                }
            }
				
            /* check if all comments must be approved manually */
            if (Config::getValue('comments_must_be_approved')) $comment->status = 'pending';

            /* mark comment as SPAM if commenter had a SPAM comment previously */
            if(Config::getValue('comments_blacklist_enabled')){
                connect()->where('authorEmail', '=', $comment->authorEmail);
                connect()->where('authorName', '=', $comment->authorName);
                connect()->where('status', '<>', 'unconfirmed');
                if (connect()->table('comments')->select('status')->orderBy('addedOn DESC')->getValue() == 'spam') $comment->status = 'spam';
            }

            /* avoid moderation if commenter has a previously approved comment */
            if ($comment->status != 'spam' && Config::getValue('comments_whitelist_enabled')){
                connect()->where('authorEmail', '=', $comment->authorEmail);
                connect()->where('authorName', '=', $comment->authorName);
                connect()->where('status', '<>', 'unconfirmed');
                if (connect()->table('comments')->select('status')->orderBy('addedOn DESC')->getValue() == 'approved') $comment->status = 'approved';
            }

            connect()->table('comments')->where('commentId','=',$comment->commentId)->update(['status' => $comment->status]);
            if ($comment->status == 'approved') {
                $success['comment_published'] = true;
            } else {
                $success['comment_saved'] = true;
            }

        } else {
            $success['incorrect_code'] = true;
        }
    } else {
        $success['comment_not_found'] = true;
    }

    $smarty->assign('success', $success);
//    $smarty->display('modules/commenting.tpl');

} else {

    global $smarty, $article, $visitorIp, $visitorId, $userAuth;

    $comment    = request('newComment');
    $errors = null;
    $success = null;

    if (!empty($comment) && $article->commentsEnabled) {

//        $comment['authorName']  = Session::get('siteUser')['site_user_first_name'];
//        $comment['authorEmail'] = Session::get('siteUser')['site_user_username'];

//		/** checking contact email */
//		$comment['authorEmail'] = trim($comment['authorEmail']);
//		if (!preg_match('/^[A-Z0-9\._\-]+@[A-Z0-9\.\-]+\.[A-Z]{2,4}$/i', $comment['authorEmail'])) $errors['authorEmail'] = true;

        /** checking author name */
        if (empty($comment['authorName'])) $errors['authorName'] = true;
        /** removing HTML tags from comment */
        $comment['content'] = Config::getValue('comments_strip_html') ? stripHtml($comment['content']) : $comment['content'];

        /** trim */
        $comment['content']     = trim($comment['content']);
//        $comment['authorEmail'] = trim($comment['authorEmail']);
        $comment['authorName']  = trim($comment['authorName']);
			
        /** checking whether content is empty */
        if(empty($comment['content'])) $errors['content'] = true;
			/* checking CAPTCHA */
//			if(!empty(Config::getValue('comments_captcha_enabled')) && (empty($comment['captcha']) || $_SESSION['captcha'] != md5($comment['captcha']))) $errors['captcha'] = true;
			
        /* checking for duplicate comment */
        if(connect()->table('comments')
            ->where('authorName', '=', $comment['authorName'])
//            ->where('authorEmail','=', $comment['authorEmail'])
            ->where('content', '=', $comment['content'])
            ->get()){
				$errors['duplicate_comment'] = true;
                $success['duplicate_comment'] = true;
        }

        if (empty($errors)) {
//			$comment['commentId']   = '';
            $comment['articleId']   = $article->articleId;
            $comment['userId']      = $userAuth->id();
            $comment['visitorId']   = $visitorId;
            $comment['authorIp']    = $visitorIp;
            $comment['answerId']    = !empty($comment['answerId']) ? $comment['answerId'] : 0;
            $comment['addedOn']     = gmdate('Y-m-d H:i:s');
            $comment['modifiedBy']  = 0;
            $comment['modifiedOn']  = gmdate('Y-m-d H:i:s');
            $comment['status']      = 'approved';

//            	print_r($comment);
            /* apply SPAM filters to the comment */
            if (!empty(Config::getValue('comments_spam_words'))) {
                $spamWords = preg_split('/[\r\n]+/', Config::getValue('comments_spam_words'));
                $spamWords = array_map('preg_quote', $spamWords);
                $regex = '/'.implode('|', $spamWords).'/i';
                if(preg_match($regex, $comment['content']) || preg_match($regex, $comment['authorIp']) || preg_match($regex, $comment['authorName'])){
                    $comment['status'] = 'spam';
                }
            }
				
            /* apply HOLD filters to the comment */
            if (($comment['status'] != 'spam') && !Config::getValue('comments_must_be_approved') && !empty(Config::getValue('comments_hold_words'))) {
                $holdWords = preg_split('/[\r\n]+/', Config::getValue('comments_hold_words'));
                $holdWords = array_map('preg_quote', $holdWords);
                $regex = '/'.implode('|', $holdWords).'/i';
                if (preg_match($regex, $comment['content']) || preg_match($regex, $comment['authorIp']) || preg_match($regex, $comment['authorName'])) {
                    $comment['status'] = 'pending';
                }
            }
				
            /* check if all comments must be approved manually */
            if($comment['status'] != 'spam' && Config::getValue('comments_must_be_approved')) $comment['status'] = 'pending';

            /** mark comment as SPAM if commenter had a SPAM comment previously */
            if($comment['status'] != 'spam' && Config::getValue('comments_blacklist_enabled')){
                connect()->where('authorEmail', '=', $comment['authorEmail']);
                connect()->where('authorName', '=', $comment['authorName']);
                if (connect()->table('comments')->select('status')->orderBy('addedOn DESC')->getValue() == 'spam') $comment->status = 'spam';
            }

            /** avoid moderation if commenter has a previously approved comment */
            if($comment['status'] != 'spam' && Config::getValue('comments_whitelist_enabled')){
                connect()->where('authorEmail', $comment->authorEmail);
                connect()->where('authorName', $comment->authorName);
                if (connect()->table('comments')->select('status')->orderBy('addedOn DESC')->getValue() == 'approved') $comment->status = 'approved';
            }

            /* email confirmation */
            if (Config::getValue('comments_email_confirmation_required') == 1) {
                /* confirm once */
//                connect()->where('authorEmail', '=', $comment['authorEmail']);
                connect()->where('authorName', '=', $comment['authorName']);
                connect()->in('status', ['pending', 'approved']);
                if (!connect()->table('comments')->select('commentId')->limit(1)->getValue()) {
                    $comment['status'] = 'unconfirmed';
                }
            } elseif(Config::getValue('comments_email_confirmation_required') == 2) {
                /* confirm each time */
                $comment['status'] = 'unconfirmed';
            }


            $comment['commentId'] = connect()->table('comments')->insert($comment);

            if ($comment['status'] == 'approved') {
                $success['duplicate_comment'] = true;
            } elseif($comment['status'] == 'unconfirmed') {
                $smarty->assign('commentId', $comment['commentId']);
                $smarty->assign('commentCode', substr(md5($comment['authorName'].$comment['addedOn'].AP_SERIAL.SITE_ROOT.'AbBra-cAda8Ra'), 0, 12));

                $recipient = $comment['authorEmail'];
                $subject   = '=?'.Config::getValue('charset').'?B?'.base64_encode('Email Confirmation').'?=';
                $message   = chunk_split(base64_encode($smarty->fetch('commenting-confirmation.tpl')), 68, "\n");
                $headers   = 'From: '.'NO-REPLY'.preg_replace('/^.+(@.+)$/', '$1',Config::getValue('feedback_email'))."\nContent-Type: text/plain; charset=".Config::getValue('charset')."\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64";

                mail($recipient, $subject, $message, $headers);

                $success['confirm_email'] = true;
            }
            else {
                $success['comment_saved'] = true;
            }

            $smarty->assign('success', $success);
            $smarty->assign('newComment', array());
				
            /** delete unconfirmed comments */
            connect()->table('comments')->where('status', '=', 'unconfirmed')->where('addedOn', '<', gmdate('Y-m-d H:i:s', time() - 86400*3))->delete();
            /** delete spam comments */
            connect()->table('comments')->where('status', '=', 'spam')->where('addedOn', '<', gmdate('Y-m-d H:i:s', time() - 86400*3))->delete();


        } else {
//            print_r($errors);
            $smarty->assign('success', $success);
            $smarty->assign('errors', $errors);
        }
    }
}

$smarty->display('modules/commenting.tpl');