Example #1
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 #2
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 #3
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 #4
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 #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_front_end_search_pr_form()
{
    tzs_copy_get_to_post();
    $product_auction = get_param_def('product_auction', 'products');
    $pa_root_id = $product_auction === 'auctions' ? '' . TZS_AU_ROOT_CATEGORY_PAGE_ID : '' . TZS_PR_ROOT_CATEGORY_PAGE_ID;
    $p_id = get_the_ID();
    ?>
    <form class="search_pr_form" id="search_pr_form1" name="search_pr_form" method="POST">
        <table name="search_param" border="0">
            <tr>
                <th colspan="2">Укажите критерии поиска товаров и услуг</th>
            </tr>
            <tr>
                <td>Категория:<br>
                    <!--select name="type_id" <?php 
    //echo (isset($_POST['cur_type_id']) && ($_POST['cur_type_id'] === $pa_root_id)) ? '' : ' disabled="disabled"';
    ?>
 -->
                    <!--select name="type_id" <?php 
    //echo (isset($_POST['rootcategory']) && ($_POST['rootcategory'] === '1')) ? '' : ' disabled="disabled"';
    ?>
 -->
                    <select name="type_id" <?php 
    echo $p_id == $pa_root_id ? '' : ' disabled="disabled"';
    ?>
 >
                        <option value="0">все категории</option>
			<option disabled>- - - - - - - -</option>
                        <?php 
    tzs_build_product_types('type_id', $pa_root_id);
    ?>
                    </select>
                    <?php 
    wp_nonce_field('type_id', 'type_id_nonce');
    ?>
                </td>
                <td>Местонахождение: страна:<br>
                    <select name="country_from">
                        <?php 
    tzs_build_countries('country_from');
    ?>
                    </select>
                </td>
            <tr>
                <td>Тип заявки:<br>
                    <select name="sale_or_purchase">
                        <option value="0" <?php 
    if (isset($_POST['sale_or_purchase']) && $_POST['sale_or_purchase'] == 0) {
        echo 'selected="selected"';
    }
    ?>
 >Все</option>
                        <option value="1" <?php 
    if (isset($_POST['sale_or_purchase']) && $_POST['sale_or_purchase'] == 1) {
        echo 'selected="selected"';
    }
    ?>
 >Продажа</option>
                        <option value="2" <?php 
    if (isset($_POST['sale_or_purchase']) && $_POST['sale_or_purchase'] == 2) {
        echo 'selected="selected"';
    }
    ?>
 >Покупка</option>
                    </select>
                </td>
                <td>Местонахождение: регион:<br>
                    <select name="region_from">
                        <option value="0">все области</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Участник тендера:<br>
                    <select name="fixed_or_tender">
                        <option value="0" <?php 
    if (isset($_POST['fixed_or_tender']) && $_POST['fixed_or_tender'] == 0) {
        echo 'selected="selected"';
    }
    ?>
 >Все предложения</option>
                        <option value="1" <?php 
    if (isset($_POST['fixed_or_tender']) && $_POST['fixed_or_tender'] == 1) {
        echo 'selected="selected"';
    }
    ?>
 >Цена зафиксирована</option>
                        <option value="2" <?php 
    if (isset($_POST['fixed_or_tender']) && $_POST['fixed_or_tender'] == 2) {
        echo 'selected="selected"';
    }
    ?>
 >Тендерное предложение</option>
                    </select>
                </td>
                <td>Местонахождение: город:<br>
                    <input type="text" name="cityname_from" value="<?php 
    echo_val('cityname_from');
    ?>
" size="30">
                </td>
            </tr>
            <tr>
                <td>Форма оплаты:<br>
                    <select name="payment">
                        <option value="0" <?php 
    if (isset($_POST['payment']) && $_POST['payment'] == 0) {
        echo 'selected="selected"';
    }
    ?>
 >Любая</option>
                        <option value="1" <?php 
    if (isset($_POST['payment']) && $_POST['payment'] == 1) {
        echo 'selected="selected"';
    }
    ?>
 >Наличная</option>
                        <option value="2" <?php 
    if (isset($_POST['payment']) && $_POST['payment'] == 2) {
        echo 'selected="selected"';
    }
    ?>
 >Безналичная</option>
                    </select>
                </td>
                <td>НДС:<br>
                    <select name="nds">
                        <option value="0" <?php 
    if (isset($_POST['nds']) && $_POST['nds'] == 0) {
        echo 'selected="selected"';
    }
    ?>
 >Все</option>
                        <option value="1" <?php 
    if (isset($_POST['nds']) && $_POST['nds'] == 1) {
        echo 'selected="selected"';
    }
    ?>
 >Без НДС</option>
                        <option value="2" <?php 
    if (isset($_POST['nds']) && $_POST['nds'] == 2) {
        echo 'selected="selected"';
    }
    ?>
 >Включая НДС</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Стоимость: от:<br>
                    <input type="text" name="price_from" value="<?php 
    echo_val('price_from');
    ?>
" size="10">
                </td>
                <td>Стоимость: до:<br>
                    <input type="text" name="price_to" value="<?php 
    echo_val('price_to');
    ?>
" size="10">
                </td>
            </tr>
            <tr>
                <td>Дата размещения: от:<br>
                    <input type="text" name="data_from" value="<?php 
    echo_val('data_from');
    ?>
" size="10">
                </td>
                <td>Дата размещения: до:<br>
                    <input type="text" name="data_to" value="<?php 
    echo_val('data_to');
    ?>
" size="10">
                </td>
            </tr>
            <tr>
                <td>Описание:<br>
                    <input type="text" name="pr_title" value="<?php 
    echo_val('pr_title');
    ?>
" size="30">
                </td>
                <td>
                    <div style="text-align:right; vertical-aligment: middle;">
                        <a href="JavaScript:tblTHeadShowSearchForm();" title="Скрыть форму изменения условий поиска"><img src="<?php 
    echo get_site_url();
    ?>
/wp-content/plugins/tzs/assets/images/form_hide.png" width="110px" height="24px"></a>&nbsp;&nbsp;
                        <a href="javascript:onTblTheadButtonClearClick();" title="Очистить все условия фильтра"><img src="<?php 
    echo get_site_url();
    ?>
/wp-content/plugins/tzs/assets/images/eraser.png" width="24px" height="24px"></a>&nbsp;&nbsp;
                        <a href="javascript:onTblSearchButtonClick();" title="Выполнить поиск по текущим условиям фильтра"><img src="<?php 
    echo get_site_url();
    ?>
/wp-content/plugins/tzs/assets/images/find-1.png" width="24px" height="24px"></a>
                    </div>
                </td>
            </tr>
        </table>
    </form>
    <?php 
}
Example #7
0
function tzs_front_end_tables_reload()
{
    // Возвращаемые переменные
    $output_info = '';
    $output_error = '';
    $output_tbody = '';
    $output_pnav = '';
    $lastrecid = 0;
    $form_type = get_param_def('form_type', '');
    $type_id = get_param_def('type_id', '0');
    $rootcategory = get_param_def('rootcategory', '0');
    $cur_type_id = get_param_def('cur_type_id', '0');
    $cur_post_name = get_param_def('cur_post_name', '');
    $p_title = get_param_def('p_title', '');
    $page = get_param_def('page', '1');
    $records_per_page = get_param_def('records_per_page', '' . TZS_RECORDS_PER_PAGE);
    $record_pickup_time = get_option('t3s_setting_record_pickup_time', '30');
    //$p_id = get_the_ID();
    //$p_title = the_title('', '', false);
    // Если указан параметр rootcategory, то выводим все товары раздела
    // Иначе - товары категории
    if ($rootcategory === '1' && $type_id === '0') {
        $sql1 = ' AND type_id IN (' . tzs_build_product_types_id_str($cur_type_id) . ')';
        $p_name = '';
    } else {
        //$sql1 = ' AND type_id='.$type_id;
        $sql1 = '';
        $p_name = get_post_field('post_name', $type_id);
    }
    if ($form_type === 'products') {
        $sp = tzs_validate_pr_search_parameters();
    } else {
        $sp = tzs_validate_search_parameters();
    }
    $errors = $sp['errors'];
    switch ($form_type) {
        case 'products':
            $pr_type_array = tzs_get_children_pages(TZS_PR_ROOT_CATEGORY_PAGE_ID);
            $table_name = TZS_PRODUCTS_TABLE;
            $table_error_msg = 'товаров';
            $table_order_by = 'created';
            $order_table_prefix = 'PR';
            break;
        case 'trucks':
            $table_name = TZS_TRUCK_TABLE;
            $table_error_msg = 'транспорта';
            $table_order_by = 'time';
            $table_prefix = 'tr';
            $order_table_prefix = 'TR';
            break;
        case 'shipments':
            $table_name = TZS_SHIPMENT_TABLE;
            $table_error_msg = 'грузов';
            $table_order_by = 'time';
            $table_prefix = 'sh';
            $order_table_prefix = 'SH';
            break;
        default:
            array_push($errors, "Неверно указан тип формы");
    }
    if (count($errors) > 0) {
        $output_error = print_errors($errors);
    }
    if (count($errors) == 0) {
        if ($form_type === 'products') {
            $s_sql = tzs_search_pr_parameters_to_sql($sp, '');
            $s_title = tzs_search_pr_parameters_to_str($sp);
        } else {
            $s_sql = tzs_search_parameters_to_sql($sp, $table_prefix);
            $s_title = tzs_search_parameters_to_str($sp);
        }
        $output_info = $p_title;
        if (strlen($s_title) > 0) {
            $output_info .= ' * ' . $s_title;
        }
        //$page = current_page_number();
        global $wpdb;
        //$url = current_page_url();
        $pp = floatval($records_per_page);
        $sql = "SELECT COUNT(*) as cnt FROM " . $table_name . " a WHERE active=1 {$sql1} {$s_sql};";
        $res = $wpdb->get_row($sql);
        if (count($res) == 0 && $wpdb->last_error != null) {
            $output_error .= '<div>Не удалось отобразить список ' . $table_error_msg . '. Свяжитесь, пожалуйста, с администрацией сайта.<br>' . $sql . '<br>' . $wpdb->last_error . '</div>';
        } else {
            $records = $res->cnt;
            $pages = ceil($records / $pp);
            if ($pages == 0) {
                $pages = 1;
            }
            if ($page > $pages) {
                $page = $pages;
            }
            $from = ($page - 1) * $pp;
            //$sql = "SELECT * FROM ".$table_name." WHERE active=1 $sql1 $s_sql ORDER BY ".$table_order_by." DESC LIMIT $from,$pp;";
            // Хитрый запрос для отбора ТОП
            $sql = "SELECT a.*,";
            $sql .= " b.number AS order_number,";
            $sql .= " b.status AS order_status,";
            $sql .= " b.dt_pay AS order_dt_pay,";
            $sql .= " b.dt_expired AS order_dt_expired,";
            $sql .= " IFNULL(b.dt_pay, a." . $table_order_by . ") AS dt_sort,";
            $sql .= " IF(b.status IS NOT NULL, 2, IF(ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(a.dt_pickup))/60, 0) <= " . $record_pickup_time . ", 1, 0)) AS top_status,";
            $sql .= " LOWER(c.code) AS from_code";
            if ($form_type != 'products') {
                $sql .= ", LOWER(d.code) AS to_code";
            }
            $sql .= " FROM " . $table_name . " a";
            $sql .= " LEFT OUTER JOIN wp_tzs_orders b ON (b.tbl_type = '" . $order_table_prefix . "' AND a.id = b.tbl_id AND b.status = 1 AND b.dt_expired > NOW())";
            $sql .= " LEFT OUTER JOIN wp_tzs_countries c ON (a.from_cid = c.country_id)";
            if ($form_type != 'products') {
                $sql .= " LEFT OUTER JOIN wp_tzs_countries d ON (a.to_cid = d.country_id)";
            }
            $sql .= " WHERE active=1 {$sql1} {$s_sql}";
            $sql .= " ORDER BY top_status DESC, order_status DESC, dt_sort DESC";
            $sql .= " LIMIT {$from},{$pp};";
            $res = $wpdb->get_results($sql);
            if (count($res) == 0 && $wpdb->last_error != null) {
                $output_error .= '<div>Не удалось отобразить список ' . $table_error_msg . '. Свяжитесь, пожалуйста, с администрацией сайта.<br>' . $sql . '<br>' . $wpdb->last_error . '</div>';
            } else {
                if (count($res) == 0) {
                    $output_error .= '<div>По Вашему запросу ничего не найдено.</div>';
                } else {
                    foreach ($res as $row) {
                        if ($form_type === 'products') {
                            $output_tbody .= tzs_products_table_record_out($row, $form_type, $pr_type_array);
                        } else {
                            $output_tbody .= tzs_tr_sh_table_record_out($row, $form_type);
                        }
                        $lastrecid = $row->id;
                    }
                }
                // Пагинация
                if ($pages > 1) {
                    if ($page > 1) {
                        $page0 = $page - 1;
                        $output_pnav .= '<a tag="page" page="' . $page0 . '" href="javascript:TblTbodyReload(' . $page0 . ')">« Предыдущая</a>&nbsp;';
                    }
                    $start = 1;
                    $stop = $pages;
                    for ($i = $start; $i <= $stop; $i++) {
                        if ($i == $page) {
                            $output_pnav .= '&nbsp;&nbsp;<span>' . $i . '</span>&nbsp;';
                        } else {
                            $output_pnav .= '&nbsp;&nbsp;<a tag="page" page="' . $i . '" href="javascript:TblTbodyReload(' . $i . ')">' . $i . '</a>&nbsp;';
                        }
                    }
                    if ($page < $pages) {
                        $page1 = $page + 1;
                        $output_pnav .= '&nbsp;&nbsp;<a tag="page" page="' . $page1 . '" href="javascript:TblTbodyReload(' . $page1 . ')">Следующая »</a>';
                    }
                }
            }
        }
    }
    $output = array('output_info' => $output_info, 'output_error' => $output_error, 'output_tbody' => $output_tbody, 'output_pnav' => $output_pnav, 'output_tbody_cnt' => count($res), 'lastrecid' => $lastrecid, 'type_id' => $type_id, 'rootcategory' => $rootcategory, 'sql' => $sql, 'sql1' => $sql1, 's_sql' => $s_sql);
    //echo json_encode($output);
    // print_r($output_tbody);
    return $output;
}
Example #8
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 #9
0
function tzs_front_end_pr_images_handler($atts)
{
    ob_start();
    tzs_copy_get_to_post();
    $user_id = get_current_user_id();
    $pr_id = isset($_POST['id']) && is_numeric($_POST['id']) ? intval($_POST['id']) : 0;
    $form_type = get_param_def('form_type', '');
    $form_type_info = array('product' => array('product', TZS_PRODUCTS_TABLE, 'Товар/услуга', 'товаре/услуге'), 'auction' => array('auction', TZS_AUCTIONS_TABLE, 'Тендер', 'тендере'));
    if (!is_user_logged_in()) {
        print_error("Вход в систему обязателен");
    } else {
        if ($form_type !== 'product' && $form_type !== 'auction') {
            print_error('Не указан параметр "form_type"');
        } else {
            if ($pr_id <= 0) {
                print_error($form_type_info[$form_type][2] . ' не найден');
            } else {
                if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['action']) && $_POST['action'] == 'editimages' && $_POST['formName'] == $form_type . 'images') {
                    // Проверим защиту nonce
                    if (isset($_POST['image_0_nonce']) && wp_verify_nonce($_POST['image_0_nonce'], 'image_0')) {
                        tzs_edit_pr_images();
                    } else {
                        print_error("Проверка формы не пройдена. Свяжитесь, пожалуйста, с администрацией сайта.");
                    }
                } else {
                    global $wpdb;
                    $sql = "SELECT * FROM " . $form_type_info[$form_type][1] . " WHERE id={$pr_id} AND user_id={$user_id};";
                    $row = $wpdb->get_row($sql);
                    if (count($row) == 0 && $wpdb->last_error != null) {
                        print_error('Не удалось отобразить информацию о ' . $form_type_info[$form_type][3] . '. Свяжитесь, пожалуйста, с администрацией сайта');
                    } else {
                        if ($row == null) {
                            print_error($form_type_info[$form_type][2] . ' не найден');
                        } else {
                            $_POST['title'] = $row->title;
                            $_POST['image_id_lists'] = $row->image_id_lists;
                            $_POST['main_image'] = array_search($row->main_image_id, explode(';', $row->image_id_lists));
                            $_POST['id'] = '' . $row->id;
                            $_POST['form_type'] = $form_type_info[$form_type][0];
                            tzs_print_edit_image_form(null);
                        }
                    }
                }
            }
        }
    }
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}