Example #1
0
function tzs_edit_truck($id)
{
    $input_city = isset($_POST['input_city']) ? $_POST['input_city'] : array();
    $path_segment_distance = get_param('path_segment_distance');
    $tr_active = get_param_def('tr_active', '0');
    $tr_date_from = get_param('tr_date_from');
    $tr_date_to = get_param('tr_date_to');
    $comment = get_param('comment');
    $sh_descr = get_param('sh_descr');
    if (count($input_city) > 1) {
        $tr_city_from = $input_city[0];
        $tr_city_to = $input_city[count($input_city) - 1];
        $path_segment_cities = implode(";", $input_city);
    } else {
        $tr_city_from = get_param('tr_city_from');
        $tr_city_to = get_param('tr_city_to');
        $path_segment_cities = '';
    }
    $tr_weight = get_param_def('tr_weight', '0');
    $tr_volume = get_param_def('tr_volume', '0');
    $trans_type = get_param('trans_type');
    $tr_type = get_param_def('tr_type', '0');
    $trans_count = get_param('trans_count');
    $set_dim = isset($_POST['set_dim']);
    $tr_length = get_param('tr_length');
    $tr_height = get_param('tr_height');
    $tr_width = get_param('tr_width');
    $cost = get_param_def('cost', '0');
    $price = get_param_def('price', '0');
    $cost_curr = get_param_def('cost_curr', '1');
    $prepayment = get_param('prepayment');
    $price_query = isset($_POST['price_query']) ? 1 : 0;
    $cash = isset($_POST['cash']) ? 1 : 0;
    $nocash = isset($_POST['nocash']) ? 1 : 0;
    $way_ship = isset($_POST['way_ship']) ? 1 : 0;
    $way_debark = isset($_POST['way_debark']) ? 1 : 0;
    $soft = isset($_POST['soft']) ? 1 : 0;
    $way_prepay = isset($_POST['way_prepay']) ? 1 : 0;
    $top_loading = isset($_POST['top_loading']) ? 1 : 0;
    $side_loading = isset($_POST['side_loading']) ? 1 : 0;
    $back_loading = isset($_POST['back_loading']) ? 1 : 0;
    $full_movable = isset($_POST['full_movable']) ? 1 : 0;
    $remove_cross = isset($_POST['remove_cross']) ? 1 : 0;
    $remove_racks = isset($_POST['remove_racks']) ? 1 : 0;
    $without_gate = isset($_POST['without_gate']) ? 1 : 0;
    // Контроль пересечения дат
    $tr_date_from_str = date("Ymd", strtotime($tr_date_from));
    $tr_date_to_str = date("Ymd", strtotime($tr_date_to));
    $tr_date_from = is_valid_date($tr_date_from);
    $tr_date_to = is_valid_date($tr_date_to);
    // Замена "," на точку "." в числах
    $tr_weight = str_replace(',', '.', $tr_weight);
    $tr_volume = str_replace(',', '.', $tr_volume);
    $tr_length = str_replace(',', '.', $tr_length);
    $tr_height = str_replace(',', '.', $tr_height);
    $tr_width = str_replace(',', '.', $tr_width);
    $cost = str_replace(',', '.', $cost);
    $price = str_replace(',', '.', $price);
    $prepayment = str_replace(',', '.', $prepayment);
    $errors = array();
    if ($price_query && !is_valid_num_zero($cost) || !$price_query && !is_valid_num($cost)) {
        array_push($errors, "Неверно задана стоимость");
    }
    if ($price_query && !is_valid_num_zero($price) || !$price_query && !is_valid_num($price)) {
        array_push($errors, "Неверно задана цена");
    }
    if (!is_valid_num($cost_curr) || !isset($GLOBALS['tzs_curr'][intval($cost_curr)])) {
        array_push($errors, "Неверно задана валюта");
    }
    if ($way_prepay && (!is_valid_num($prepayment) || floatval($prepayment) > 100)) {
        array_push($errors, "Неверно задан размер предоплаты");
    }
    if (!$price_query && !$cash && !$nocash && !way_ship && !way_debark) {
        array_push($errors, "Необходимо выбрать хотя бы один способ в блоке \"Форма расчета\".");
    }
    if ($tr_date_from == null || $tr_date_to == null) {
        array_push($errors, "Неверный формат даты");
    }
    // Контроль пересечения дат
    if ($tr_date_to_str < $tr_date_from_str) {
        array_push($errors, "Дата выгрузки не может быть РАНЬШЕ даты погрузки");
    }
    if (count($input_city) > 1) {
        for ($i = 0; $i < count($input_city); $i++) {
            if (!is_valid_city($input_city[$i])) {
                array_push($errors, "Укажите пункт маршрута № " . ($i + 1));
            }
        }
    } else {
        if (!is_valid_city($tr_city_from)) {
            array_push($errors, "Неверный пункт погрузки");
        }
        if (!is_valid_city($tr_city_to)) {
            array_push($errors, "Неверный пункт разгрузки");
        }
    }
    if (!is_valid_num_zero($tr_weight)) {
        array_push($errors, "Неверно задан вес");
    }
    if (!is_valid_num_zero($tr_volume)) {
        array_push($errors, "Неверно задан объем");
    }
    if (strlen($trans_count) == 0) {
        $trans_count = '1';
    }
    if (!is_valid_num($trans_count)) {
        array_push($errors, "Неверно задано количество машин");
    }
    if (!is_numeric($trans_type) || intval($trans_type) < 1) {
        array_push($errors, "Неверно задан тип транспортного средства");
    }
    if (!is_numeric($tr_active) || intval($tr_active) < 0) {
        array_push($errors, "Неверно задан статус заявки");
    }
    if (!is_numeric($tr_type) || intval($tr_type) < 0 || intval($tr_type) > 3) {
        array_push($errors, "Неверно задан тип");
    }
    if ($set_dim) {
        if (!is_valid_num($tr_length)) {
            array_push($errors, "Неверно задана длина транспортного средства");
        }
        if (!is_valid_num($tr_width)) {
            array_push($errors, "Неверно задана ширина транспортного средства");
        }
        if (!is_valid_num($tr_height)) {
            array_push($errors, "Неверно задана высота транспортного средства");
        }
    } else {
        $tr_length = '0';
        $tr_width = '0';
        $tr_height = '0';
    }
    $user_id = get_current_user_id();
    $from_info = null;
    $to_info = null;
    if (count($errors) == 0) {
        if (count($input_city) > 1) {
            for ($i = 0; $i < count($input_city); $i++) {
                $city_info = tzs_yahoo_convert($input_city[$i]);
                if (isset($city_info["error"])) {
                    array_push($errors, "Не удалось распознать населенный пункт маршрута № " . ($i + 1) . ": " . $city_info["error"]);
                }
                if ($i == 0) {
                    $from_info = $city_info;
                }
                if ($i == count($input_city) - 1) {
                    $to_info = $city_info;
                }
            }
        } else {
            $from_info = tzs_yahoo_convert($tr_city_from);
            if (isset($from_info["error"])) {
                array_push($errors, "Не удалось распознать населенный пункт погрузки: " . $from_info["error"]);
            }
            $to_info = tzs_yahoo_convert($tr_city_to);
            if (isset($to_info["error"])) {
                array_push($errors, "Не удалось распознать населенный пункт выгрузки: " . $to_info["error"]);
            }
        }
    }
    if (count($errors) > 0) {
        tzs_print_truck_form($errors, $id > 0);
    } else {
        global $wpdb;
        $tr_date_from = date('Y-m-d', mktime(0, 0, 0, $tr_date_from['month'], $tr_date_from['day'], $tr_date_from['year']));
        $tr_date_to = date('Y-m-d', mktime(0, 0, 0, $tr_date_to['month'], $tr_date_to['day'], $tr_date_to['year']));
        $temp = $from_info['city_id'];
        $sql = "SELECT lat,lng FROM " . TZS_CITIES_TABLE . " WHERE city_id={$temp};";
        $row1 = $wpdb->get_row($sql);
        $temp = $to_info['city_id'];
        $sql = "SELECT lat,lng FROM " . TZS_CITIES_TABLE . " WHERE city_id={$temp};";
        $row2 = $wpdb->get_row($sql);
        //$dis = tzs_calculate_distance(array($tr_city_from, $tr_city_to));
        //$dis = get_param('length');
        $sh_distance = get_param('sh_distance');
        if ($id == 0) {
            $sql = $wpdb->prepare("INSERT INTO " . TZS_TRUCK_TABLE . " (time, last_edited, user_id, tr_date_from, tr_date_to, tr_city_from, tr_city_to, tr_weight, tr_volume, tr_length, tr_height, tr_width, trans_count, trans_type, active, tr_type, comment, distance," . " from_cid,from_rid,from_sid,to_cid,to_rid,to_sid,price,price_val,sh_descr, cost, cash, nocash, way_ship, way_debark, soft, way_prepay, prepayment, price_query," . " top_loading, side_loading, back_loading, full_movable, remove_cross, remove_racks, without_gate, path_segment_cities, path_segment_distances)" . " VALUES (now(), NULL, %d, %s, %s, %s, %s, %f, %f, %f, %f, %f, %d, %d, %d, %d, %s, %d, %d, %d, %d, %d, %d, %d, %f, %d, %s, %f, %d, %d, %d, %d, %d, %d, %f, %d," . " %d, %d, %d, %d, %d, %d, %d, %s, %s);", $user_id, $tr_date_from, $tr_date_to, stripslashes_deep($tr_city_from), stripslashes_deep($tr_city_to), floatval($tr_weight), floatval($tr_volume), floatval($tr_length), floatval($tr_height), floatval($tr_width), intval($trans_count), intval($trans_type), intval($tr_active), intval($tr_type), stripslashes_deep($comment), floatval($sh_distance), $from_info["country_id"], $from_info["region_id"], $from_info["city_id"], $to_info["country_id"], $to_info["region_id"], $to_info["city_id"], floatval($price), intval($cost_curr), stripslashes_deep($sh_descr), floatval($cost), intval($cash), intval($nocash), intval($way_ship), intval($way_debark), intval($soft), intval($way_prepay), floatval($prepayment), intval($price_query), intval($top_loading), intval($side_loading), intval($back_loading), intval($full_movable), intval($remove_cross), intval($remove_racks), intval($without_gate), stripslashes_deep($path_segment_cities), stripslashes_deep($path_segment_distance));
            if (false === $wpdb->query($sql)) {
                array_push($errors, "Не удалось опубликовать Ваш транспорт. Свяжитесь, пожалуйста, с администрацией сайта");
                array_push($errors, $wpdb->last_error);
                //	$errors = array_merge($errors, $dis['errors']);
                tzs_print_truck_form($errors, false);
            } else {
                //	print_errors($dis['errors']);
                echo "Ваш транспорт опубликован!";
                echo "<br/>";
                echo '<a href="/view-truck/?id=' . tzs_find_latest_truck_rec() . '&spis=new">Просмотреть транспорт</a>';
                $new_url = get_site_url() . '/my-trucks';
                echo '<meta http-equiv="refresh" content="0; url=' . $new_url . '">';
            }
        } else {
            $sql = $wpdb->prepare("UPDATE " . TZS_TRUCK_TABLE . " SET " . " last_edited=now(), tr_date_from=%s, tr_date_to=%s, tr_city_from=%s, tr_city_to=%s, tr_weight=%f, tr_volume=%f," . " tr_length=%f, tr_height=%f, tr_width=%f, trans_count=%d, trans_type=%d, tr_type=%d, comment=%s, distance=%d, " . " from_cid=%d,from_rid=%d,from_sid=%d,to_cid=%d,to_rid=%d,to_sid=%d, active=%d, price=%f, price_val=%d, sh_descr=%s," . " cost=%f, cash=%d, nocash=%d, way_ship=%d, way_debark=%d, soft=%d, way_prepay=%d, prepayment=%f, price_query=%d," . " top_loading=%d, side_loading=%d, back_loading=%d, full_movable=%d, remove_cross=%d, remove_racks=%d, without_gate=%d, path_segment_cities=%s, path_segment_distances=%s" . " WHERE id=%d AND user_id=%d;", $tr_date_from, $tr_date_to, stripslashes_deep($tr_city_from), stripslashes_deep($tr_city_to), floatval($tr_weight), floatval($tr_volume), floatval($tr_length), floatval($tr_height), floatval($tr_width), intval($trans_count), intval($trans_type), intval($tr_type), stripslashes_deep($comment), floatval($sh_distance), $from_info["country_id"], $from_info["region_id"], $from_info["city_id"], $to_info["country_id"], $to_info["region_id"], $to_info["city_id"], intval($tr_active), floatval($price), intval($cost_curr), stripslashes_deep($sh_descr), floatval($cost), intval($cash), intval($nocash), intval($way_ship), intval($way_debark), intval($soft), intval($way_prepay), floatval($prepayment), intval($price_query), intval($top_loading), intval($side_loading), intval($back_loading), intval($full_movable), intval($remove_cross), intval($remove_racks), intval($without_gate), stripslashes_deep($path_segment_cities), stripslashes_deep($path_segment_distance), $id, $user_id);
            if (false === $wpdb->query($sql)) {
                array_push($errors, "Не удалось изменить Ваш транспорт. Свяжитесь, пожалуйста, с администрацией сайта");
                array_push($errors, $wpdb->last_error);
                //	$errors = array_merge($errors, $dis['errors']);
                tzs_print_truck_form($errors, true);
            } else {
                //	print_errors($dis['errors']);
                echo "Ваш транспорт изменен";
                echo "<br/>";
                echo '<a href="/view-truck/?id=' . $id . '&spis=new">Просмотреть транспорт</a>';
                $new_url = get_site_url() . '/my-trucks';
                echo '<meta http-equiv="refresh" content="0; url=' . $new_url . '">';
            }
        }
    }
}
Example #2
0
function tzs_edit_product($id)
{
    $errors = array();
    $user_id = get_current_user_id();
    // Проверим защиту nonce
    if (isset($_POST['pr_type_id_nonce']) && wp_verify_nonce($_POST['pr_type_id_nonce'], 'pr_type_id')) {
        $pr_active = get_param_def('pr_active', '0');
        $pr_type_id = get_param_def('pr_type_id', '0');
        $pr_sale_or_purchase = get_param_def('pr_sale_or_purchase', '0');
        $pr_fixed_or_tender = get_param_def('pr_fixed_or_tender', '0');
        $pr_title = get_param('pr_title');
        $pr_description = get_param('pr_description');
        $pr_copies = get_param_def('pr_copies', '0');
        $pr_unit = get_param_def('pr_unit', '0');
        $pr_currency = get_param_def('pr_currency', '0');
        $pr_price = get_param_def('pr_price', '0');
        $pr_payment = get_param_def('pr_payment', '0');
        $pr_nds = get_param_def('pr_nds', '0');
        $pr_city_from = get_param('pr_city_from');
        $pr_comment = get_param('pr_comment');
        $pr_expiration = get_param('pr_expiration');
        if (is_valid_date($pr_expiration) === null) {
            array_push($errors, "Неверный формат даты");
        } else {
            $cur_date = new DateTime();
            $exp_date = new DateTime($pr_expiration);
            $interval = date_diff($cur_date, $exp_date);
            if ($interval->days < TZS_PR_PUBLICATION_MIN_DAYS) {
                array_push($errors, "Минимальный срок публикации " . TZS_PR_PUBLICATION_MIN_DAYS . " дней");
            }
        }
        $pr_expiration = is_valid_date($pr_expiration);
        if (!is_valid_city($pr_city_from)) {
            array_push($errors, "Неверный населенный пункт");
        }
        if (strlen($pr_title) < 2) {
            array_push($errors, "Введите наименование товара");
        }
        if (strlen($pr_description) < 2) {
            array_push($errors, "Введите описание товара");
        }
        if (!is_valid_num_zero($pr_type_id)) {
            array_push($errors, "Неверно задана категория товара");
        }
        if (!is_valid_num_zero($pr_sale_or_purchase)) {
            array_push($errors, "Неверно задан тип операции");
        }
        if (!is_valid_num_zero($pr_fixed_or_tender)) {
            array_push($errors, "Неверно задан тип ценового предложения");
        }
        if (!is_valid_num_zero($pr_active)) {
            array_push($errors, "Неверно задан статус товара");
        }
        if (!is_valid_num_zero($pr_copies)) {
            array_push($errors, "Неверно задано количество экземпляров товара");
        }
        if (!is_valid_num_zero($pr_unit)) {
            array_push($errors, "Неверно задана единица измерения количества экземпляров товара");
        }
        if (!is_valid_num_zero($pr_currency)) {
            array_push($errors, "Неверно задана валюта");
        }
        if (!is_valid_num_zero($pr_payment)) {
            array_push($errors, "Неверно задана форма оплаты");
        }
        if (!is_valid_num_zero($pr_nds)) {
            array_push($errors, "Неверно задан переключатель наличия НДС");
        }
        if (!is_valid_num_zero($pr_price)) {
            array_push($errors, "Неверно задана стоимость товара");
        }
    } else {
        array_push($errors, "Проверка формы не пройдена. Свяжитесь, пожалуйста, с администрацией сайта.");
    }
    $from_info = null;
    if (count($errors) == 0) {
        $from_info = tzs_yahoo_convert($pr_city_from);
        if (isset($from_info["error"])) {
            array_push($errors, "Не удалось распознать населенный пункт: " . $from_info["error"]);
        }
    }
    if (count($errors) > 0) {
        tzs_print_product_form($errors, $id > 0);
    } else {
        global $wpdb;
        // Если выбран тип заявки "Покупка" - то только "Тендерное предложение"
        // Проверка и присвоение сделаны для перестраховки, на случай если не сработает JS
        if ($pr_sale_or_purchase == 2) {
            $pr_fixed_or_tender = 2;
        }
        $pr_expiration = date('Y-m-d', mktime(0, 0, 0, $pr_expiration['month'], $pr_expiration['day'], $pr_expiration['year']));
        if ($id == 0) {
            $sql = $wpdb->prepare("INSERT INTO " . TZS_PRODUCTS_TABLE . " (type_id, user_id, sale_or_purchase, \tfixed_or_tender, title, description, copies, unit, currency, price, payment, nds, city_from, from_cid, from_rid, from_sid, created, comment, last_edited, active, expiration)" . " VALUES (%d, %d, %d, %d, %s, %s, %d, %d, %d, %f, %d, %d, %s, %d, %d, %d, now(), %s, NULL, %d, %s);", intval($pr_type_id), $user_id, intval($pr_sale_or_purchase), intval($pr_fixed_or_tender), stripslashes_deep($pr_title), stripslashes_deep($pr_description), intval($pr_copies), intval($pr_unit), intval($pr_currency), floatval($pr_price), intval($pr_payment), intval($pr_nds), stripslashes_deep($pr_city_from), $from_info["country_id"], $from_info["region_id"], $from_info["city_id"], stripslashes_deep($pr_comment), intval($pr_active), $pr_expiration);
            if (false === $wpdb->query($sql)) {
                array_push($errors, "Не удалось опубликовать Ваш товар/услугу. Свяжитесь, пожалуйста, с администрацией сайта");
                array_push($errors, $wpdb->last_error);
                tzs_print_product_form($errors, false);
            } else {
                echo "<div>";
                echo "<h2>Ваш товар/услуга опубликован !</h2>";
                echo "<br/>";
                //echo '<a href="/view-product/?id='.tzs_find_latest_product_rec().'&spis=new">Просмотреть товар/услугу</a>';
                echo "<h3>Сейчас будет открыта страница для добавления изображений !</h3>";
                echo "<div>";
                $new_url = get_site_url() . '/edit-images-pr/?id=' . tzs_find_latest_product_rec() . '&form_type=product';
                echo '<meta http-equiv="refresh" content="0; url=' . $new_url . '">';
            }
        } else {
            $sql = $wpdb->prepare("UPDATE " . TZS_PRODUCTS_TABLE . " SET " . " last_edited=now(), type_id=%d, sale_or_purchase=%d, fixed_or_tender=%d, title=%s, description=%s, copies=%d, unit=%d, currency=%d, price=%f, payment=%d, nds=%d, " . " city_from=%s, from_cid=%d, from_rid=%d, from_sid=%d, comment=%s, active=%d, expiration=%s" . " WHERE id=%d AND user_id=%d;", intval($pr_type_id), intval($pr_sale_or_purchase), intval($pr_fixed_or_tender), stripslashes_deep($pr_title), stripslashes_deep($pr_description), intval($pr_copies), intval($pr_unit), intval($pr_currency), floatval($pr_price), intval($pr_payment), intval($pr_nds), stripslashes_deep($pr_city_from), $from_info["country_id"], $from_info["region_id"], $from_info["city_id"], stripslashes_deep($pr_comment), intval($pr_active), $pr_expiration, $id, $user_id);
            if (false === $wpdb->query($sql)) {
                array_push($errors, "Не удалось изменить Ваш товар/услугу. Свяжитесь, пожалуйста, с администрацией сайта");
                array_push($errors, $wpdb->last_error);
                tzs_print_product_form($errors, true);
            } else {
                echo "<div>";
                echo "<h2>Ваш товар/услуга изменен !</h2>";
                echo "<br/>";
                //echo '<a href="/view-product/?id='.$id.'">Просмотреть товар/услугу</a>';
                echo "<h3>Сейчас будет открыта страница для добавления изображений !</h3>";
                echo "<div>";
                $new_url = get_site_url() . '/edit-images-pr/?id=' . $id . '&form_type=product';
                echo '<meta http-equiv="refresh" content="0; url=' . $new_url . '">';
            }
        }
    }
}
Example #3
0
function tzs_edit_truck($id)
{
    $tr_active = get_param_def('tr_active', '0');
    $tr_date_from = get_param('tr_date_from');
    $tr_date_to = get_param('tr_date_to');
    $tr_city_from = get_param('tr_city_from');
    $tr_city_to = get_param('tr_city_to');
    $comment = get_param('comment');
    $sh_descr = get_param('sh_descr');
    $tr_weight = get_param_def('tr_weight', '0');
    $tr_volume = get_param_def('tr_volume', '0');
    $trans_type = get_param('trans_type');
    $tr_type = get_param_def('tr_type', '0');
    $trans_count = get_param('trans_count');
    $set_dim = isset($_POST['set_dim']);
    $tr_length = get_param('tr_length');
    $tr_height = get_param('tr_height');
    $tr_width = get_param('tr_width');
    // Контроль пересечения дат
    $tr_date_from_str = date("Ymd", strtotime($tr_date_from));
    $tr_date_to_str = date("Ymd", strtotime($tr_date_to));
    $tr_date_from = is_valid_date($tr_date_from);
    $tr_date_to = is_valid_date($tr_date_to);
    // Замена "," на точку "." в числах
    $tr_weight = str_replace(',', '.', $tr_weight);
    $tr_volume = str_replace(',', '.', $tr_volume);
    $tr_length = str_replace(',', '.', $tr_length);
    $tr_height = str_replace(',', '.', $tr_height);
    $tr_width = str_replace(',', '.', $tr_width);
    $errors = array();
    // cost
    $price = get_param_def('set_price', '0') == '1';
    $price_json = array();
    $price_json['set_price'] = $price ? 1 : 0;
    if ($price) {
        $price_val = get_param_def('price', '0');
        if (!is_valid_num($price_val)) {
            array_push($errors, "Неверно задана стоимость");
        } else {
            $price_json['price'] = floatval($price_val);
        }
        $cost_curr = get_param_def('cost_curr', '0');
        if (!is_valid_num($cost_curr) || !isset($GLOBALS['tzs_curr'][intval($cost_curr)])) {
            array_push($errors, "Неверно задана валюта");
        } else {
            $price_json['cost_curr'] = intval($cost_curr);
        }
        $payment = get_param_def('payment', null);
        if ($payment != null) {
            if ($payment != 'nocash' && $payment != 'cash' && $payment != 'mix_cash' && $payment != 'soft' && $payment != 'conv' && $payment != 'on_card') {
                array_push($errors, "Неверно задана форма оплаты");
            } else {
                $price_json['payment'] = $payment;
            }
        }
        if (isset($_POST['payment_way_nds'])) {
            $price_json['payment_way_nds'] = true;
        }
        if (isset($_POST['payment_way_ship'])) {
            $price_json['payment_way_ship'] = true;
        }
        if (isset($_POST['payment_way_debark'])) {
            $price_json['payment_way_debark'] = true;
        }
        if (isset($_POST['payment_way_barg'])) {
            $price_json['payment_way_barg'] = true;
        }
        if (isset($_POST['payment_way_prepay'])) {
            $price_json['payment_way_prepay'] = true;
            $prepayment = get_param_def('prepayment', '0');
            if (!is_valid_num($prepayment) || floatval($prepayment) > 100) {
                array_push($errors, "Неверно задан размер предоплаты");
            } else {
                $price_json['prepayment'] = floatval($prepayment);
            }
        }
    } else {
        if (isset($_POST['price_query'])) {
            $price_json['price_query'] = true;
        }
    }
    // ----
    if ($tr_date_from == null || $tr_date_to == null) {
        array_push($errors, "Неверный формат даты");
    }
    // Контроль пересечения дат
    if ($tr_date_to_str < $tr_date_from_str) {
        array_push($errors, "Дата выгрузки не может быть РАНЬШЕ даты погрузки");
    }
    if (!is_valid_city($tr_city_from)) {
        array_push($errors, "Неверный пункт погрузки");
    }
    if (!is_valid_city($tr_city_to)) {
        array_push($errors, "Неверный пункт разгрузки");
    }
    if (!is_valid_num_zero($tr_weight)) {
        array_push($errors, "Неверно задан вес");
    }
    if (!is_valid_num_zero($tr_volume)) {
        array_push($errors, "Неверно задан объем");
    }
    if (strlen($trans_count) == 0) {
        $trans_count = '1';
    }
    if (!is_valid_num($trans_count)) {
        array_push($errors, "Неверно задано количество машин");
    }
    if (!is_numeric($trans_type) || intval($trans_type) < 1) {
        array_push($errors, "Неверно задан тип ТС");
    }
    if (!is_numeric($tr_active) || intval($tr_active) < 0) {
        array_push($errors, "Неверно задан статус заявки");
    }
    if (!is_numeric($tr_type) || intval($tr_type) < 0 || intval($tr_type) > 3) {
        array_push($errors, "Неверно задан тип");
    }
    if ($set_dim) {
        if (!is_valid_num($tr_length)) {
            array_push($errors, "Неверно задана длина транспортного средства");
        }
        if (!is_valid_num($tr_width)) {
            array_push($errors, "Неверно задана ширина транспортного средства");
        }
        if (!is_valid_num($tr_height)) {
            array_push($errors, "Неверно задана высота транспортного средства");
        }
    } else {
        $tr_length = '0';
        $tr_width = '0';
        $tr_height = '0';
    }
    $user_id = get_current_user_id();
    $from_info = null;
    $to_info = null;
    if (count($errors) == 0) {
        $from_info = tzs_yahoo_convert($tr_city_from);
        if (isset($from_info["error"])) {
            array_push($errors, "Не удалось распознать населенный пункт погрузки: " . $from_info["error"]);
        }
        $to_info = tzs_yahoo_convert($tr_city_to);
        if (isset($to_info["error"])) {
            array_push($errors, "Не удалось распознать населенный пункт выгрузки: " . $to_info["error"]);
        }
    }
    if (count($errors) > 0) {
        tzs_print_truck_form($errors, $id > 0);
    } else {
        global $wpdb;
        $tr_date_from = date('Y-m-d', mktime(0, 0, 0, $tr_date_from['month'], $tr_date_from['day'], $tr_date_from['year']));
        $tr_date_to = date('Y-m-d', mktime(0, 0, 0, $tr_date_to['month'], $tr_date_to['day'], $tr_date_to['year']));
        //$dis = tzs_calculate_distance(array($tr_city_from, $tr_city_to));
        $dis = get_param('length');
        if ($id == 0) {
            $sql = $wpdb->prepare("INSERT INTO " . TZS_TRUCK_TABLE . " (time, last_edited, user_id, tr_date_from, tr_date_to, tr_city_from, tr_city_to, tr_weight, tr_volume, tr_length, tr_height, tr_width, trans_count, trans_type, active, tr_type, cost, comment, distance,from_cid,from_rid,from_sid,to_cid,to_rid,to_sid,price,price_val,sh_descr)" . " VALUES (now(), NULL, %d, %s, %s, %s, %s, %f, %f, %f, %f, %f, %d, %d, %d, %d, %s, %s, %d, %d,%d,%d,%d,%d,%d,%f,%d,%s);", $user_id, $tr_date_from, $tr_date_to, stripslashes_deep($tr_city_from), stripslashes_deep($tr_city_to), floatval($tr_weight), floatval($tr_volume), floatval($tr_length), floatval($tr_height), floatval($tr_width), intval($trans_count), intval($trans_type), intval($tr_active), intval($tr_type), stripslashes_deep(json_encode($price_json)), stripslashes_deep($comment), $dis, $from_info["country_id"], $from_info["region_id"], $from_info["city_id"], $to_info["country_id"], $to_info["region_id"], $to_info["city_id"], floatval($price_val), intval($cost_curr), stripslashes_deep($sh_descr));
            if (false === $wpdb->query($sql)) {
                array_push($errors, "Не удалось опубликовать Ваш транспорт. Свяжитесь, пожалуйста, с администрацией сайта");
                array_push($errors, $wpdb->last_error);
                //	$errors = array_merge($errors, $dis['errors']);
                tzs_print_truck_form($errors, false);
            } else {
                //	print_errors($dis['errors']);
                echo "Ваш транспорт опубликован!";
                echo "<br/>";
                echo '<a href="/view-truck/?id=' . tzs_find_latest_truck_rec() . '&spis=new">Просмотреть транспорт</a>';
            }
        } else {
            $sql = $wpdb->prepare("UPDATE " . TZS_TRUCK_TABLE . " SET " . " last_edited=now(), tr_date_from=%s, tr_date_to=%s, tr_city_from=%s, tr_city_to=%s, tr_weight=%f, tr_volume=%f," . " tr_length=%f, tr_height=%f, tr_width=%f, trans_count=%d, trans_type=%d, tr_type=%d, cost=%s, comment=%s, distance=%d, " . " from_cid=%d,from_rid=%d,from_sid=%d,to_cid=%d,to_rid=%d,to_sid=%d, active=%d, price=%f, price_val=%d, sh_descr=%s" . " WHERE id=%d AND user_id=%d;", $tr_date_from, $tr_date_to, stripslashes_deep($tr_city_from), stripslashes_deep($tr_city_to), floatval($tr_weight), floatval($tr_volume), floatval($tr_length), floatval($tr_height), floatval($tr_width), intval($trans_count), intval($trans_type), intval($tr_type), stripslashes_deep(json_encode($price_json)), stripslashes_deep($comment), $dis, $from_info["country_id"], $from_info["region_id"], $from_info["city_id"], $to_info["country_id"], $to_info["region_id"], $to_info["city_id"], intval($tr_active), floatval($price_val), intval($cost_curr), stripslashes_deep($sh_descr), $id, $user_id);
            if (false === $wpdb->query($sql)) {
                array_push($errors, "Не удалось изменить Ваш транспорт. Свяжитесь, пожалуйста, с администрацией сайта");
                array_push($errors, $wpdb->last_error);
                //	$errors = array_merge($errors, $dis['errors']);
                tzs_print_truck_form($errors, true);
            } else {
                //	print_errors($dis['errors']);
                echo "Ваш транспорт изменен";
                echo "<br/>";
                echo '<a href="/view-truck/?id=' . $id . '&spis=new">Просмотреть транспорт</a>';
            }
        }
    }
}
Example #4
0
function tzs_edit_product($id)
{
    $errors = array();
    $file_error_message = array(0 => 'Ошибок не возникло, файл был успешно загружен на сервер', 1 => 'Размер принятого файла превысил максимально допустимый размер, который задан директивой upload_max_filesize конфигурационного файла php.ini', 2 => 'Размер загружаемого файла превысил значение MAX_FILE_SIZE, указанное в HTML-форме', 3 => 'Загружаемый файл был получен только частично', 4 => 'Файл не был загружен', 5 => '', 6 => 'Отсутствует временная папка', 7 => 'Не удалось записать файл на диск', 8 => 'PHP-расширение остановило загрузку файла');
    $user_id = get_current_user_id();
    // Проверим защиту nonce
    if (isset($_POST['pr_type_id_nonce']) && wp_verify_nonce($_POST['pr_type_id_nonce'], 'pr_type_id')) {
        $pr_active = get_param_def('pr_active', '0');
        $pr_type_id = get_param_def('pr_type_id', '0');
        $pr_sale_or_purchase = get_param_def('pr_sale_or_purchase', '0');
        $pr_fixed_or_tender = get_param_def('pr_fixed_or_tender', '0');
        $pr_title = get_param('pr_title');
        $pr_description = get_param('pr_description');
        $pr_copies = get_param_def('pr_copies', '0');
        $pr_unit = get_param_def('pr_unit', '0');
        $pr_currency = get_param_def('pr_currency', '0');
        $pr_price = get_param_def('pr_price', '0');
        $pr_city_from = get_param('pr_city_from');
        $pr_comment = get_param('pr_comment');
        $pr_expiration = get_param('pr_expiration');
        $cash = isset($_POST['cash']) ? 1 : 0;
        $nocash = isset($_POST['nocash']) ? 1 : 0;
        $nds = isset($_POST['nds']) ? 1 : 0;
        $nonds = isset($_POST['nonds']) ? 1 : 0;
        $pr_payment = $cash && $nocash ? 11 : ($cash && !$nocash ? 10 : (!$cash && $nocash ? 1 : 0));
        $pr_nds = nds && $nonds ? 11 : (nds && !$nondsh ? 10 : (!nds && $nonds ? 1 : 0));
        //$image_id_lists = get_param('image_id_lists');
        //$main_image = get_param_def('main_image', '0');
        $image_id_lists = array();
        $main_image = 0;
        if (is_valid_date($pr_expiration) === null) {
            array_push($errors, "Неверный формат даты.");
        } else {
            $cur_date = new DateTime();
            $exp_date = new DateTime($pr_expiration);
            $interval = date_diff($cur_date, $exp_date);
            if ($interval->days < TZS_PR_PUBLICATION_MIN_DAYS) {
                array_push($errors, "Минимальный срок публикации " . TZS_PR_PUBLICATION_MIN_DAYS . " дней.");
            }
        }
        $pr_expiration = is_valid_date($pr_expiration);
        if (!is_valid_city($pr_city_from)) {
            array_push($errors, "Не указан пункт местонахождения товара.");
        }
        if (strlen($pr_title) < 2) {
            array_push($errors, "Не указано наименование товара.");
        }
        if (strlen($pr_description) < 2) {
            array_push($errors, "Не указано описание товара.");
        }
        if (!is_valid_num_zero($pr_type_id)) {
            array_push($errors, "Не указана категория товара.");
        }
        if (!is_valid_num_zero($pr_sale_or_purchase)) {
            array_push($errors, "Не указан тип операции.");
        }
        if (!is_valid_num_zero($pr_fixed_or_tender)) {
            array_push($errors, "Не указан тип ценового предложения.");
        }
        if (!is_valid_num_zero($pr_active)) {
            array_push($errors, "Не указан статус товара.");
        }
        if (!is_valid_num_zero($pr_copies)) {
            array_push($errors, "Не указано количество экземпляров товара.");
        }
        if (!is_valid_num_zero($pr_unit)) {
            array_push($errors, "Не указана единица измерения количества экземпляров товара.");
        }
        if (!is_valid_num_zero($pr_currency)) {
            array_push($errors, "Не указана валюта.");
        }
        if (!is_valid_num_zero($pr_price)) {
            array_push($errors, "Не указана стоимость товара.");
        }
        if (!$cash && !$nocash && !$nds && !$nonds) {
            array_push($errors, "Необходимо выбрать хотя бы один способ в блоке \"Форма расчета\".");
        }
    } else {
        array_push($errors, "Проверка формы не пройдена. Свяжитесь, пожалуйста, с администрацией сайта.");
    }
    $from_info = null;
    if (count($errors) == 0) {
        $from_info = tzs_yahoo_convert($pr_city_from);
        if (isset($from_info["error"])) {
            array_push($errors, "Не удалось распознать населенный пункт: " . $from_info["error"]);
        }
    }
    if (count($errors) > 0) {
        tzs_print_product_form($errors, $id > 0);
    } else {
        global $wpdb;
        // Если выбран тип заявки "Покупка" - то только "Тендерное предложение"
        // Проверка и присвоение сделаны для перестраховки, на случай если не сработает JS
        if ($pr_sale_or_purchase == 2) {
            $pr_fixed_or_tender = 2;
        }
        $pr_expiration = date('Y-m-d', mktime(0, 0, 0, $pr_expiration['month'], $pr_expiration['day'], $pr_expiration['year']));
        // Обработка изображений
        for ($i = 1; $i <= 3; $i++) {
            $add_image_index = 'image' . $i . '_load';
            $del_image_index = 'image_id_' . $i;
            // Удаление изображения
            if (count($errors) === 0 && isset($_POST[$del_image_index]) && strlen($_FILES[$add_image_index]['name']) > 0) {
                if (false === wp_delete_attachment($_POST[$del_image_index], true)) {
                    array_push($errors, "Не удалось удалить файл с изображением: " . $_POST[$del_image_index]->get_error_message());
                }
            } elseif (count($errors) === 0 && isset($_POST[$del_image_index]) && strlen($_FILES[$add_image_index]['name']) == 0) {
                $image_id_lists[] = $_POST[$del_image_index];
            }
            // Добавление изображения
            if (count($errors) === 0 && strlen($_FILES[$add_image_index]['name']) > 0) {
                if ($_FILES[$add_image_index]['error']) {
                    array_push($errors, "Не удалось загрузить файл с изображением: " . $file_error_message[$_FILES[$add_image_index]['error']]);
                } else {
                    // Позволим WordPress перехватить загрузку.
                    // не забываем указать атрибут name поля input
                    $attachment_id = media_handle_upload($add_image_index, 0);
                    if (is_wp_error($attachment_id)) {
                        array_push($errors, "Не удалось загрузить файл с изображением: " . $attachment_id->get_error_message());
                    } else {
                        $image_id_lists[] = $attachment_id;
                    }
                }
            }
        }
        $main_image = isset($image_id_lists[0]) ? $image_id_lists[0] : 0;
        // Обработка изображений - END
        if ($id == 0) {
            $sql = $wpdb->prepare("INSERT INTO " . TZS_PRODUCTS_TABLE . " (type_id, user_id, sale_or_purchase, \tfixed_or_tender, title, description, copies, unit, currency, price, payment, nds, city_from, from_cid, from_rid, from_sid, created, comment, last_edited, active, expiration, image_id_lists, main_image_id)" . " VALUES (%d, %d, %d, %d, %s, %s, %d, %d, %d, %f, %d, %d, %s, %d, %d, %d, now(), %s, NULL, %d, %s, %s, %d);", intval($pr_type_id), $user_id, intval($pr_sale_or_purchase), intval($pr_fixed_or_tender), stripslashes_deep($pr_title), stripslashes_deep($pr_description), intval($pr_copies), intval($pr_unit), intval($pr_currency), floatval($pr_price), intval($pr_payment), intval($pr_nds), stripslashes_deep($pr_city_from), $from_info["country_id"], $from_info["region_id"], $from_info["city_id"], stripslashes_deep($pr_comment), intval($pr_active), $pr_expiration, implode(';', $image_id_lists), intval($main_image));
            if (false === $wpdb->query($sql)) {
                array_push($errors, "Не удалось опубликовать Ваш товар/услугу. Свяжитесь, пожалуйста, с администрацией сайта");
                array_push($errors, $wpdb->last_error);
                tzs_print_product_form($errors, false);
            } else {
                echo "<div>";
                echo "<h2>Ваш товар/услуга опубликован !</h2>";
                echo "<br/>";
                echo '<a href="/view-product/?id=' . tzs_find_latest_product_rec() . '&spis=new">Просмотреть товар/услугу</a>';
                //echo "<h3>Сейчас будет открыта страница для добавления изображений !</h3>";
                //echo "<div>";
                //$new_url = get_site_url().'/edit-images-pr/?id='.tzs_find_latest_product_rec().'&form_type=product';
                $new_url = get_site_url() . '/my-products';
                echo '<meta http-equiv="refresh" content="0; url=' . $new_url . '">';
            }
        } else {
            $sql = $wpdb->prepare("UPDATE " . TZS_PRODUCTS_TABLE . " SET " . " last_edited=now(), type_id=%d, sale_or_purchase=%d, fixed_or_tender=%d, title=%s, description=%s, copies=%d, unit=%d, currency=%d, price=%f, payment=%d, nds=%d, " . " city_from=%s, from_cid=%d, from_rid=%d, from_sid=%d, comment=%s, active=%d, expiration=%s, image_id_lists=%s, main_image_id=%d" . " WHERE id=%d AND user_id=%d;", intval($pr_type_id), intval($pr_sale_or_purchase), intval($pr_fixed_or_tender), stripslashes_deep($pr_title), stripslashes_deep($pr_description), intval($pr_copies), intval($pr_unit), intval($pr_currency), floatval($pr_price), intval($pr_payment), intval($pr_nds), stripslashes_deep($pr_city_from), $from_info["country_id"], $from_info["region_id"], $from_info["city_id"], stripslashes_deep($pr_comment), intval($pr_active), $pr_expiration, implode(';', $image_id_lists), intval($main_image), $id, $user_id);
            if (false === $wpdb->query($sql)) {
                array_push($errors, "Не удалось изменить Ваш товар/услугу. Свяжитесь, пожалуйста, с администрацией сайта");
                array_push($errors, $wpdb->last_error);
                tzs_print_product_form($errors, true);
            } else {
                echo "<div>";
                echo "<h2>Ваш товар/услуга изменен !</h2>";
                echo "<br/>";
                echo '<a href="/view-product/?id=' . $id . '">Просмотреть товар/услугу</a>';
                //echo "<h3>Сейчас будет открыта страница для добавления изображений !</h3>";
                //echo "<div>";
                //$new_url = get_site_url().'/edit-images-pr/?id='.$id.'&form_type=product';
                $new_url = get_site_url() . '/my-products';
                echo '<meta http-equiv="refresh" content="0; url=' . $new_url . '">';
            }
        }
    }
}
Example #5
0
function tzs_edit_shipment($id)
{
    $sh_active = get_param_def('sh_active', '0');
    $sh_date_from = get_param('sh_date_from');
    $sh_date_to = get_param('sh_date_to');
    $sh_city_from = get_param('sh_city_from');
    $sh_city_to = get_param('sh_city_to');
    $comment = get_param('comment');
    $sh_descr = get_param('sh_descr');
    $sh_weight = get_param_def('sh_weight', '0');
    $sh_volume = get_param_def('sh_volume', '0');
    $sh_type = get_param('sh_type');
    $trans_type = get_param('trans_type');
    $trans_count = get_param('trans_count');
    $set_dim = isset($_POST['set_dim']);
    $sh_length = get_param('sh_length');
    $sh_height = get_param('sh_height');
    $sh_width = get_param('sh_width');
    $cost = get_param_def('cost', '0');
    $price = get_param_def('price', '0');
    $cost_curr = get_param_def('cost_curr', '1');
    $prepayment = get_param('prepayment');
    $price_query = isset($_POST['price_query']) ? 1 : 0;
    $cash = isset($_POST['cash']) ? 1 : 0;
    $nocash = isset($_POST['nocash']) ? 1 : 0;
    $way_ship = isset($_POST['way_ship']) ? 1 : 0;
    $way_debark = isset($_POST['way_debark']) ? 1 : 0;
    $soft = isset($_POST['soft']) ? 1 : 0;
    $way_prepay = isset($_POST['way_prepay']) ? 1 : 0;
    // Контроль пересечения дат
    $sh_date_from_str = date("Ymd", strtotime($sh_date_from));
    $sh_date_to_str = date("Ymd", strtotime($sh_date_to));
    $sh_date_from = is_valid_date($sh_date_from);
    $sh_date_to = is_valid_date($sh_date_to);
    // Замена "," на точку "." в числах
    $sh_weight = str_replace(',', '.', $sh_weight);
    $sh_volume = str_replace(',', '.', $sh_volume);
    $sh_length = str_replace(',', '.', $sh_length);
    $sh_height = str_replace(',', '.', $sh_height);
    $sh_width = str_replace(',', '.', $sh_width);
    $cost = str_replace(',', '.', $cost);
    $price = str_replace(',', '.', $price);
    $prepayment = str_replace(',', '.', $prepayment);
    $errors = array();
    if ($price_query && !is_valid_num_zero($cost) || !$price_query && !is_valid_num($cost)) {
        array_push($errors, "Неверно задана стоимость.");
    }
    if ($price_query && !is_valid_num_zero($price) || !$price_query && !is_valid_num($price)) {
        array_push($errors, "Неверно задана цена.");
    }
    if (!is_valid_num($cost_curr) || !isset($GLOBALS['tzs_curr'][intval($cost_curr)])) {
        array_push($errors, "Неверно задана валюта.");
    }
    if ($way_prepay && (!is_valid_num($prepayment) || floatval($prepayment) > 100)) {
        array_push($errors, "Неверно задан размер предоплаты.");
    }
    if (!$price_query && !$cash && !$nocash && !$way_ship && !$way_debark && !$soft && !$way_prepay) {
        array_push($errors, "Необходимо выбрать хотя бы один способ в блоке \"Форма расчета\".");
    }
    if ($sh_date_from == null || $sh_date_to == null) {
        array_push($errors, "Неверный формат даты");
    }
    // Контроль пересечения дат
    if ($sh_date_to_str < $sh_date_from_str) {
        array_push($errors, "Дата выгрузки не может быть РАНЬШЕ даты погрузки.");
    }
    if (!is_valid_city($sh_city_from)) {
        array_push($errors, "Неверный пункт погрузки");
    }
    if (!is_valid_city($sh_city_to)) {
        array_push($errors, "Неверный пункт разгрузки");
    }
    if (strlen($sh_descr) < 2) {
        array_push($errors, "Введите описание груза");
    }
    if (!is_valid_num_zero($sh_weight)) {
        array_push($errors, "Неверно задан вес");
    }
    if (!is_valid_num_zero($sh_volume)) {
        array_push($errors, "Неверно задан объем");
    }
    if (strlen($trans_count) == 0) {
        $trans_count = '1';
    }
    if (!is_valid_num($trans_count)) {
        array_push($errors, "Неверно задано количество машин");
    }
    if (!is_numeric($sh_type) || intval($sh_type) < 1) {
        array_push($errors, "Неверно задан тип груза");
    }
    if (!is_numeric($trans_type) || intval($trans_type) < 0) {
        array_push($errors, "Неверно задан тип ТС");
    }
    if ($set_dim) {
        if (!is_valid_num($sh_length)) {
            array_push($errors, "Неверно задана длина груза");
        }
        if (!is_valid_num($sh_width)) {
            array_push($errors, "Неверно задана ширина груза");
        }
        if (!is_valid_num($sh_height)) {
            array_push($errors, "Неверно задана высота груза");
        }
    } else {
        $sh_length = '0';
        $sh_width = '0';
        $sh_height = '0';
    }
    $user_id = get_current_user_id();
    $from_info = null;
    $to_info = null;
    if (count($errors) == 0) {
        $from_info = tzs_yahoo_convert($sh_city_from);
        if (isset($from_info["error"])) {
            array_push($errors, "Не удалось распознать населенный пункт погрузки: " . $from_info["error"]);
        }
        $to_info = tzs_yahoo_convert($sh_city_to);
        if (isset($to_info["error"])) {
            array_push($errors, "Не удалось распознать населенный пункт выгрузки: " . $to_info["error"]);
        }
    }
    if (count($errors) > 0) {
        tzs_print_shipment_form($errors, $id > 0);
    } else {
        global $wpdb;
        $sh_date_from = date('Y-m-d', mktime(0, 0, 0, $sh_date_from['month'], $sh_date_from['day'], $sh_date_from['year']));
        $sh_date_to = date('Y-m-d', mktime(0, 0, 0, $sh_date_to['month'], $sh_date_to['day'], $sh_date_to['year']));
        $temp = $from_info['city_id'];
        $sql = "SELECT lat,lng FROM " . TZS_CITIES_TABLE . " WHERE city_id={$temp};";
        $row1 = $wpdb->get_row($sql);
        $temp = $to_info['city_id'];
        $sql = "SELECT lat,lng FROM " . TZS_CITIES_TABLE . " WHERE city_id={$temp};";
        $row2 = $wpdb->get_row($sql);
        //print("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$lng1,$lat1&destinations=$lng2,$lat2&language=en-EN&sensor=false");
        //print("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$row1->lng,$row1->lat&destinations=$row2->lng,$row2->lat&language=ru-RU&sensor=false");echo '<br>';
        /* 		$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$row1->lat,$row1->lng&destinations=$row2->lat,$row2->lng&language=ru-RU&sensor=false");
        		$data = json_decode($data);
        		$dis = $data->rows[0]->elements[0]->distance->value / 1000; */
        /*
        Не срабатывает это:
        $sh_distance = get_param('sh_distance');
        */
        // А теперь на срабатывает это
        //$sh_distance = get_param('length');
        $sh_distance = get_param('sh_distance');
        //echo 'Дистанция - '+$sh_distance+'<br>';
        if ($id == 0) {
            $sql = $wpdb->prepare("INSERT INTO " . TZS_SHIPMENT_TABLE . " (time, last_edited, user_id, sh_date_from, sh_date_to, sh_city_from, sh_city_to, sh_descr, sh_weight, sh_volume, sh_length, sh_height, sh_width, trans_count, trans_type, sh_type, active, comment, distance, from_cid, from_rid, from_sid, to_cid, to_rid, to_sid, price, price_val, cost, cash, nocash, way_ship, way_debark, soft, way_prepay, prepayment, price_query)" . " VALUES (now(), NULL, %d, %s, %s, %s, %s, %s, %f, %f, %f, %f, %f, %d, %d, %d, %d, %s, %d, %d, %d, %d, %d, %d, %d, %f, %d, %f, %d, %d, %d, %d, %d, %d, %f, %d);", $user_id, $sh_date_from, $sh_date_to, stripslashes_deep($sh_city_from), stripslashes_deep($sh_city_to), stripslashes_deep($sh_descr), floatval($sh_weight), floatval($sh_volume), floatval($sh_length), floatval($sh_height), floatval($sh_width), intval($trans_count), intval($trans_type), intval($sh_type), intval($sh_active), stripslashes_deep($comment), $sh_distance, $from_info["country_id"], $from_info["region_id"], $from_info["city_id"], $to_info["country_id"], $to_info["region_id"], $to_info["city_id"], floatval($price), intval($cost_curr), floatval($cost), intval($cash), intval($nocash), intval($way_ship), intval($way_debark), intval($soft), intval($way_prepay), floatval($prepayment), intval($price_query));
            if (false === $wpdb->query($sql)) {
                array_push($errors, "Не удалось опубликовать Ваш груз. Свяжитесь, пожалуйста, с администрацией сайта");
                array_push($errors, $wpdb->last_error);
                //$errors = array_merge($errors, $dis['errors']);
                tzs_print_shipment_form($errors, false);
            } else {
                //print_errors($dis['errors']);
                echo "Ваш груз опубликован!";
                echo "<br/>";
                //echo '<pre>'.print_r($_POST,true).'</pre>';
                echo '<a href="/view-shipment/?id=' . tzs_find_latest_shipment_rec() . '&spis=new">Просмотреть груз</a>';
                $new_url = get_site_url() . '/my-shipments';
                echo '<meta http-equiv="refresh" content="0; url=' . $new_url . '">';
            }
        } else {
            $sql = $wpdb->prepare("UPDATE " . TZS_SHIPMENT_TABLE . " SET " . " last_edited=now(), sh_date_from=%s, sh_date_to=%s, sh_city_from=%s, sh_city_to=%s, sh_descr=%s, sh_weight=%f, sh_volume=%f, sh_length=%f, sh_height=%f, sh_width=%f, trans_count=%d, trans_type=%d, sh_type=%d, active=%d, comment=%s, distance=%d, " . " from_cid=%d,from_rid=%d,from_sid=%d,to_cid=%d,to_rid=%d,to_sid=%d, price=%f, price_val=%d," . " cost=%f, cash=%d, nocash=%d, way_ship=%d, way_debark=%d, soft=%d, way_prepay=%d, prepayment=%f, price_query=%d" . " WHERE id=%d AND user_id=%d;", $sh_date_from, $sh_date_to, stripslashes_deep($sh_city_from), stripslashes_deep($sh_city_to), stripslashes_deep($sh_descr), floatval($sh_weight), floatval($sh_volume), floatval($sh_length), floatval($sh_height), floatval($sh_width), intval($trans_count), intval($trans_type), intval($sh_type), intval($sh_active), stripslashes_deep($comment), round($dis['distance'] / 1000), $from_info["country_id"], $from_info["region_id"], $from_info["city_id"], $to_info["country_id"], $to_info["region_id"], $to_info["city_id"], floatval($price), intval($cost_curr), floatval($cost), intval($cash), intval($nocash), intval($way_ship), intval($way_debark), intval($soft), intval($way_prepay), floatval($prepayment), intval($price_query), $id, $user_id);
            if (false === $wpdb->query($sql)) {
                array_push($errors, "Не удалось изменить Ваш груз. Свяжитесь, пожалуйста, с администрацией сайта");
                array_push($errors, $wpdb->last_error);
                $errors = array_merge($errors, $dis['errors']);
                tzs_print_shipment_form($errors, true);
            } else {
                //print_errors($dis['errors']);
                echo "Ваш груз изменен";
                echo "<br/>";
                echo '<a href="/view-shipment/?id=' . $id . '&spis=new">Просмотреть груз</a>';
                $new_url = get_site_url() . '/my-shipments';
                echo '<meta http-equiv="refresh" content="0; url=' . $new_url . '">';
            }
        }
    }
}
Example #6
0
function tzs_validate_pr_search_parameters()
{
    $errors = array();
    $res = array();
    // Проверим защиту nonce
    if (isset($_POST['type_id_nonce']) && wp_verify_nonce($_POST['type_id_nonce'], 'type_id')) {
        // get parameters from _POST
        $form_type = get_param_def('form_type', '');
        $type_id = get_param_def('type_id', '0');
        $cur_type_id = get_param_def('cur_type_id', '0');
        $rootcategory = get_param_def('rootcategory', '0');
        $sale_or_purchase = get_param_def('sale_or_purchase', '0');
        $fixed_or_tender = get_param_def('fixed_or_tender', '0');
        $payment = get_param_def('payment', '0');
        $nds = get_param_def('nds', '0');
        $country_from = get_param_def('country_from', '0');
        $region_from = get_param_def('region_from', '0');
        $cityname_from = get_param('cityname_from');
        $pr_title = get_param('pr_title');
        $price_from = get_param_def('price_from', '0');
        $price_to = get_param_def('price_to', '0');
        $data_from = get_param_def('data_from', null);
        $data_to = get_param_def('data_to', null);
        $auction_type = get_param_def('auction_type', '0');
        $rate_from = get_param_def('rate_from', '0');
        $rate_to = get_param_def('rate_to', '0');
        // validate and parse parameters
        if (is_valid_num_zero($country_from)) {
            // use float not int because ID can be long
            $country_from = floatval($country_from);
        } else {
            array_push($errors, "Неверно выбрана страна");
        }
        if (is_valid_num_zero($region_from)) {
            // use float not int because ID can be long
            $region_from = floatval($region_from);
        } else {
            array_push($errors, "Неверно выбран регион");
        }
        if (is_valid_num_zero($price_from)) {
            $price_from = floatval($price_from);
        } else {
            array_push($errors, "Неверно указано начальное значение стоимости");
        }
        if (is_valid_num_zero($price_to)) {
            $price_to = floatval($price_to);
        } else {
            array_push($errors, "Неверно указано конечное значение стоимости");
        }
        if (is_valid_num_zero($rate_from)) {
            $rate_from = floatval($rate_from);
        } else {
            array_push($errors, "Неверно указано начальное значение ставки");
        }
        if (is_valid_num_zero($rate_to)) {
            $rate_to = floatval($rate_to);
        } else {
            array_push($errors, "Неверно указано конечное значение ставки");
        }
        if (is_valid_num_zero($type_id)) {
            $type_id = intval($type_id);
        } else {
            array_push($errors, "Неверно выбрана категория");
        }
        if (is_valid_num_zero($cur_type_id)) {
            $cur_type_id = intval($cur_type_id);
        } else {
            array_push($errors, "Неверно выбрана категория");
        }
        if (is_valid_num_zero($rootcategory)) {
            $rootcategory = intval($rootcategory);
        } else {
            array_push($errors, "Неверно выбрана категория");
        }
        if (is_valid_num_zero($auction_type)) {
            $auction_type = intval($auction_type);
        } else {
            array_push($errors, "Неверно выбран тип тендера");
        }
        if (is_valid_num_zero($sale_or_purchase)) {
            $sale_or_purchase = intval($sale_or_purchase);
        } else {
            array_push($errors, "Неверно выбран тип заявки");
        }
        if (is_valid_num_zero($fixed_or_tender)) {
            $fixed_or_tender = intval($fixed_or_tender);
        } else {
            array_push($errors, "Неверно выбран тип тендера");
        }
        if (is_valid_num_zero($payment)) {
            $payment = intval($payment);
        } else {
            array_push($errors, "Неверно выбран форма оплаты");
        }
        if (is_valid_num_zero($nds)) {
            $nds = intval($nds);
        } else {
            array_push($errors, "Неверно выбран НДС");
        }
        if ($cityname_from != null && strlen($cityname_from) == 0) {
            $cityname_from = null;
        }
        if ($pr_title != null && strlen($pr_title) == 0) {
            $pr_title = null;
        }
        if ($data_from != null && strlen($data_from) > 0) {
            $data_from = is_valid_date($data_from);
            if ($data_from == null) {
                array_push($errors, "Неверный формат даты (с)");
            }
        } else {
            $data_from = null;
        }
        if ($data_to != null && strlen($data_to) > 0) {
            $data_to = is_valid_date($data_to);
            if ($data_to == null) {
                array_push($errors, "Неверный формат даты (по)");
            }
        } else {
            $data_to = null;
        }
        $cityname_from_ids = null;
        if ($cityname_from != null && count($errors) == 0) {
            $r = tzs_city_to_ids($cityname_from, 0, 0);
            if (isset($r['error'])) {
                array_push($errors, $r['error']);
            } else {
                $cityname_from_ids = isset($r['ids']) ? $r['ids'] : null;
            }
        }
        // Если нет ошибок - то заполняем результирующий массив
        if (count($errors) == 0) {
            if ($country_from > 0) {
                $res['country_from'] = $country_from;
            }
            if ($region_from > 0) {
                $res['region_from'] = $region_from;
            }
            if ($cityname_from != null) {
                $res['cityname_from'] = $cityname_from;
            }
            if ($pr_title != null) {
                $res['pr_title'] = $pr_title;
            }
            if ($data_from != null) {
                $res['data_from'] = $data_from;
                $res['data_from_str'] = get_param('data_from');
            }
            if ($data_to != null) {
                $res['data_to'] = $data_to;
                $res['data_to_str'] = get_param('data_to');
            }
            if ($price_from > 0) {
                $res['price_from'] = $price_from;
            }
            if ($price_to > 0) {
                $res['price_to'] = $price_to;
            }
            if ($rate_from > 0) {
                $res['rate_from'] = $rate_from;
            }
            if ($rate_to > 0) {
                $res['rate_to'] = $rate_to;
            }
            if ($auction_type > 0) {
                $res['auction_type'] = $auction_type;
            }
            if ($type_id > 0) {
                $res['type_id'] = $type_id;
            }
            if ($cur_type_id > 0) {
                $res['cur_type_id'] = $cur_type_id;
            }
            if ($rootcategory > 0) {
                $res['rootcategory'] = $rootcategory;
            }
            if ($sale_or_purchase > 0) {
                $res['sale_or_purchase'] = $sale_or_purchase;
            }
            if ($fixed_or_tender > 0) {
                $res['fixed_or_tender'] = $fixed_or_tender;
            }
            if ($payment > 0) {
                $res['payment'] = $payment;
            }
            if ($nds > 0) {
                $res['nds'] = $nds;
            }
            if ($cityname_from_ids != null) {
                $res['cityname_from_ids'] = $cityname_from_ids;
            }
        }
    } else {
        array_push($errors, "Проверка формы не пройдена. Свяжитесь, пожалуйста, с администрацией сайта.");
    }
    $res['errors'] = $errors;
    return $res;
}
Example #7
0
function tzs_validate_search_parameters()
{
    $errors = array();
    $res = array();
    // get parameters from _POST
    $country_from = get_param_def('country_from', '0');
    $country_to = get_param_def('country_to', '0');
    $region_from = get_param_def('region_from', '0');
    $region_to = get_param_def('region_to', '0');
    $cargo_city_from = isset($_POST['cargo_city_from']);
    $cargo_city_to = isset($_POST['cargo_city_to']);
    $cargo_cityname_from = $cargo_city_from ? get_param('cargo_cityname_from') : null;
    $cargo_cityname_to = $cargo_city_to ? get_param('cargo_cityname_to') : null;
    $data_from = get_param_def('data_from', null);
    $data_to = get_param_def('data_to', null);
    $weight_from = get_param_def('weight_from', '0');
    $weight_to = get_param_def('weight_to', '0');
    $volume_from = get_param_def('volume_from', '0');
    $volume_to = get_param_def('volume_to', '0');
    $trans_type = get_param_def('trans_type', '0');
    $sh_type = get_param_def('sh_type', '0');
    $cargo_city_from_radius_check = isset($_POST['cargo_city_from_radius_check']);
    $cargo_city_from_radius_value = get_param_def('cargo_city_from_radius_value', 0);
    $price_from = get_param_def('price_from', '0');
    $price_to = get_param_def('price_to', '0');
    $price_km_from = get_param_def('price_km_from', '0');
    $price_km_to = get_param_def('price_km_to', '0');
    $sh_descr = get_param('sh_descr');
    // validate and parse parameters
    if (is_valid_num_zero($cargo_city_from_radius_value)) {
        $cargo_city_from_radius_value = intval($cargo_city_from_radius_value);
    } else {
        array_push($errors, "Неверно выбран радиус");
    }
    if (is_valid_num_zero($country_from)) {
        // use float not int because ID can be long
        $country_from = floatval($country_from);
    } else {
        array_push($errors, "Неверно выбрана страна погрузки");
    }
    if (is_valid_num_zero($country_to)) {
        // use float not int because ID can be long
        $country_to = floatval($country_to);
    } else {
        array_push($errors, "Неверно выбрана страна выгрузки");
    }
    if (is_valid_num_zero($region_from)) {
        // use float not int because ID can be long
        $region_from = floatval($region_from);
    } else {
        array_push($errors, "Неверно выбран регион погрузки");
    }
    if (is_valid_num_zero($region_to)) {
        // use float not int because ID can be long
        $region_to = floatval($region_to);
    } else {
        array_push($errors, "Неверно выбран регион выгрузки");
    }
    if ($cargo_cityname_from != null && strlen($cargo_cityname_from) == 0) {
        $cargo_cityname_from = null;
    }
    if ($cargo_cityname_to != null && strlen($cargo_cityname_to) == 0) {
        $cargo_cityname_to = null;
    }
    if ($data_from != null && strlen($data_from) > 0) {
        $data_from = is_valid_date($data_from);
        if ($data_from == null) {
            array_push($errors, "Неверный формат даты (с)");
        }
    } else {
        $data_from = null;
    }
    if ($data_to != null && strlen($data_to) > 0) {
        $data_to = is_valid_date($data_to);
        if ($data_to == null) {
            array_push($errors, "Неверный формат даты (по)");
        }
    } else {
        $data_to = null;
    }
    if (is_valid_num_zero($weight_from)) {
        $weight_from = intval($weight_from);
    } else {
        array_push($errors, "Неверно выбрана масса (от)");
    }
    if (is_valid_num_zero($weight_to)) {
        $weight_to = intval($weight_to);
    } else {
        array_push($errors, "Неверно выбрана масса (до)");
    }
    if (is_valid_num_zero($volume_from)) {
        $volume_from = intval($volume_from);
    } else {
        array_push($errors, "Неверно выбран объем (от)");
    }
    if (is_valid_num_zero($volume_to)) {
        $volume_to = intval($volume_to);
    } else {
        array_push($errors, "Неверно выбран объем (до)");
    }
    if (is_valid_num_zero($trans_type)) {
        $trans_type = intval($trans_type);
    } else {
        array_push($errors, "Неверно выбран тип транспорта");
    }
    if (is_valid_num_zero($sh_type)) {
        $sh_type = intval($sh_type);
    } else {
        array_push($errors, "Неверно выбран тип груза");
    }
    $cargo_cityname_from_ids = null;
    if ($cargo_cityname_from != null && count($errors) == 0) {
        $r = tzs_city_to_ids($cargo_cityname_from, $region_from, $country_from);
        if (isset($r['error'])) {
            array_push($errors, $r['error']);
        } else {
            $cargo_cityname_from_ids = isset($r['ids']) ? $r['ids'] : null;
        }
    }
    if (is_valid_num_zero($price_from)) {
        $price_from = intval($price_from);
    } else {
        array_push($errors, "Неверно выбрана стоимость (от)");
    }
    if (is_valid_num_zero($price_to)) {
        $price_to = intval($price_to);
    } else {
        array_push($errors, "Неверно выбрана стоимость (до)");
    }
    if (is_valid_num_zero($price_km_from)) {
        $price_km_from = intval($price_km_from);
    } else {
        array_push($errors, "Неверно выбрана цена 1 км (от)");
    }
    if (is_valid_num_zero($price_km_to)) {
        $price_km_to = intval($price_km_to);
    } else {
        array_push($errors, "Неверно выбрана цена 1 км (до)");
    }
    // KSK - добавляем выбор ids для городов в радиусе
    $cargo_city_from_radius_ids = null;
    if ($cargo_city_from_radius_check && $cargo_cityname_from != null && count($errors) == 0) {
        $r = tzs_city_from_radius_to_ids($cargo_cityname_from, $region_from, $country_from, $cargo_city_from_radius_value);
        if (isset($r['error'])) {
            array_push($errors, $r['error']);
        } else {
            $cargo_city_from_radius_ids = isset($r['ids']) ? $r['ids'] : null;
        }
    }
    $cargo_cityname_to_ids = null;
    if ($cargo_cityname_to != null && count($errors) == 0) {
        $r = tzs_city_to_ids($cargo_cityname_to, $region_to, $country_to);
        if (isset($r['error'])) {
            array_push($errors, $r['error']);
        } else {
            $cargo_cityname_to_ids = isset($r['ids']) ? $r['ids'] : null;
        }
    }
    if ($sh_descr != null && strlen($sh_descr) == 0) {
        $sh_descr = null;
    }
    if (count($errors) == 0) {
        if ($country_from > 0) {
            $res['country_from'] = $country_from;
        }
        if ($country_to > 0) {
            $res['country_to'] = $country_to;
        }
        if ($region_from > 0) {
            $res['region_from'] = $region_from;
        }
        if ($region_to > 0) {
            $res['region_to'] = $region_to;
        }
        if ($cargo_cityname_from != null) {
            $res['cargo_cityname_from'] = $cargo_cityname_from;
        }
        if ($cargo_cityname_to != null) {
            $res['cargo_cityname_to'] = $cargo_cityname_to;
        }
        if ($data_from != null) {
            $res['data_from'] = $data_from;
            $res['data_from_str'] = get_param('data_from');
        }
        if ($data_to != null) {
            $res['data_to'] = $data_to;
            $res['data_to_str'] = get_param('data_to');
        }
        if ($weight_from > 0) {
            $res['weight_from'] = $weight_from;
        }
        if ($weight_to > 0) {
            $res['weight_to'] = $weight_to;
        }
        if ($volume_from > 0) {
            $res['volume_from'] = $volume_from;
        }
        if ($volume_to > 0) {
            $res['volume_to'] = $volume_to;
        }
        if ($trans_type > 0) {
            $res['trans_type'] = $trans_type;
        }
        if ($sh_type > 0) {
            $res['sh_type'] = $sh_type;
        }
        if ($cargo_cityname_from_ids != null) {
            $res['cargo_cityname_from_ids'] = $cargo_cityname_from_ids;
        }
        if ($cargo_cityname_to_ids != null) {
            $res['cargo_cityname_to_ids'] = $cargo_cityname_to_ids;
        }
        if ($cargo_city_from_radius_ids != null) {
            $res['cargo_city_from_radius_ids'] = $cargo_city_from_radius_ids;
        }
        if ($cargo_city_from_radius_value != null) {
            $res['cargo_city_from_radius_value'] = $cargo_city_from_radius_value;
        }
        if ($price_from > 0) {
            $res['price_from'] = $price_from;
        }
        if ($price_to > 0) {
            $res['price_to'] = $price_to;
        }
        if ($price_km_from > 0) {
            $res['price_km_from'] = $price_km_from;
        }
        if ($price_km_to > 0) {
            $res['price_km_to'] = $price_km_to;
        }
        if ($sh_descr != null) {
            $res['sh_descr'] = $sh_descr;
        }
    }
    $res['errors'] = $errors;
    return $res;
}
Example #8
0
function tzs_front_end_feedback_handler($atts)
{
    ob_start();
    tzs_copy_get_to_post();
    $pp = TZS_FEEDBACKS_PER_PAGE;
    $id = isset($_POST['id']) && is_valid_num($_POST['id']) ? intval($_POST['id']) : 0;
    $page = isset($_POST['pg']) && is_valid_num($_POST['pg']) ? intval($_POST['pg']) : 1;
    $user_id = get_current_user_id();
    $user_info = $id > 0 ? get_userdata($id) : null;
    if ($user_info == null) {
        print_error('Пользователь не найден');
    } else {
        global $wpdb;
        $res_neg = $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) as cnt FROM {$wpdb->comments} WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) ) AND comment_content like %s", $id, $user_id, '0%'));
        $res_pos = $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) as cnt FROM {$wpdb->comments} WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) ) AND comment_content like %s", $id, $user_id, '2%'));
        $res_cnt = $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) as cnt FROM {$wpdb->comments} WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) )", $id, $user_id));
        $records = $res_cnt->cnt;
        $pages = ceil($records / $pp);
        if ($pages == 0) {
            $pages = 1;
        }
        if ($page > $pages) {
            $page = $pages;
        }
        $from = ($page - 1) * $pp;
        $rate = 0 - $res_neg->cnt + $res_pos->cnt;
        $rate_class = "feedback_neutral";
        if ($rate < 0) {
            $rate_class = "feedback_negative";
        } else {
            if ($rate > 0) {
                $rate_class = "feedback_positive";
            }
        }
        $u_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->comments} WHERE comment_post_ID = %d AND user_id = %d", $id, $user_id));
        $u_exists = count($u_comment) > 0;
        $u_text = $u_exists ? substr($u_comment->comment_content, 1) : "";
        $u_type = $u_exists ? substr($u_comment->comment_content, 0, 1) : "1";
        $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->comments} WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) )  ORDER BY comment_date_gmt DESC LIMIT %d,%d", $id, $user_id, $from, $pp));
        ?>
	<div id="feedback_title">Компания <?php 
        $meta = get_user_meta($id, 'company');
        echo $meta[0];
        ?>
, контактное лицо &quot;<?php 
        $meta = get_user_meta($user_id, 'fio');
        echo $meta[0];
        //echo htmlspecialchars($user_info->display_name);
        ?>
&quot;</div>
	
	<div id="feedback_rating">
		Рейтинг: <span class="<?php 
        echo $rate_class;
        ?>
"><?php 
        echo $rate;
        ?>
</span>
	</div>
	
	<?php 
        if (count($comments) == 0) {
            ?>
			<div id="info">У этого пользователя еще нет отзывов.</div>
		<?php 
        } else {
            ?>
	<div id="feedback_content">
		<table>
			<tr>
				<th id="adds">Дата</th>
				<th id="type">Тип отзыва</th>
				<th id="auth">Автор</th>
				<th id="feedback">Отзыв</th>
			</tr>
			<?php 
            foreach ($comments as $row) {
                $cont = $row->comment_content;
                $type = substr($cont, 0, 1);
                $user_id = $row->user_id;
                $user_info = get_userdata($user_id);
                if (is_valid_num_zero($type)) {
                    $cont = substr($cont, 1);
                    if ($type == '0') {
                        $type = "<span id=\"negative\">Отрицательный<span>";
                    } else {
                        if ($type == '1') {
                            $type = "<span id=\"neutral\">Нейтральный<span>";
                        } else {
                            $type = "<span id=\"positive\">Положительный<span>";
                        }
                    }
                } else {
                    $type = "<span id=\"neutral\">Нейтральный<span>";
                }
                ?>
				<tr>
					<td><b><?php 
                echo convert_date_no_year($row->comment_date);
                ?>
</b><br/><?php 
                echo convert_time_only($row->comment_date);
                ?>
</td>
					<td><?php 
                echo $type;
                ?>
</td>
					<td><?php 
                echo $user_info->display_name;
                ?>
</td>
					<td><?php 
                echo htmlspecialchars($cont);
                ?>
</td>
				</tr>
				<?php 
            }
            ?>
		</table>
		<?php 
            build_pages_footer($page, $pages, "fpage");
            ?>
	</div>
	<?php 
        }
        ?>
	
	<div id="feedback_form">
		<input type="hidden" name="user_id" value="<?php 
        echo $id;
        ?>
"></input>
		<select name="feedback_type">
			<option value="0" <?php 
        if ($u_type == "0") {
            echo "selected";
        }
        ?>
>Отрицательный</option>
			<option value="1" <?php 
        if ($u_type == "1") {
            echo "selected";
        }
        ?>
>Нейтральный</option>
			<option value="2" <?php 
        if ($u_type == "2") {
            echo "selected";
        }
        ?>
>Положительный</option>
		</select>
		<textarea name="feedback_text"><?php 
        echo $u_text;
        ?>
</textarea>
		<?php 
        if ($u_exists) {
            ?>
			<button onClick="javascript:sendFeedback();">Изменить</button>
			<button onClick="javascript:delFeedback();">Удалить</button>
		<?php 
        } else {
            ?>
			<button onClick="javascript:sendFeedback();">Добавить</button>
		<?php 
        }
        ?>
	</div>
	
	<!--<button onClick="javascript:doReloadFeedback();">Обновить</button>-->
	
	<script>
		function sendFeedback() {
			var tp = jQuery("select[name=feedback_type] option:selected").attr('value');
			var cont = jQuery("textarea[name=feedback_text]").val();
			var id = jQuery("input[name=user_id]").val();
			
			var data = {
				'action': 'tzs_add_feedback',
				'cont': cont,
				'type': tp,
				'id': id
			};
			
			jQuery.post(ajax_url, data, function(response) {
				if (response != '1') {
					alert("Ошибка: "+response);
				} else {
					doReloadFeedback();
				}
			}).fail(function() {
				alert("Не удалось добавить/изменить отзыв. Попробуйте, пожалуйста, еще раз.");
			});
		}
		
		function delFeedback() {
			var id = jQuery("input[name=user_id]").val();
			
			var data = {
				'action': 'tzs_del_feedback',
				'id': id
			};
			
			jQuery.post(ajax_url, data, function(response) {
				if (response != '1') {
					alert("Ошибка: "+response);
				} else {
					doReloadFeedback();
				}
			}).fail(function() {
				alert("Не удалось удалить отзыв. Попробуйте, пожалуйста, еще раз.");
			});
		}
		
		function hijackFeedbackLinks() {
			jQuery('a[tag=fpage]').each(function() {
				jQuery(this).click(function(){
					feedback_page = parseInt(jQuery(this).attr('page'));
					doReloadFeedback();
					return false;
				});
			});
		}
		
		jQuery(document).ready(function() {
			hijackFeedbackLinks();
		});
	</script>
	
	<?php 
    }
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}