<?php
include "common.php";

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 " . FORMS_TABLE . " WHERE type_form=1 or type_form=2";
$result = mysqli_query($sql_global_link, $sqlQuery);
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 " . FORMS_TABLE . " 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);
        $total_count++;
    }
};
echo "<br>Done forms: $total_count";