<?php

$sql_query = 'UPDATE ' . $config['table_prefix'] . 'calc_template SET ';
$sql_query .= <<<'EOT'
calculate_tpl = "if (!function_exists(str_replace_crm_function_for_this_expression)) {
    function str_replace_crm_function_for_this_expression(& $str_line, & $table, & $line) {
        if (mb_stripos($str_line, {literal}'{{'{/literal}) !== false) {
            $str = mb_strcut($str_line, (strpos($str_line, {literal}'{{'{/literal})+2) );
            $str = mb_strcut($str, 0, strpos($str, {literal}'}}'{/literal}) );

            if ($str == 'user_id') {
                $result = sql_fetch_assoc(sql_select_field(FIELDS_TABLE, '*', 'table_id='.$table['id'].' AND type_field=11'));
            } else {
                $str = mb_strcut($str, 1);
                $result = sql_fetch_assoc(sql_select_field(FIELDS_TABLE, '*', 'table_id='.$table['id'].' AND id='.$str));
            }

            if ($result['id']) {
                if ($result['type_field'] == 1 || $result['type_field'] == 2 || $result['type_field'] == 3 || $result['type_field'] == 4 ) {
                    $replace = $line['f'.$result['id']];
                } elseif ($result['type_field'] == 5) {
                    $type_value  = explode('|', $result['type_value']);
                    $idLine = is_array($line['f'.$result['id']]) ? ($line['f'.$result['id']]['id'] ? $line['f'.$result['id']]['id'] : -1) : ($line['f'.$result['id']] ? $line['f'.$result['id']] : -1);
                    $result_2 = sql_fetch_assoc(data_select_field($type_value['0'], 'f'.$type_value['1'], 'id=' . $idLine));
                    $replace = $result_2['f'.$type_value['1']];
                } elseif ($result['type_field'] == 7 || $result['type_field'] == 11) {
                    $result_2 = sql_fetch_assoc(sql_select_field(USERS_TABLE, 'fio', 'id='.( $str == 'user_id' ? $line['user_id'] : $line['f'.$result['id']] )));
                    $replace = $result_2['fio'];
                }

                if ($str == 'user_id') {
                    $str_line = str_replace({literal}'{{'{/literal}.$str.{literal}'}}'{/literal}, $replace, $str_line);
                } else {
                    $str_line = str_replace({literal}'{{f'{/literal}.$str.{literal}'}}'{/literal}, $replace, $str_line);
                }
                str_replace_crm_function_for_this_expression($str_line, $table, $line);
            }
        }
        return false;
    }
}

$str_line = \"{$flex_data}\";
str_replace_crm_function_for_this_expression($str_line, $table, $line);
$line['{$result}'] = $str_line;" WHERE id = 108
EOT;
run_query($sql_query);
