/**
 * Handles database insertion if the user tries to submit a new week.
 *
 * @param $db
 *      The database reference.
 */
function week_post_handler(&$db)
{
    if (isset($_POST)) {
        return;
    }
    global $success_message;
    global $error_message;
    global $WEEK_TYPE_DICT;
    if (!check_post_values_set(array('week_number', 'week_type', 'week_season', 'week_start_date', 'week_end_date'))) {
        $error_message = "Missing expected POST week values.";
        return;
    }
    if (!is_valid_number($_POST['week_number'])) {
        $error_message = "Illegal week number detected.";
        return;
    }
    $week_number = intval($_POST['week_number']);
    if (!is_valid_number($_POST['week_season'])) {
        $error_message = "Season is invalid.";
        return;
    }
    $week_season_id = intval($_POST['week_season']);
    if (!is_valid_number($_POST['week_type'])) {
        $error_message = "Unexpected week type.";
        return;
    }
    $week_type = intval($_POST['week_type']);
    if ($week_type < 0 || $week_type >= count($WEEK_TYPE_DICT)) {
        $error_message = "Unexpected week type number enumeration (outside range).";
        return;
    }
    if (!is_valid_date($_POST['week_start_date'])) {
        $error_message = "Invalid start date, is it in YYYY-MM-DD form?";
        return;
    }
    $start_date = $_POST['week_start_date'];
    if (!is_valid_date($_POST['week_end_date'])) {
        $error_message = "Invalid end date, is it in YYYY-MM-DD form?";
        return;
    }
    $end_date = $_POST['week_end_date'];
    if ($start_date > $end_date) {
        $error_message = "Start date is after the end date.";
        return;
    }
    if (!week_in_season_range($start_date, $end_date, $db)) {
        $error_message = "This week is not in any season date range. Cannot figure out what season it belongs to.";
        return;
    }
    try {
        $stmt = $db->prepare('INSERT INTO weeks(fk_season_id, number, type, start_date, end_date) VALUES(:sid, :wnum, :wtype, :sdate, :edate)');
        $stmt->execute(array("sid" => $week_season_id, "wnum" => $week_number, "wtype" => $week_type, "sdate" => $start_date, "edate" => $end_date));
        $success_message = "Successful week addition.";
    } catch (PDOException $e) {
        $error_message = "Error adding week: " . $e->getMessage();
    }
}
Example #2
0
function date_to_mysqldate($date)
{
    if (is_mysql_date($date)) {
        return $date;
    } else {
        if (is_valid_date($date)) {
            $ndate = explode('/', $date, 3);
            return $ndate[2] . '-' . $ndate[1] . '-' . $ndate[0];
        } else {
            return false;
        }
    }
}
Example #3
0
     if (!isset($_POST['suppress_response_codes'])) {
         header('HTTP/1.1 403 Forbidden');
     } else {
         echo generate_error($api_session->format, 'Invalid description paramater, max length could be 160 characters.', $_SERVER['REQUEST_URI'], $api_session->callback);
     }
     exit;
 }
 if (isset($_POST['location']) && mb_strlen($_POST['location']) > 30) {
     if (!isset($_POST['suppress_response_codes'])) {
         header('HTTP/1.1 403 Forbidden');
     } else {
         echo generate_error($api_session->format, 'Invalid location paramater, max length could be 30 characters.', $_SERVER['REQUEST_URI'], $api_session->callback);
     }
     exit;
 }
 if (isset($_POST['birthdate']) && !is_valid_date($_POST['birthdate'])) {
     if (!isset($_POST['suppress_response_codes'])) {
         header('HTTP/1.1 403 Forbidden');
     } else {
         echo generate_error($api_session->format, 'Invalid birthdate paramater, the birth date should be in YYYY-DD-MM format.', $_SERVER['REQUEST_URI'], $api_session->callback);
     }
     exit;
 }
 if (isset($_POST['gender']) && ($_POST['gender'] != 'm' && $_POST['gender'] != 'f')) {
     if (!isset($_POST['suppress_response_codes'])) {
         header('HTTP/1.1 403 Forbidden');
     } else {
         echo generate_error($api_session->format, 'Invalid gender paramater, it could be m or f.', $_SERVER['REQUEST_URI'], $api_session->callback);
     }
     exit;
 }
Example #4
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 #5
0
function valid_date($date)
{
    return is_valid_date($date);
}
 /**
  * 检查类型约束
  * @param  string $type  需要约束的类型
  * @param  string $value 需要约束的值
  * @return mixed
  */
 public function checkTypeContraint($type, $value)
 {
     switch ($type) {
         case 'TINYINT':
         case 'SMALLINT':
         case 'INT':
         case 'BIGINT':
             if (!isint($value)) {
                 return $this->resultReturn(false, 'int');
             }
             break;
         case 'FLOAT':
         case 'DOUBLE':
             if (!isdouble($value)) {
                 return $this->resultReturn(false, 'double');
             }
             break;
         case 'date':
             if (!is_valid_date($value)) {
                 return $this->resultReturn(false, 'date');
             }
             break;
     }
     return $this->resultReturn(true);
 }
 function doUpdate(&$argsObj, $basehref)
 {
     $date_format_cfg = config_get('date_format');
     $obj = new stdClass();
     $descr_prefix = lang_get('Milestone') . TITLE_SEP;
     $obj = $this->edit($argsObj);
     $obj->user_feedback = 'ok';
     $obj->template = null;
     $dummy = $this->milestone_mgr->get_by_id($argsObj->id);
     $originalMilestone = $dummy[$argsObj->id];
     $op_ok = 1;
     // Check name do not exists
     $name_exists = $this->milestone_mgr->check_name_existence($originalMilestone['testplan_id'], $argsObj->name, $argsObj->id);
     if ($name_exists) {
         $obj->user_feedback = sprintf(lang_get('milestone_name_already_exists'), $argsObj->name);
         $op_ok = 0;
     }
     // BUGID 3716
     // are the dates valid?
     if ($op_ok) {
         // start date is optional
         $op_ok = is_valid_date($argsObj->target_date_original, $date_format_cfg) && ($argsObj->start_date_original == '' || is_valid_date($argsObj->start_date_original, $date_format_cfg));
         if (!$op_ok) {
             $obj->user_feedback = lang_get('warning_invalid_date');
         }
     }
     // target date changed ?
     if ($op_ok) {
         $timestamp = array();
         $timestamp['target'] = strtotime($argsObj->target_date . " 23:59:59");
         $timestamp['original_target'] = strtotime($originalMilestone['target_date'] . " 23:59:59");
         $timestamp['now'] = strtotime("now");
         if ($timestamp['target'] != $timestamp['original_target'] && $timestamp['target'] < $timestamp['now']) {
             $op_ok = 0;
             $obj->user_feedback = lang_get('warning_milestone_date');
         }
     }
     // BUGID 3829 - check target date > start date
     if ($op_ok && isset($argsObj->start_date)) {
         $timestamp['target'] = strtotime($argsObj->target_date . " 23:59:59");
         $timestamp['start'] = strtotime($argsObj->start_date . " 23:59:59");
         // target must be chronologically after start
         if ($timestamp['target'] < $timestamp['start']) {
             $op_ok = 0;
             $obj->user_feedback = lang_get('warning_target_before_start');
         }
     }
     if ($op_ok) {
         // BUGID 3907 - start date is optional -> if empty set to default date
         if (!isset($argsObj->start_date) || $argsObj->start_date == "") {
             $argsObj->start_date = "0000-00-00";
         }
         $op_ok = $this->milestone_mgr->update($argsObj->id, $argsObj->name, $argsObj->target_date, $argsObj->start_date, $argsObj->low_priority_tcases, $argsObj->medium_priority_tcases, $argsObj->high_priority_tcases);
     }
     if ($op_ok) {
         $obj->main_descr = '';
         $obj->action_descr = '';
         $obj->template = $basehref . $this->viewAction . "?tproject_id=" . $argsObj->tproject_id . "&tplan_id=" . $argsObj->tplan_id;
         logAuditEvent(TLS("audit_milestone_saved", $argsObj->tplan_name, $argsObj->name), "SAVE", $argsObj->id, "milestones");
     } else {
         // Action has failed => no change done on DB.
         $obj->main_descr = $descr_prefix . $originalMilestone['name'];
     }
     return $obj;
 }
function validateFields($fields, $rules)
{
    $errors = array();
    // loop through rules
    for ($i = 0; $i < count($rules); $i++) {
        // split row into component parts
        $row = explode(",", $rules[$i]);
        // while the row begins with "if:..." test the condition. If true, strip the if:..., part and
        // continue evaluating the rest of the line. Keep repeating this while the line begins with an
        // if-condition. If it fails any of the conditions, don't bother validating the rest of the line
        $satisfies_if_conditions = true;
        while (preg_match("/^if:/", $row[0])) {
            $condition = preg_replace("/^if:/", "", $row[0]);
            // check if it's a = or != test
            $comparison = "equal";
            $parts = array();
            if (preg_match("/!=/", $condition)) {
                $parts = explode("!=", $condition);
                $comparison = "not_equal";
            } else {
                $parts = explode("=", $condition);
            }
            $field_to_check = $parts[0];
            $value_to_check = $parts[1];
            // if the VALUE is NOT the same, we don't need to validate this field. Return.
            if ($comparison == "equal" && $fields[$field_to_check] != $value_to_check) {
                $satisfies_if_conditions = false;
                break;
            } else {
                if ($comparison == "not_equal" && $fields[$field_to_check] == $value_to_check) {
                    $satisfies_if_conditions = false;
                    break;
                } else {
                    array_shift($row);
                }
            }
            // remove this if-condition from line, and continue validating line
        }
        if (!$satisfies_if_conditions) {
            continue;
        }
        $requirement = $row[0];
        $field_name = $row[1];
        // depending on the validation test, store the incoming strings for use later...
        if (count($row) == 6) {
            $field_name2 = $row[2];
            $field_name3 = $row[3];
            $date_flag = $row[4];
            $error_message = $row[5];
        } else {
            if (count($row) == 5) {
                $field_name2 = $row[2];
                $field_name3 = $row[3];
                $error_message = $row[4];
            } else {
                if (count($row) == 4) {
                    $field_name2 = $row[2];
                    $error_message = $row[3];
                } else {
                    $error_message = $row[2];
                }
            }
        }
        // everything else!
        // if the requirement is "length=...", rename requirement to "length" for switch statement
        if (preg_match("/^length/", $requirement)) {
            $length_requirements = $requirement;
            $requirement = "length";
        }
        // if the requirement is "range=...", rename requirement to "range" for switch statement
        if (preg_match("/^range/", $requirement)) {
            $range_requirements = $requirement;
            $requirement = "range";
        }
        // now, validate whatever is required of the field
        switch ($requirement) {
            case "required":
                if (!isset($fields[$field_name]) || $fields[$field_name] == "") {
                    $errors[] = $error_message;
                }
                break;
            case "digits_only":
                if (isset($fields[$field_name]) && preg_match("/\\D/", $fields[$field_name])) {
                    $errors[] = $error_message;
                }
                break;
            case "letters_only":
                if (isset($fields[$field_name]) && preg_match("/[^a-zA-Z]/", $fields[$field_name])) {
                    $errors[] = $error_message;
                }
                break;
                // doesn't fail if field is empty
            // doesn't fail if field is empty
            case "valid_email":
                if (!LoginUtils::IsEmailValid($fields[$field_name])) {
                    $errors[] = $error_message;
                }
                break;
            case "length":
                $comparison_rule = "";
                $rule_string = "";
                if (preg_match("/length=/", $length_requirements)) {
                    $comparison_rule = "equal";
                    $rule_string = preg_replace("/length=/", "", $length_requirements);
                } else {
                    if (preg_match("/length>=/", $length_requirements)) {
                        $comparison_rule = "greater_than_or_equal";
                        $rule_string = preg_replace("/length>=/", "", $length_requirements);
                    } else {
                        if (preg_match("/length<=/", $length_requirements)) {
                            $comparison_rule = "less_than_or_equal";
                            $rule_string = preg_replace("/length<=/", "", $length_requirements);
                        } else {
                            if (preg_match("/length>/", $length_requirements)) {
                                $comparison_rule = "greater_than";
                                $rule_string = preg_replace("/length>/", "", $length_requirements);
                            } else {
                                if (preg_match("/length</", $length_requirements)) {
                                    $comparison_rule = "less_than";
                                    $rule_string = preg_replace("/length</", "", $length_requirements);
                                }
                            }
                        }
                    }
                }
                switch ($comparison_rule) {
                    case "greater_than_or_equal":
                        if (!(strlen($fields[$field_name]) >= $rule_string)) {
                            $errors[] = $error_message;
                        }
                        break;
                    case "less_than_or_equal":
                        if (!(strlen($fields[$field_name]) <= $rule_string)) {
                            $errors[] = $error_message;
                        }
                        break;
                    case "greater_than":
                        if (!(strlen($fields[$field_name]) > $rule_string)) {
                            $errors[] = $error_message;
                        }
                        break;
                    case "less_than":
                        if (!(strlen($fields[$field_name]) < $rule_string)) {
                            $errors[] = $error_message;
                        }
                        break;
                    case "equal":
                        // if the user supplied two length fields, make sure the field is within that range
                        if (preg_match("/-/", $rule_string)) {
                            list($start, $end) = explode("-", $rule_string);
                            if (strlen($fields[$field_name]) < $start || strlen($fields[$field_name]) > $end) {
                                $errors[] = $error_message;
                            }
                        } else {
                            if (strlen($fields[$field_name]) != $rule_string) {
                                $errors[] = $error_message;
                            }
                        }
                        break;
                }
                break;
            case "range":
                $comparison_rule = "";
                $rule_string = "";
                if (preg_match("/range=/", $range_requirements)) {
                    $comparison_rule = "equal";
                    $rule_string = preg_replace("/range=/", "", $range_requirements);
                } else {
                    if (preg_match("/range>=/", $range_requirements)) {
                        $comparison_rule = "greater_than_or_equal";
                        $rule_string = preg_replace("/range>=/", "", $range_requirements);
                    } else {
                        if (preg_match("/range<=/", $range_requirements)) {
                            $comparison_rule = "less_than_or_equal";
                            $rule_string = preg_replace("/range<=/", "", $range_requirements);
                        } else {
                            if (preg_match("/range>/", $range_requirements)) {
                                $comparison_rule = "greater_than";
                                $rule_string = preg_replace("/range>/", "", $range_requirements);
                            } else {
                                if (preg_match("/range</", $range_requirements)) {
                                    $comparison_rule = "less_than";
                                    $rule_string = preg_replace("/range</", "", $range_requirements);
                                }
                            }
                        }
                    }
                }
                switch ($comparison_rule) {
                    case "greater_than":
                        if (!($fields[$field_name] > $rule_string)) {
                            $errors[] = $error_message;
                        }
                        break;
                    case "less_than":
                        if (!($fields[$field_name] < $rule_string)) {
                            $errors[] = $error_message;
                        }
                        break;
                    case "greater_than_or_equal":
                        if (!($fields[$field_name] >= $rule_string)) {
                            $errors[] = $error_message;
                        }
                        break;
                    case "less_than_or_equal":
                        if (!($fields[$field_name] <= $rule_string)) {
                            $errors[] = $error_message;
                        }
                        break;
                    case "equal":
                        list($start, $end) = explode("-", $rule_string);
                        if ($fields[$field_name] < $start || $fields[$field_name] > $end) {
                            $errors[] = $error_message;
                        }
                        break;
                }
                break;
            case "same_as":
                if ($fields[$field_name] != $fields[$field_name2]) {
                    $errors[] = $error_message;
                }
                break;
            case "valid_date":
                // this is written for future extensibility of isValidDate function to allow
                // checking for dates BEFORE today, AFTER today, IS today and ANY day.
                $is_later_date = false;
                if ($date_flag == "later_date") {
                    $is_later_date = true;
                } else {
                    if ($date_flag == "any_date") {
                        $is_later_date = false;
                    }
                }
                if (!is_valid_date($fields[$field_name], $fields[$field_name2], $fields[$field_name3], $is_later_date)) {
                    $errors[] = $error_message;
                }
                break;
            case "is_alpha":
                if (preg_match('/[^A-Za-z0-9]/', $fields[$field_name])) {
                    $errors[] = $error_message;
                }
                break;
            case "custom_alpha":
                $chars = array();
                $chars["L"] = "[A-Z]";
                $chars["V"] = "[AEIOU]";
                $chars["l"] = "[a-z]";
                $chars["v"] = "[aeiou]";
                $chars["D"] = "[a-zA-Z]";
                $chars["F"] = "[aeiouAEIOU]";
                $chars["C"] = "[BCDFGHJKLMNPQRSTVWXYZ]";
                $chars["x"] = "[0-9]";
                $chars["c"] = "[bcdfghjklmnpqrstvwxyz]";
                $chars["X"] = "[1-9]";
                $chars["E"] = "[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]";
                $reg_exp_str = "";
                for ($j = 0; $j < strlen($field_name2); $j++) {
                    if (array_key_exists($field_name2[$j], $chars)) {
                        $reg_exp_str .= $chars[$field_name2[$j]];
                    } else {
                        $reg_exp_str .= $field_name2[$j];
                    }
                }
                if (!empty($fields[$field_name]) && !preg_match("/{$reg_exp_str}/", $fields[$field_name])) {
                    $errors[] = $error_message;
                }
                break;
            case "reg_exp":
                $reg_exp_str = $field_name2;
                // rather crumby, but...
                if (count($row) == 5) {
                    $reg_exp = "/" . $reg_exp_str . "/" . $row[3];
                } else {
                    $reg_exp = "/" . $reg_exp_str . "/";
                }
                if (!empty($fields[$field_name]) && !preg_match($reg_exp, $fields[$field_name])) {
                    $errors[] = $error_message;
                }
                break;
            default:
                die("Unknown requirement flag in validate_fields(): {$requirement}");
                break;
        }
    }
    return $errors;
}
Example #9
0
 function offer_seats()
 {
     if (!is_logged_in()) {
         redirect('login');
     }
     $this->init_scripts = array('frontend/_partials/google_script');
     if ($this->input->is_ajax_request()) {
         $this->load->model('rides_model');
         try {
             $this->db->trans_begin();
             if (!get_current_user_id()) {
                 throw new Exception("Your session is expired.");
             }
             $form = $this->security->xss_clean($this->input->post());
             //Enter rides data
             $rides = array();
             $rides['user_id'] = get_current_user_id();
             $rides['origin_name'] = $form['origin_name'];
             $rides['origin_latlng'] = $form['origin_latlng'];
             $rides['origin_address'] = $form['origin_address'];
             $rides['dest_name'] = $form['dest_name'];
             $rides['dest_latlng'] = $form['dest_latlng'];
             $rides['dest_address'] = $form['dest_address'];
             $rides['schedule_type'] = 'OT';
             $rides['ride_type'] = $form['ride_type'] == 'up_down' ? 'R' : 'S';
             $ride_id = $this->rides_model->insert($rides);
             if (!$ride_id) {
                 throw new Exception("Database error.");
             }
             //Enter Ride Details
             $ride_details = array();
             $ride_details['ride_id'] = $ride_id;
             $ride_details['seat_count'] = $form['seat_count'];
             $ride_details['description'] = $form['ride_details'];
             $ride_details['luggage'] = $form['luggage'];
             $ride_details['schedule_flexibility'] = $form['schedule_flexibility'];
             $ride_details['detour_flexibility'] = $form['detour_flexibility'];
             $ride_details['total_dist'] = $form['total_dist'];
             $ride_details['total_time'] = $form['total_time'];
             $this->rides_model->insert($ride_details, 'ride_details');
             //Schedules
             $dep_date = $this->input->post('dep_date');
             if (!is_valid_date($dep_date, 'Y-m-d H:i')) {
                 throw new Exception("Deaprture date is invalid.");
             }
             $ride_schedules = array();
             $ride_schedules['ride_id'] = $ride_id;
             $ride_schedules['ride_day'] = date('w', strtotime($dep_date));
             $ride_schedules['ride_start_time'] = date('H:i', strtotime($dep_date));
             $ride_schedules['schedule_start_date'] = date('Y-m-d', strtotime($dep_date));
             $ride_schedules['schedule_end_date'] = date('Y-m-d', strtotime($dep_date));
             $ride_schedules['towards'] = 'up';
             $this->rides_model->insert($ride_schedules, 'ride_schedules');
             if ($this->input->post('ride_type') == 'up_down') {
                 $ret_date = $this->input->post('ret_date');
                 if (!is_valid_date($ret_date, 'Y-m-d H:i')) {
                     throw new Exception("Return date is invalid.");
                 }
                 $ride_schedules = array();
                 $ride_schedules['ride_id'] = $ride_id;
                 $ride_schedules['ride_day'] = date('w', strtotime($ret_date));
                 $ride_schedules['ride_start_time'] = date('H:i', strtotime($ret_date));
                 $ride_schedules['schedule_start_date'] = date('Y-m-d', strtotime($ret_date));
                 $ride_schedules['schedule_end_date'] = date('Y-m-d', strtotime($ret_date));
                 $ride_schedules['towards'] = 'down';
                 $this->rides_model->insert($ride_schedules, 'ride_schedules');
             }
             //Waypoints
             $waypoints = $this->input->post('waypoints');
             if (isset($waypoints) && is_array($waypoints)) {
                 foreach ($waypoints as $waypoint) {
                     $temp = array();
                     $temp['ride_id'] = $ride_id;
                     $temp['wp_name'] = $waypoint['name'];
                     $temp['wp_address'] = $waypoint['address'];
                     $temp['wp_latlng'] = $waypoint['latlng'];
                     $this->rides_model->insert($temp, 'ride_waypoints');
                 }
             }
             if ($this->db->trans_status() === FALSE) {
                 throw new Exception("Database error.");
             }
             $this->db->trans_commit();
             $status = 'success';
             $message = 'Published successfully.';
         } catch (Exception $e) {
             $status = 'error';
             $message = $e->getMessage();
             $this->db->trans_rollback();
         }
         $output = array('status' => $status, 'message' => $message);
         $this->_ajax_output($output, TRUE);
     }
     $this->data['tmenu'] = $this->load->view('frontend/_partials/top-menu', $this->data, TRUE);
     $this->layout->view('frontend/home/offer_seats');
 }
 public function dispatch()
 {
     global $awpcp_plugin_path;
     global $start_date;
     global $end_date;
     global $import_date_format;
     global $date_sep;
     global $time_sep;
     global $auto_cat;
     global $assign_user;
     global $assigned_user;
     global $test_import;
     global $import_count;
     global $reject_count;
     global $pic_import_count;
     global $import_errors;
     $do_import = awpcp_post_param('do_import');
     $do_test_import = awpcp_post_param('do_test_import');
     if (!empty($do_import)) {
         $import_type = 'Import';
     } else {
         if (!empty($do_test_import)) {
             $import_type = 'Test Import';
         } else {
             $import_type = false;
         }
     }
     $test_import = strcmp($import_type, "Test Import") === 0;
     $start_date = awpcp_post_param("startDate", '');
     $end_date = awpcp_post_param("endDate", '');
     $import_date_format = awpcp_post_param("date_fmt", 'us_date');
     $date_sep = awpcp_post_param("sep_date", '/');
     $time_sep = awpcp_post_param("sep_time", ':');
     $auto_cat = awpcp_post_param("auto_cat", 0);
     $assign_user = awpcp_post_param('assign_user', 0);
     $assigned_user = intval(awpcp_post_param('user', 0));
     // Original implementation used a global var to pass errors.
     // That is still used until I got a change to refactor the
     // existing functions to use an errors array passed by reference.
     // The messages array is only used to report when a new user
     // is created.
     $errors = array();
     $messages = array();
     $form_errors = array();
     $importer = null;
     if (!empty($import_type)) {
         $msg = __('There was an error with your CSV file: %s', 'AWPCP');
         list($csv_error, $message) = awpcp_uploaded_file_error($_FILES['import']);
         if (!in_array($csv_error, array(UPLOAD_ERR_OK))) {
             $form_errors['import'] = sprintf($msg, $message);
         } else {
             $csv_file_name = $_FILES['import']['name'];
             $ext = trim(strtolower(substr(strrchr($csv_file_name, "."), 1)));
             if ($ext != "csv") {
                 $form_errors['import'] = sprintf($msg, __('Please upload a valid CSV file.', 'AWPCP'));
             }
         }
         $msg = __('There was an error with your ZIP file: %s', 'AWPCP');
         list($zip_error, $message) = awpcp_uploaded_file_error($_FILES['import_zip']);
         if (!in_array($zip_error, array(UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE))) {
             $form_errors['import_zip'] = sprintf($msg, $message);
         } else {
             if ($zip_error === UPLOAD_ERR_OK) {
                 $zip_file_name = $_FILES['import_zip']['name'];
                 $ext = trim(strtolower(substr(strrchr($zip_file_name, "."), 1)));
                 if ($ext != "zip") {
                     $form_errors['import_zip'] = sprintf($msg, __('Please upload a valid ZIP file.', 'AWPCP'));
                 }
             }
         }
         if (!empty($start_date)) {
             $date_arr = explode("/", $start_date);
             if (!is_valid_date($date_arr[0], $date_arr[1], $date_arr[2])) {
                 $form_errors['startDate'] = __('Invalid Start Date.', 'AWPCP');
             } else {
                 if (strlen($date_arr[2]) != 4) {
                     $form_errors['startDate'] = __('Invalid Start Date -- Year Must be of Four Digit.', 'AWPCP');
                 }
             }
         }
         if (!empty($end_date)) {
             $date_arr = explode("/", $end_date);
             if (!is_valid_date($date_arr[0], $date_arr[1], $date_arr[2])) {
                 $form_errors['endDate'] = __('Invalid End Date.', 'AWPCP');
             } else {
                 if (strlen($date_arr[2]) != 4) {
                     $form_errors['endDate'] = __('Invalid End Date -- Year Must be of Four Digit.', 'AWPCP');
                 }
             }
         }
         if (empty($form_errors)) {
             if (empty($errors)) {
                 $csv = $_FILES['import']['tmp_name'];
                 $zip = $_FILES['import_zip']['tmp_name'];
                 $importer = new AWPCP_CSV_Importer(array('start-date' => $start_date, 'end-date' => $end_date, 'date-format' => $import_date_format, 'date-separator' => $date_sep, 'time-separator' => $time_sep, 'autocreate-categories' => $auto_cat, 'assign-user' => $assign_user, 'default-user' => $assigned_user, 'test-import' => $test_import));
                 $importer->import($csv, $zip, $errors, $messages);
             }
         }
     }
     ob_start();
     include AWPCP_DIR . '/admin/templates/admin-panel-csv-importer.tpl.php';
     $html = ob_get_contents();
     ob_end_clean();
     echo $html;
 }
Example #11
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 #12
0
    $Type = 'title';
}
// What are we looking for? Let's make sure it isn't dangerous.
if (isset($_GET['search'])) {
    $Search = trim($_GET['search']);
} else {
    $Search = '';
}
$ThreadAfterDate = db_string($_GET['thread_created_after']);
$ThreadBeforeDate = db_string($_GET['thread_created_before']);
if (!empty($ThreadAfterDate) && !is_valid_date($ThreadAfterDate) || !empty($ThreadBeforeDate) && !is_valid_date($ThreadBeforeDate)) {
    error("Incorrect topic created date");
}
$PostAfterDate = db_string($_GET['post_created_after']);
$PostBeforeDate = db_string($_GET['post_created_before']);
if (!empty($PostAfterDate) && !is_valid_date($PostAfterDate) || !empty($PostBeforeDate) && !is_valid_date($PostBeforeDate)) {
    error("Incorrect post created date");
}
// Searching for posts by a specific user
if (!empty($_GET['user'])) {
    $User = trim($_GET['user']);
    $DB->query("\n\t\tSELECT ID\n\t\tFROM users_main\n\t\tWHERE Username = '******'");
    list($AuthorID) = $DB->next_record();
    if ($AuthorID === null) {
        $AuthorID = 0;
        //this will cause the search to return 0 results.
        //workaround in line 276 to display that the username was wrong.
    }
} else {
    $User = '';
}
Example #13
0
 function setPermitRegistrationDates($reg_date, $exp_date, $for_year)
 {
     if (is_valid_date($reg_date) && is_valid_date($exp_date) && is_numeric($for_year)) {
         $this->m_tsRegDate = $reg_date;
         $this->m_tsExpDate = $exp_date;
         $this->m_nForYear = $for_year;
         return true;
     } else {
         $this->debug("Invalid param value on calling method setPermitRegistration( {$reg_date}, {$exp_date}, {$for_year} )");
         return false;
     }
 }
Example #14
0
function check_web_service_params($params)
{
    if (!empty($params['digitized'])) {
        if (!in_array($params['digitized'], array(0, 1))) {
            return 'digitized value can be only 1 or 0';
        }
    }
    if (!empty($params['modified_date'])) {
        if (!is_valid_date($params['modified_date'])) {
            return 'modified_date should be in YYYYMMDD';
        }
    }
    if (!empty($params['page'])) {
        if (!is_numeric($params['page'])) {
            return 'page must be integer.';
        }
    }
    return 'valid';
}
Example #15
0
<?php

$PerPage = POSTS_PER_PAGE;
list($Page, $Limit) = Format::page_limit($PerPage);
$CanEdit = check_perms('users_mod');
if ($CanEdit && isset($_POST['perform'])) {
    authorize();
    if ($_POST['perform'] === 'add' && !empty($_POST['message'])) {
        $Message = db_string($_POST['message']);
        $Author = db_string($_POST['author']);
        $Date = db_string($_POST['date']);
        if (!is_valid_date($Date)) {
            $Date = sqltime();
        }
        $DB->query("\n\t\t\tINSERT INTO changelog (Message, Author, Time)\n\t\t\tVALUES ('{$Message}', '{$Author}', '{$Date}')");
        $ID = $DB->inserted_id();
        //	SiteHistory::add_event(sqltime(), "Change log $ID", "tools.php?action=change_log", 1, 3, "", $Message, $LoggedUser['ID']);
    }
    if ($_POST['perform'] === 'remove' && !empty($_POST['change_id'])) {
        $ID = (int) $_POST['change_id'];
        $DB->query("\n\t\t\tDELETE FROM changelog\n\t\t\tWHERE ID = '{$ID}'");
    }
}
$DB->query("\n\tSELECT\n\t\tSQL_CALC_FOUND_ROWS\n\t\tID,\n\t\tMessage,\n\t\tAuthor,\n\t\tDate(Time) as Time2\n\tFROM changelog\n\tORDER BY Time DESC\n\tLIMIT {$Limit}");
$ChangeLog = $DB->to_array();
$DB->query('SELECT FOUND_ROWS()');
list($NumResults) = $DB->next_record();
View::show_header('Gazelle Change Log', 'datetime_picker', 'datetime_picker');
?>
<div class="thin">
	<h2>Gazelle Change Log</h2>
Example #16
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 . '">';
            }
        }
    }
}
<?php

require_once '../core.php';
define('SEASON_NAME_MAX_CHARS', 128);
$db = get_database_connection();
$error_message = NULL;
$developer_error_message = NULL;
$success_message = NULL;
// Look for any POST data that we could process.
if (isset($_POST)) {
    // Make sure all fields are available and valid before committing a new season.
    if (check_post_values_set(array('season_name', 'season_start_date', 'season_end_date'))) {
        if (preg_match('/[-a-zA-Z0-9_. ]+/', $_POST['season_name'])) {
            if (strlen($_POST['season_name']) < SEASON_NAME_MAX_CHARS) {
                if (is_valid_date($_POST['season_start_date'])) {
                    if (is_valid_date($_POST['season_end_date'])) {
                        if ($_POST['season_start_date'] < $_POST['season_end_date']) {
                            $season_name = $_POST['season_name'];
                            $start_date = $_POST['season_start_date'];
                            $end_date = $_POST['season_end_date'];
                            try {
                                $stmt = $db->prepare('INSERT INTO seasons(name, start_date, end_date) VALUES(:sname, :sdate, :edate)');
                                $stmt->execute(array("sname" => $season_name, "sdate" => $start_date, "edate" => $end_date));
                                $success_message = "Successful season addition.";
                            } catch (PDOException $e) {
                                $error_message = "Error adding season: " . $e->getMessage();
                            }
                        } else {
                            $error_message = "Start date is after the end date.";
                        }
                    } else {
Example #18
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 #19
0
 public function _validate_birthdate($date)
 {
     $this->form_validation->set_message('_validate_birthdate', 'The %s must be in format: mm/dd/yyyy');
     return is_valid_date($date, 'm/d/Y');
 }
Example #20
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 #21
0
function tzs_validate_pr_search_parameters()
{
    $errors = array();
    $res = array();
    // Проверим защиту nonce
    if (isset($_POST['type_id_nonce']) && wp_verify_nonce($_POST['type_id_nonce'], 'type_id')) {
        // get parameters from _POST
        $form_type = get_param_def('form_type', '');
        $type_id = get_param_def('type_id', '0');
        $cur_type_id = get_param_def('cur_type_id', '0');
        $rootcategory = get_param_def('rootcategory', '0');
        $sale_or_purchase = get_param_def('sale_or_purchase', '0');
        $fixed_or_tender = get_param_def('fixed_or_tender', '0');
        $payment = get_param_def('payment', '0');
        $nds = get_param_def('nds', '0');
        $country_from = get_param_def('country_from', '0');
        $region_from = get_param_def('region_from', '0');
        $cityname_from = get_param('cityname_from');
        $pr_title = get_param('pr_title');
        $price_from = get_param_def('price_from', '0');
        $price_to = get_param_def('price_to', '0');
        $data_from = get_param_def('data_from', null);
        $data_to = get_param_def('data_to', null);
        $auction_type = get_param_def('auction_type', '0');
        $rate_from = get_param_def('rate_from', '0');
        $rate_to = get_param_def('rate_to', '0');
        // validate and parse parameters
        if (is_valid_num_zero($country_from)) {
            // use float not int because ID can be long
            $country_from = floatval($country_from);
        } else {
            array_push($errors, "Неверно выбрана страна");
        }
        if (is_valid_num_zero($region_from)) {
            // use float not int because ID can be long
            $region_from = floatval($region_from);
        } else {
            array_push($errors, "Неверно выбран регион");
        }
        if (is_valid_num_zero($price_from)) {
            $price_from = floatval($price_from);
        } else {
            array_push($errors, "Неверно указано начальное значение стоимости");
        }
        if (is_valid_num_zero($price_to)) {
            $price_to = floatval($price_to);
        } else {
            array_push($errors, "Неверно указано конечное значение стоимости");
        }
        if (is_valid_num_zero($rate_from)) {
            $rate_from = floatval($rate_from);
        } else {
            array_push($errors, "Неверно указано начальное значение ставки");
        }
        if (is_valid_num_zero($rate_to)) {
            $rate_to = floatval($rate_to);
        } else {
            array_push($errors, "Неверно указано конечное значение ставки");
        }
        if (is_valid_num_zero($type_id)) {
            $type_id = intval($type_id);
        } else {
            array_push($errors, "Неверно выбрана категория");
        }
        if (is_valid_num_zero($cur_type_id)) {
            $cur_type_id = intval($cur_type_id);
        } else {
            array_push($errors, "Неверно выбрана категория");
        }
        if (is_valid_num_zero($rootcategory)) {
            $rootcategory = intval($rootcategory);
        } else {
            array_push($errors, "Неверно выбрана категория");
        }
        if (is_valid_num_zero($auction_type)) {
            $auction_type = intval($auction_type);
        } else {
            array_push($errors, "Неверно выбран тип тендера");
        }
        if (is_valid_num_zero($sale_or_purchase)) {
            $sale_or_purchase = intval($sale_or_purchase);
        } else {
            array_push($errors, "Неверно выбран тип заявки");
        }
        if (is_valid_num_zero($fixed_or_tender)) {
            $fixed_or_tender = intval($fixed_or_tender);
        } else {
            array_push($errors, "Неверно выбран тип тендера");
        }
        if (is_valid_num_zero($payment)) {
            $payment = intval($payment);
        } else {
            array_push($errors, "Неверно выбран форма оплаты");
        }
        if (is_valid_num_zero($nds)) {
            $nds = intval($nds);
        } else {
            array_push($errors, "Неверно выбран НДС");
        }
        if ($cityname_from != null && strlen($cityname_from) == 0) {
            $cityname_from = null;
        }
        if ($pr_title != null && strlen($pr_title) == 0) {
            $pr_title = null;
        }
        if ($data_from != null && strlen($data_from) > 0) {
            $data_from = is_valid_date($data_from);
            if ($data_from == null) {
                array_push($errors, "Неверный формат даты (с)");
            }
        } else {
            $data_from = null;
        }
        if ($data_to != null && strlen($data_to) > 0) {
            $data_to = is_valid_date($data_to);
            if ($data_to == null) {
                array_push($errors, "Неверный формат даты (по)");
            }
        } else {
            $data_to = null;
        }
        $cityname_from_ids = null;
        if ($cityname_from != null && count($errors) == 0) {
            $r = tzs_city_to_ids($cityname_from, 0, 0);
            if (isset($r['error'])) {
                array_push($errors, $r['error']);
            } else {
                $cityname_from_ids = isset($r['ids']) ? $r['ids'] : null;
            }
        }
        // Если нет ошибок - то заполняем результирующий массив
        if (count($errors) == 0) {
            if ($country_from > 0) {
                $res['country_from'] = $country_from;
            }
            if ($region_from > 0) {
                $res['region_from'] = $region_from;
            }
            if ($cityname_from != null) {
                $res['cityname_from'] = $cityname_from;
            }
            if ($pr_title != null) {
                $res['pr_title'] = $pr_title;
            }
            if ($data_from != null) {
                $res['data_from'] = $data_from;
                $res['data_from_str'] = get_param('data_from');
            }
            if ($data_to != null) {
                $res['data_to'] = $data_to;
                $res['data_to_str'] = get_param('data_to');
            }
            if ($price_from > 0) {
                $res['price_from'] = $price_from;
            }
            if ($price_to > 0) {
                $res['price_to'] = $price_to;
            }
            if ($rate_from > 0) {
                $res['rate_from'] = $rate_from;
            }
            if ($rate_to > 0) {
                $res['rate_to'] = $rate_to;
            }
            if ($auction_type > 0) {
                $res['auction_type'] = $auction_type;
            }
            if ($type_id > 0) {
                $res['type_id'] = $type_id;
            }
            if ($cur_type_id > 0) {
                $res['cur_type_id'] = $cur_type_id;
            }
            if ($rootcategory > 0) {
                $res['rootcategory'] = $rootcategory;
            }
            if ($sale_or_purchase > 0) {
                $res['sale_or_purchase'] = $sale_or_purchase;
            }
            if ($fixed_or_tender > 0) {
                $res['fixed_or_tender'] = $fixed_or_tender;
            }
            if ($payment > 0) {
                $res['payment'] = $payment;
            }
            if ($nds > 0) {
                $res['nds'] = $nds;
            }
            if ($cityname_from_ids != null) {
                $res['cityname_from_ids'] = $cityname_from_ids;
            }
        }
    } else {
        array_push($errors, "Проверка формы не пройдена. Свяжитесь, пожалуйста, с администрацией сайта.");
    }
    $res['errors'] = $errors;
    return $res;
}
Example #22
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 #23
0
 public function addDate($date)
 {
     if (!is_valid_date($date)) {
         throw new RuntimeException('Invalid date for delivery');
     }
     $this->date = $date;
 }