$review = $http_post->review;
$product_id = intval($review->product_id);
$rating = intval($review->product_rating);
$captcha_id = intval($review->captcha_id);
$captcha_value = intval($review->captcha_value);
$product_name = htmlentities(strip_tags($review->product_name));
$product_review = htmlentities(strip_tags($review->product_review));
$name = htmlentities(strip_tags($review->user_name));
$phone = htmlentities(strip_tags($review->user_phone));
$email = htmlentities(strip_tags($review->user_email));
$options = $app->fetchAll('SELECT * FROM `options`');
if (count($options)) {
    foreach ($options as $key => $option) {
        ${$option}['name'] = $option['value'];
    }
    if ($app->execCount("DELETE FROM captchas WHERE id = {$captcha_id} AND value = {$captcha_value}")) {
        if ($product_id and $name and $phone and $email) {
            $num = $app->fetch("SELECT COUNT(*) FROM `reviews` WHERE `mail` = '{$email}' AND `product_id` = {$product_id}")['COUNT(*)'];
            if ($num) {
                $return['error'] .= $error_count++ . '. На этот товар вы уже оставили отзыв!';
            } else {
                if (preg_match('#(.+)@(.+)\\.(.){2,6}#', $email) and strlen($email) < 100) {
                    $code = md5(crypt($email, 'mms_shop'));
                    $num = $app->execCount("INSERT INTO `reviews` (`name`, `phone`, `mail`, `review`, `product_id`, `product_name`," . " `rating`, `code`, `approved`, `create_tm`, `approve_tm`, `ip`) VALUES (" . $app->pdo->quote($name) . ", " . $app->pdo->quote($phone) . ", " . $app->pdo->quote($email) . ", " . $app->pdo->quote($product_review) . ", {$product_id}, " . $app->pdo->quote($product_name) . ", {$rating}, '{$code}', 0, " . time() . ", 0, '" . $_SERVER['REMOTE_ADDR'] . "' )");
                    if ($num) {
                        // Sends email to customer to approve subscription
                        $app->myMail($email, 'Отзыв в MinskElectro', "<html><body><h1>Здравствуйте, {$name}.</h1>" . "E-mail {$email} был указан при добавлении отзыва на сайте MinskElectro.com. Для подтверждения вам следует перейти по <a href='http://www.minskelectro.com/?confirm={$code}'>этой ссылке</a>." . "<p>С уважением,<br>MinskElectro.com</p>" . "</body></html>", 'MinskElectro', $order_mail);
                        $return['success'] .= $success_count++ . '. Сообщение для подтверждения отправлено.';
                    } else {
                        $return['error'] .= $error_count++ . '. Отзыв не добавлен из-за ошибки сервера.';
                    }
$options = $app->fetchAll('SELECT * FROM `options`');
if (count($options)) {
    foreach ($options as $key => $option) {
        ${$option}['name'] = $option['value'];
    }
    $code = isset($_GET['code']) ? htmlentities(strip_tags($_GET['code'])) : '';
    $command = isset($_GET['command']) ? htmlentities(strip_tags($_GET['command'])) : '';
    switch ($command) {
        case 'review':
            $num = $app->fetch("SELECT COUNT(*) FROM `reviews` WHERE `code` = " . $app->pdo->quote($code))['COUNT(*)'];
            if ($num) {
                $review = $app->fetch("SELECT * FROM `reviews` WHERE `code` = " . $app->pdo->quote($code));
                if ($review['approved'] == 1) {
                    $return['success'] .= $success_count++ . '. Ваш e-mail уже подтверждён. ';
                } else {
                    $num = $app->execCount("UPDATE `reviews` SET `approved` = 1, `approve_tm` = " . time() . " WHERE `code` = " . $app->pdo->quote($code));
                    if ($num) {
                        $return['success'] .= $success_count++ . '. Ваш отзыв подтверждён.';
                        // Sends email to customer about confirming subscription
                        if ($app->myMail($review['mail'], 'ME Notification', "<html><body>Отзыв подтверждён.<br><br>{$review['review']}</body></html>")) {
                            $return['success'] .= $success_count++ . '. Письмо об успешном подтверждении отзыва отправлено.';
                        }
                        // Sends email to admin about confirming subscription
                        if ($app->myMail($order_mail, 'ME Notification', "<html><body>E-mail {$review['mail']} подтверждён.<br><br>{$review['review']}</body></html>")) {
                            $return['success'] .= $success_count++ . '. Письмо об успешном подтверждении отзыва отправлено.';
                        }
                    } else {
                        $return['error'] .= $error_count++ . '. Не удалось обновить статус отзыва на сервере. ';
                    }
                }
            } else {
include 'app.inc';
$app = new App();
$font = 'captcha.ttf';
$charset = '0123456789';
// list possible characters to include on the CAPTCHA
$code_length = 4;
// how many characters include in the CAPTCHA
$height = 16;
// antispam image height
$width = 50;
// antispam image width
$code = '';
for ($i = 0; $i < $code_length; $i++) {
    $code = $code . substr($charset, mt_rand(0, strlen($charset) - 1), 1);
}
$ins = $app->execCount("INSERT INTO captchas (id, value, create_tm, ip, useragent_md5) VALUES ({$_GET['id']}, {$code}, " . ($t = time()) . ", '" . $_SERVER['REMOTE_ADDR'] . "', '" . md5($_SERVER['HTTP_USER_AGENT']) . "')");
$del = $app->execCount("DELETE FROM captchas WHERE abs( {$t} - create_tm ) > 10 * 60");
if ($ins) {
    $app->myLog(LOG_INFO, "CAPTCHA set: captcha_id = {$_GET['id']}, captcha_value = {$code}");
} else {
    $app->myLog(LOG_INFO, "CAPTCHA set error: inserted {$ins}, deleted {$del}");
}
$font_size = $height * 0.7;
$image = imagecreate($width, $height);
$background_color = imagecolorallocate($image, 255, 255, 255);
$noise_color = imagecolorallocate($image, 200, 200, 200);
// add image noise
for ($i = 0; $i < $width * $height / 4; $i++) {
    imageellipse($image, mt_rand(0, $width), mt_rand(0, $height), 1, 1, $noise_color);
}
// render text
$app = new App();
$error_count = 1;
$success_count = 1;
$return = array('success' => '', 'error' => '');
// AngularJS transmits data using Content-Type: application/json and JSON serialization,
// which unfortunately some Web server languages—notably PHP—do not unserialize natively.
// So server has empty $_POST array.
$feedback = json_decode(file_get_contents("php://input"));
$captcha_id = intval($feedback->captcha_id);
$captcha_value = intval($feedback->captcha_value);
$options = $app->fetchAll('SELECT * FROM `options`');
if (count($options)) {
    foreach ($options as $key => $option) {
        ${$option}['name'] = $option['value'];
    }
    if ($app->execCount("DELETE FROM captchas WHERE id = {$captcha_id} AND value = {$captcha_value}")) {
        try {
            $app->myMail($order_mail, $feedback->subject, $feedback->message);
        } catch (myException $e) {
            $return['error'] .= $error_count++ . '. ' . $e->getMessage();
        }
        if (!$return['error']) {
            $return['success'] .= $success_count++ . '. Ваше сообщение отправлено!';
        }
    } else {
        $return['error'] .= $error_count++ . '. Неправильно введены цифры с картинки!';
    }
} else {
    $return['error'] .= $error_count++ . '. Количество опций: 0.';
}
echo json_encode($return);
 // delivery free
 $p = (int) $delivery_cost;
 // delivery price
 $captcha_id = intval($order->user->captcha->id);
 $captcha_value = intval($order->user->captcha->value);
 $name = htmlentities(strip_tags($order->user->name));
 $phone = htmlentities(strip_tags($order->user->phone));
 $address = htmlentities(strip_tags($order->user->address));
 $email = isset($order->user->email) ? htmlentities(strip_tags($order->user->email)) : '';
 $comment = isset($order->user->comment) ? htmlentities(strip_tags($order->user->comment)) : '';
 $referral = isset($order->user->referral) ? htmlentities(strip_tags($order->user->referral)) : '';
 $subscribe = isset($order->user->subscribe) ? htmlentities(strip_tags($order->user->subscribe)) : '';
 $subscribe_now = '';
 $subscribe_already = '';
 $subscribe_decline = '';
 if ($app->execCount("DELETE FROM captchas WHERE id = {$captcha_id} AND value = {$captcha_value}")) {
     if (count($order->product)) {
         if ($name and $phone and $address) {
             if ($subscribe and $email) {
                 $num = $app->fetch("SELECT COUNT(*) FROM `subscribes` WHERE `mail` = '" . $email . "'")['COUNT(*)'];
                 if ($num) {
                     $code = $app->fetch("SELECT `code` FROM `subscribes` WHERE `mail`= '" . $email . "'")[0];
                     $subscribe_already = "подписаны ранее";
                 } else {
                     if (preg_match('#(.+)@(.+)\\.(.){2,6}#', $email) and strlen($email) < 100) {
                         $code = md5(crypt($email, 'mms_shop'));
                         $num = $app->execCount("INSERT INTO subscribes (`name`, `mail`, `code`, `approved`, `create_tm`, `approve_tm`, `ip`) VALUES (" . $app->pdo->quote($name) . ", " . $app->pdo->quote($email) . ", '" . $code . "', 0, " . time() . ", 0, '" . $_SERVER['REMOTE_ADDR'] . "' )");
                         $subscribe_now = "подписаны сейчас";
                         // Sends email to customer to approve subscription
                         $app->myMail($email, 'Подписка в MinskElectro', "<html><body><h1>Здравствуйте, {$name}.</h1>" . "E-mail {$email} был указан при подписке на новости сайта MinskElectro.com. Для подтверждения подписки вам следует перейти по <a href='http://www.minskelectro.com/?subscribe={$code}'>этой ссылке</a>." . "<p>С уважением,<br>MinskElectro.com</p>" . "</body></html>", 'MinskElectro', $order_mail);
                         $return['success'] .= $success_count++ . '. Subscription e-mail sent to the customer.';