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 . '">'; } } } }
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>'; } } } }
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 . '">'; } } } }
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 . '">'; } } } }
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 . '">'; } } } }
function tzs_city_from_radius_to_ids($city, $region_id, $country_id, $radius_value) { $key = tzs_yahoo_get_id(); if ($key == NULL) { return array("error" => "Внутренняя ошибка. AppID не найден"); } $city_str = $city; $radius = $radius_value + 1; global $wpdb; $sql1 = "SELECT city_id, lat, lng FROM " . TZS_CITIES_TABLE . " WHERE title_ru='" . $city . "'"; $lat = null; $lng = null; if ($region_id > 0) { $sql1 .= " AND region_id=" . $region_id; // convert region_id to title $sql = "SELECT title_ru FROM " . TZS_REGIONS_TABLE . " WHERE region_id={$region_id};"; $row = $wpdb->get_row($sql); if (count($row) == 0 && $wpdb->last_error != null) { return array("error" => "Внутренняя ошибка (область)."); } else { if ($row == null) { return array("error" => "Неизвестная область."); } } $city_str .= ' ' . $row->title_ru; } if ($country_id > 0) { $sql1 .= " AND {$country_id}=" . $country_id; // convert country_id to title $sql = "SELECT title_ru FROM " . TZS_COUNTRIES_TABLE . " WHERE country_id={$country_id};"; $row = $wpdb->get_row($sql); if (count($row) == 0 && $wpdb->last_error != null) { return array("error" => "Внутренняя ошибка (страна)."); } else { if ($row == null) { return array("error" => "Неизвестная страна."); } } $city_str .= ' ' . $row->title_ru; } ksk_debug($city_str, 'tzs_city_from_radius_to_ids: Поиск населенных пунктов в радиусе ' . $radius_value); $row = $wpdb->get_row($sql1); if ($wpdb->last_error != null) { return array("error" => "При поиске населенного пункта погрузки '" . $city_str . "' возникла ошибка :" . $wpdb->last_error); } else { if ($row != null) { $lat = $row->lat; $lng = $row->lng; ksk_debug($lat . ':' . $lng, 'tzs_city_from_radius_to_ids: Запись обнаружена - возьмем координаты'); } else { print "<br>" . $city_str . "<br>"; $res = tzs_yahoo_convert($city_str); ksk_debug($res, 'tzs_city_from_radius_to_ids: Запись не обнаружена - поищем в yahoo и возьмем координаты'); if (isset($res["error"])) { return array("error" => "Не удалось распознать населенный пункт погрузки: " . $res["error"]); } // Координаты $lat = $res['lat']; $lng = $res['lng']; } } //****************************** //* Поищем в таблице населенные пункты в указанном радиусе от указанного //****************************** $sql = "SELECT city_id, title_ru, lat, lng,"; //$sql .= " (6371.009 * acos(sin(RADIANS(lat)) * sin(RADIANS(".$lat.")) + cos(RADIANS(lat)) * cos(RADIANS(".$lat.")) * cos(RADIANS(lng) - RADIANS(".$lng.")))) as distance"; $sql .= " (6371.009 * acos(sin(RADIANS(lng)) * sin(RADIANS(" . $lng . ")) + cos(RADIANS(lng)) * cos(RADIANS(" . $lng . ")) * cos(RADIANS(lat) - RADIANS(" . $lat . ")))) as distance"; $sql .= " FROM " . TZS_CITIES_TABLE . " WHERE lat IS NOT NULL AND lng IS NOT NULL"; $sql .= " HAVING distance < " . $radius; $rows = $wpdb->get_results($sql); if ($wpdb->last_error != null) { return array("error" => "При поиске пунктов погрузки в радиусе " . $radius_value . " км от населенного пункта '" . $city_str . "' возникла ошибка :" . $wpdb->last_error); } $ids = array(); ksk_debug($rows, 'tzs_city_from_radius_to_ids: населенные пункты в указанном радиусе от указанного'); foreach ($rows as $row) { if ($row->city_id != null) { // ksk_debug($row->city_id.' - '.$row->title_ru, 'tzs_city_from_radius_to_ids: населенные пункты в указанном радиусе от указанного'); array_push($ids, $row->city_id); } } $res = array('ids' => $ids); if (!isset($res['ids']) || count($res['ids']) == 0) { return array("error" => "Пункты погрузки в радиусе " . $radius_value . " км от населенного пункта '" . $city_str . "' не обнаружены"); } return $res; }