<?php
run_query("UPDATE " . $config["table_prefix"] . "config SET `value` = '010903' WHERE `key` = 'version'");

// указатель о том что неправильный email
run_query("ALTER TABLE `" . $config["table_prefix"] . "unsubscribe` ADD `invalid_mail` TINYINT( 1 ) NOT NULL");
run_query("ALTER TABLE `" . $config["table_prefix"] . "unsubscribe` ADD `mailbox` VARCHAR( 255 ) NOT NULL");
run_query("ALTER TABLE `" . $config["table_prefix"] . "smtp` ADD `check_invalid_email` TINYINT( 1 ) NOT NULL");
run_query("ALTER TABLE `" . $config["table_prefix"] . "smtp` ADD `imap_host` VARCHAR( 255 ) NOT NULL");
run_query("ALTER TABLE `" . $config["table_prefix"] . "smtp` ADD `imap_port` VARCHAR( 255 ) NOT NULL");
run_query("ALTER TABLE `" . $config["table_prefix"] . "smtp` ADD `imap_login` VARCHAR( 255 ) NOT NULL");
run_query("ALTER TABLE `" . $config["table_prefix"] . "smtp` ADD `imap_pass` VARCHAR( 255 ) NOT NULL");
run_query("ALTER TABLE `" . $config["table_prefix"] . "smtp` ADD `imap_sec`  VARCHAR( 10 ) NOT NULL");

// визуализация служебных полей
$result = run_query("SELECT * FROM " . $config["table_prefix"] . "tables");
while ($row = mysqli_fetch_array($result)) {
    $table_id = $row['id'];
    // перенумеровываем поля
    $field_num = 5;
    $result2 = run_query("SELECT id FROM " . $config["table_prefix"] . "fields WHERE table_id=" . $table_id . " ORDER BY field_num");
    while ($row2 = mysqli_fetch_array($result2)) {
        run_query("UPDATE " . $config["table_prefix"] . "fields SET field_num=" . ($field_num++) . " WHERE id=" . $row2["id"]);
    }
    // создание служебных полей
    run_query("INSERT INTO " . $config["table_prefix"] . "fields VALUES ('', " . $table_id . ", 1, 'ID', 10, '', '{autonumber}', '', '', 1, 1, 0, 0)");
    $field_id_10 = mysqli_insert_id($sql_global_link);
    run_query("INSERT INTO " . $config["table_prefix"] . "fields VALUES ('', " . $table_id . ", 2, '" . $lang['added_by'] . "', 11, '0|0', '{current}', '', '', 0, 0, 0, 0)");
    $field_id_11 = mysqli_insert_id($sql_global_link);
    run_query("INSERT INTO " . $config["table_prefix"] . "fields VALUES ('', " . $table_id . ", 3, '" . $lang['addition_time'] . "', 12, '1', '{cur.time}', '', '', 0, 0, 0, 0)");
    $field_id_12 = mysqli_insert_id($sql_global_link);
    run_query("INSERT INTO " . $config["table_prefix"] . "fields VALUES ('', " . $table_id . ", 4, '" . $lang['record_status'] . "', 13, '', '', '', '', 0, 0, 0, 0)");
    $field_id_13 = mysqli_insert_id($sql_global_link);
    // создание прав пользователей на служебные поля
    $result2 = run_query("SELECT * FROM " . $config["table_prefix"] . "groups");
    while ($row2 = mysqli_fetch_array($result2)) {
        $group_id = $row2['id'];
        run_query("INSERT INTO " . $config["table_prefix"] . "acc_fields VALUES ('', " . $group_id . ", " . $table_id . ", " . $field_id_10 . ", 0, 0, 0, 0)");
        run_query("INSERT INTO " . $config["table_prefix"] . "acc_fields VALUES ('', " . $group_id . ", " . $table_id . ", " . $field_id_11 . ", 0, 0, 0, 0)");
        run_query("INSERT INTO " . $config["table_prefix"] . "acc_fields VALUES ('', " . $group_id . ", " . $table_id . ", " . $field_id_12 . ", 0, 0, 0, 0)");
        run_query("INSERT INTO " . $config["table_prefix"] . "acc_fields VALUES ('', " . $group_id . ", " . $table_id . ", " . $field_id_13 . ", 0, 0, 0, 0)");
    }
}

// чтобы в напоминания можно было вставлять другие события
run_query("ALTER TABLE `" . $config["table_prefix"] . "tips_show` ADD `custom_url` VARCHAR( 1024 ) NOT NULL");

// шаблоны импорта
run_query("CREATE TABLE `" . $config["table_prefix"] . "import_tpl` (`id` int( 11 ) AUTO_INCREMENT NOT NULL, `table_id` int( 11 ) NOT NULL, `name` varchar( 255 ) NOT NULL, `imp_config` text NOT NULL, PRIMARY KEY ( `id` )) ENGINE = MYISAM DEFAULT CHARSET = utf8 COLLATE = utf8_general_ci;");

// создаем скрытые поля
run_query("ALTER TABLE `" . $config["table_prefix"] . "fields` ADD `hidden` TINYINT( 1 ) NOT NULL DEFAULT '0'");

// меняем права доступа
run_query("CREATE TABLE `" . $config["table_prefix"] . "acc_fields_ex` (`table_id` int(11) NOT NULL, `user_fid` int(11) NOT NULL, `field_id` int(11) NOT NULL, `read_tb` tinyint(1) NOT NULL, `read` tinyint(1) NOT NULL, `write` tinyint(1) NOT NULL, KEY `user_id` (`user_fid`), KEY `field_id` (`field_id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1");

// Проверяем поля скрытые для администратора, служебные поля
$result = run_query("SELECT a.*, b.name_field FROM " . $config["table_prefix"] . "acc_fields a, " . $config["table_prefix"] . "fields b  WHERE a.group_id=1 and  a.field_id=b.id and a.`read_tb`=0 and a.`read_ed`=0");
while ($row = mysqli_fetch_array($result)) {
    $id = $row["id"];
    $table_id = $row["table_id"];
    $field_id = $row["field_id"];
    $field_name = $row["name_field"];
    // Проверяем есть ли это поле в шаблонах?
    $var_field = utf2eng($field_name);
    $sql = "SELECT * FROM " . $config["table_prefix"] . "forms WHERE `head_form` LIKE '%{$var_field}%' or `body_form` LIKE '%{$var_field}%' or `foot_form` LIKE '%{$var_field}%'";
    $result2 = run_query($sql);
    if ($row2 = mysqli_fetch_array($result2)) { // да есть в шаблоне печати, метим поле как скрытое
        run_query("UPDATE `" . $config["table_prefix"] . "fields` SET hidden=1 WHERE id='$field_id'");
        // меняем права доступа, разрешаем чтение
        run_query("UPDATE `" . $config["table_prefix"] . "acc_fields` SET `read_ed`=1 WHERE id='$id'");
    };
}

// делаем выборку из текущих прав пользователей, переводим их в новую б.д.
$result = run_query("SELECT * FROM " . $config["table_prefix"] . "acc_fields WHERE write_my!=write_an");
while ($row = mysqli_fetch_array($result)) {
    $table_id = $row["table_id"];
    $field_id = $row["field_id"];
    $read_tb = $row["read_tb"];
    $read_ed = $row["read_ed"];
    // выбираем поле пользователь. для данной таблицы
    $result2 = run_query("SELECT * FROM " . $config["table_prefix"] . "fields WHERE `table_id`='$table_id' and `type_field`='11'");
    if ($row2 = mysqli_fetch_array($result2)) {
        $usr_fid = $row2["id"];
    } else { // нет поля пользователь, для данной таблицы
        run_query("No user field for table$table_id.");
    }

    run_query("UPDATE " . $config["table_prefix"] . "fields SET `type_value`='0|0|1' WHERE id='$usr_fid' and `type_value`='0|0'");

    $result2 = run_query("SELECT * FROM " . $config["table_prefix"] . "acc_fields_ex WHERE `table_id`='$table_id' and `user_fid`='$usr_fid' and `field_id`='$field_id'");
    if ($row2 = mysqli_fetch_array($result2)) { // Уже есть такая строка
        continue;
    }

    if ($row["write_an"] == 0) { // запрещено писать чужие, разрешено свои
        // меняем у данной таблицы, у поля пользователь, тип на применять права
        run_query("UPDATE " . $config["table_prefix"] . "acc_fields SET `write_an`='0' WHERE id='" . $row["id"] . "'");
        run_query("INSERT INTO " . $config["table_prefix"] . "acc_fields_ex (`table_id`,`user_fid`,`field_id`,`read_tb`,`read`,`write`) VALUES ('$table_id', '$usr_fid', '$field_id', '$read_tb', '$read_ed', '1')");
    } else { // запрещено писать cвои, разрешено чужие
        run_query("UPDATE " . $config["table_prefix"] . "acc_fields SET `write_an`='1' WHERE id='" . $row["id"] . "'");
        run_query("INSERT INTO " . $config["table_prefix"] . "acc_fields_ex (`table_id`,`user_fid`,`field_id`,`read_tb`,`read`,`write`) VALUES ('$table_id', '$usr_fid', '$field_id', '$read_tb', '$read_ed', '0')");
    }
};
run_query("ALTER TABLE `" . $config["table_prefix"] . "acc_fields` DROP `write_my`");
run_query("ALTER TABLE `" . $config["table_prefix"] . "acc_fields` CHANGE `read_ed` `read` TINYINT( 1 ) NOT NULL DEFAULT '0'");
run_query("ALTER TABLE `" . $config["table_prefix"] . "acc_fields` CHANGE `write_an` `write` TINYINT( 1 ) NOT NULL DEFAULT '0'");

// Быстрое редактирование на форме
run_query("ALTER TABLE `" . $config["table_prefix"] . "fields` ADD `fast_edit` TINYINT NOT NULL DEFAULT '0'");

//Cкролл
run_query("INSERT INTO " . $config["table_prefix"] . "config (`key`,`value`) VALUES ('window_scroll','0')");
run_query("ALTER TABLE `" . $config["table_prefix"] . "users`  ADD `window_scroll` TINYINT( 1 ) NOT NULL DEFAULT '-1'");
run_query("ALTER TABLE `" . $config["table_prefix"] . "tables` ADD `fixed_scroll`  INT(11) NOT NULL DEFAULT '0'");


// фиксируем отчеты
function replace_d($d1)
{
    $st = 0;
    while (1) {
        $p1 = '$';
        $t1 = strpos($d1, $p1, $st);
        if ($t1 !== false) {
            // проверяем скобки
            if ($d1[$t1 - 1] == '{') {
                $st = $t1 + 1;
                continue;
            }
            // неэкранированная область
            $end_char = strlen($d1);
            for ($m = $t1 + 1; $m < strlen($d1); $m++) {
                // цифры буквы точки допустимы
                if (((ord($d1[$m]) > 47) && (ord($d1[$m]) < 58)) || ((ord($d1[$m]) > 96) && (ord($d1[$m]) < 123)) || ((ord($d1[$m]) > 64) && (ord($d1[$m]) < 91)) || ($d1[$m] == ".") || ($d1[$m] == "_")) {
                    continue;
                } else {
                    $end_char = $m;
                    break;
                }
            }
            $d1 = substr($d1, 0, $t1) . "{" . substr($d1, $t1, $end_char - $t1) . "}" . substr($d1, $end_char,
                    strlen($d1) + 1);
            $st = 0;
        } else {
            break;
        }
    }
    return $d1;
}

function replace_p($v1)
{
    while (1) {
        $p1 = '{SumFormat value=$';
        $t1 = strpos($v1, $p1);
        if ($t1) {
            $t1 = $t1 + strlen($p1) - 1;
            $t2 = strpos($v1, " ", $t1);
            $t_res = substr($v1, $t1, $t2 - $t1);
//            echo "<br>".$t_res."=>";
            $t_res = '"' . replace_d($t_res) . '"';
//            echo $t_res;
            $v1 = substr($v1, 0, $t1) . $t_res . substr($v1, $t2, strlen($v1));
        } else {
            break;
        }
    }
    return $v1;
}

;

$total_count = 0;
$sqlQuery = "SELECT * FROM " . $config["table_prefix"] . "forms WHERE type_form=1 or type_form=2";
$result = mysqli_query($sql_global_link, $sqlQuery) or user_error(mysqli_error($sql_global_link) . "<br>" . $sqlQuery . "<br>", E_USER_ERROR);
while ($row = mysqli_fetch_array($result)) {
    $body_form = replace_p($row["body_form"]);
    $head_form = replace_p($row["head_form"]);
    $foot_form = replace_p($row["foot_form"]);

    if (($body_form != $row["body_form"]) || ($head_form != $row["head_form"]) || ($foot_form != $row["foot_form"])) {
        $sqlQuery = "UPDATE " . $config["table_prefix"] . "forms SET body_form='" . addslashes($body_form) . "', head_form='" . addslashes($head_form) . "', foot_form='" . addslashes($foot_form) . "' WHERE id='" . $row["id"] . "'";
        mysqli_query($sql_global_link, $sqlQuery) or user_error(mysqli_error($sql_global_link) . "<br>" . $sqlQuery . "<br>", E_USER_ERROR);
        $total_count++;
    }
};


// Заголовок и отправитель напоминания на емейл
run_query("ALTER TABLE `" . $config["table_prefix"] . "tips` ADD `email_sender` VARCHAR( 255 ) NOT NULL AFTER `email_on`, ADD `email_header` VARCHAR( 255 ) NOT NULL AFTER `email_sender`");
run_query("UPDATE `" . $config["table_prefix"] . "tips` SET `email_sender` = '" . $config['application'] . "', `email_header` = '" . $lang['Tip'] . "'");


// Добавление настройки яваскрипта в поле
run_query("ALTER TABLE `" . $config["table_prefix"] . "fields` ADD `javascript` TEXT NOT NULL AFTER `default_value`");

?>