/**
 * Сохраняет конфигурацию в базе данных
 * @param $Exe
 * @param string $Group
 * @param bool $ShowHidden
 * @return void
 */
function AdminConfigurationSave($Exe, $Group = '', $ShowHidden = false)
{
    global $config, $conf_config_table, $conf_config_groups_table;
    // Вытаскиваем настройки и отсортировываем по группам
    $temp = System::database()->Select($conf_config_table, '');
    for ($i = 0, $cnt = count($temp); $i < $cnt; $i++) {
        $configs[$temp[$i]['group_id']][] = $temp[$i];
    }
    unset($temp);
    // Вытаскиваем группы настроек
    if ($Group == '') {
        $q = '';
    } else {
        $q = "`name`='" . $Group . "'";
    }
    $cfg_grps = System::database()->Select($conf_config_groups_table, $q);
    for ($i = 0, $cnt = count($cfg_grps); $i < $cnt; $i++) {
        // Если эта группа невидима то пропускаем её
        if ($Group == '') {
            if ($cfg_grps[$i]['visible'] == 0) {
                continue;
            }
        }
        // Или если в ней нет настроек
        if (!isset($configs[$cfg_grps[$i]['id']])) {
            continue;
        }
        for ($j = 0, $jcnt = count($configs[$cfg_grps[$i]['id']]); $j < $jcnt; $j++) {
            // Если настройка невидима то пропускаем её
            if ($configs[$cfg_grps[$i]['id']][$j]['visible'] == 0 && !$ShowHidden) {
                continue;
            }
            $name = $configs[$cfg_grps[$i]['id']][$j]['name'];
            $kind = explode(':', $configs[$cfg_grps[$i]['id']][$j]['kind']);
            $kind = trim(strtolower($kind[0]));
            $savefunc = trim($configs[$cfg_grps[$i]['id']][$j]['savefunc']);
            $type = trim($configs[$cfg_grps[$i]['id']][$j]['type']);
            if ($type != '') {
                $type = explode(',', $type);
            } else {
                $type = array(255, str, false);
            }
            $where = "`name`='{$name}' and `group_id`='" . $cfg_grps[$i]['id'] . "'";
            if (isset($_POST[$name])) {
                switch ($kind) {
                    case 'edit':
                    case 'radio':
                    case 'combo':
                        if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                            $savefunc = CONF_SAVE_PREFIX . $savefunc;
                            $value = $savefunc(FormsCheckType($_POST[$name], $type));
                        } else {
                            $value = FormsCheckType($_POST[$name], $type);
                        }
                        break;
                    case 'text':
                        if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                            $savefunc = CONF_SAVE_PREFIX . $savefunc;
                            $value = $savefunc(FormsCheckType($_POST[$name], $type));
                        } else {
                            $value = FormsCheckType($_POST[$name], $type);
                        }
                        break;
                    case 'check':
                    case 'list':
                        if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                            $savefunc = CONF_SAVE_PREFIX . $savefunc;
                            $value = $savefunc(FormsCheckType($_POST[$name], $type));
                        } else {
                            if (isset($_POST[$name])) {
                                $c = count($_POST[$name]);
                            } else {
                                $c = 0;
                            }
                            $value = '';
                            for ($k = 0; $k < $c; $k++) {
                                $value .= ',';
                                $value .= FormsCheckType($_POST[$name][$k], $type);
                            }
                            $value = substr($value, 1);
                        }
                        break;
                    default:
                        if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                            $savefunc = CONF_SAVE_PREFIX . $savefunc;
                            $value = $savefunc(FormsCheckType($_POST[$name], $type));
                        } else {
                            $value = FormsCheckType($_POST[$name], $type);
                        }
                }
                System::database()->Update($conf_config_table, 'value=\'' . $value . '\'', $where);
                // FIXME: Использовать транзакцию
            }
        }
    }
    // Очищаем кэш настроек
    System::cache()->Clear('config');
    GO(ADMIN_FILE . '?exe=' . $Exe);
}
function IndexFormSave($form)
{
    // Проверяем капчу
    if (!System::user()->Auth || !System::user()->isAdmin() && System::config('forms/show_captcha')) {
        if (!isset($_POST['keystr']) || !System::user()->isDef('captcha_keystring') || System::user()->Get('captcha_keystring') != $_POST['keystr']) {
            $text = '<p align="center">Вы ошиблись при вводе кода с картинки. Форма не отправлена.</p>';
            $text .= '<p align="center"><input type="button" value="Назад" onclick="history.back();"></p>';
            System::site()->AddTextBox('', $text);
            return;
        }
    }
    $errors = array();
    $controls = unserialize($form['form_data']);
    $post_data = array();
    foreach ($controls as $control) {
        $error = '';
        $name = $control['name'];
        $hname = $control['hname'];
        $kind = FormsParseParams($control['kind']);
        $savefunc = trim($control['savefunc']);
        $type = trim($control['type']);
        if ($type != '') {
            $type = explode(',', $type);
        } else {
            $type = array(255, str, false);
        }
        switch ($kind['control']) {
            case 'edit':
                if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                    $value = CONF_SAVE_PREFIX . $savefunc(FormsCheckType($_POST[$name], $type));
                } else {
                    $value = FormsCheckType($_POST[$name], $type);
                }
                if ($kind['required'] && $value == '') {
                    $errors[] = 'Обязательное поле "' . SafeDB($hname, 255, str) . '" не заполнено.';
                }
                break;
                //case 'radio' :
            //case 'radio' :
            case 'combo':
                $vals = IndexFormGetValues($name, $control['values']);
                if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                    $value = CONF_SAVE_PREFIX . $savefunc(FormsCheckType($_POST[$name], $type));
                } else {
                    $value = $vals[$_POST[$name]];
                }
                if ($kind['required'] && $value == '') {
                    $errors[] = 'Значение в поле "' . SafeDB($hname, 255, str) . '" не выбрано.';
                }
                break;
            case 'text':
                if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                    $value = CONF_SAVE_PREFIX . $savefunc(FormsCheckType($_POST[$name], $type));
                } else {
                    $value = FormsCheckType($_POST[$name], $type);
                }
                if ($kind['required'] && $value == '') {
                    $errors[] = 'Обязательное поле "' . SafeDB($hname, 255, str) . '" не заполнено.';
                }
                break;
            case 'check':
            case 'list':
                $vals = IndexFormGetValues($name, $control['values']);
                if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                    $value = CONF_SAVE_PREFIX . $savefunc(FormsCheckType($_POST[$name], $type));
                } else {
                    if (isset($_POST[$name])) {
                        $c = count($_POST[$name]);
                    } else {
                        $c = 0;
                    }
                    $value = '';
                    for ($k = 0; $k < $c; $k++) {
                        $value .= ',';
                        $value .= $vals[$_POST[$name][$k]];
                    }
                    $value = substr($value, 1);
                }
                if ($kind['required'] && $value == '') {
                    $errors[] = 'Значение в поле "' . SafeDB($hname, 255, str) . '" не выбрано.';
                }
                break;
            case 'file':
                if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                    $value = CONF_SAVE_PREFIX . $savefunc(FormsCheckType($_POST[$name], $type));
                } else {
                    $value = FormsCheckType($_FILES[$name], $type, $error, $filename);
                }
                if ($error != '') {
                    $errors[] = $error;
                } elseif ($kind['required'] && $value == '') {
                    $errors[] = 'Файл в поле "' . SafeDB($hname, 255, str) . '" не выбран.';
                }
                break;
            default:
                if (FormsConfigCheck2Func('function', $savefunc, 'save')) {
                    $value = CONF_SAVE_PREFIX . $savefunc(FormsCheckType($_POST[$name], $type));
                } else {
                    $value = FormsCheckType($_POST[$name], $type);
                }
        }
        if ($type[1] == 'file') {
            $post_data[] = array($hname, $value, $type[1], $filename);
        } else {
            $post_data[] = array($hname, $value, $type[1]);
        }
    }
    /*
     * Вывод ошибок.
     */
    if (count($errors) > 0) {
        $text = '<p>Произошли ошибки при потправке формы:</p><ul>';
        foreach ($errors as $error) {
            $text .= '<li>' . $error . '</li>';
        }
        $text .= '</ul>';
        $text .= '<p align="center"><input type="button" value="Назад" onclick="history.back();"></p>';
        System::site()->AddTextBox('', $text);
        return;
    }
    $form_id = SafeEnv($form['id'], 11, int);
    if (System::user()->Auth) {
        $user_id = System::user()->Get('u_id');
    } else {
        $user_id = 0;
    }
    $time = time();
    $ip = getip();
    if ($form['email'] != '') {
        IndexFormSendMail($form['email'], $form['hname'], $time, $user_id, $ip, $post_data);
    }
    $data = serialize($post_data);
    $data = SafeEnv($data, 0, str);
    System::database()->Insert('forms_data', "'','{$form_id}','{$user_id}','{$time}','{$data}','0','{$ip}'");
    $new = $form['new_answ'] + 1;
    $cnt = $form['answ'] + 1;
    System::database()->Update('forms', "`answ`='{$cnt}',`new_answ`='{$new}'", "`id`='{$form_id}'");
    if ($form['send_ok_msg'] != '') {
        $msg = SafeDB($form['send_ok_msg'], 0, str, false, false);
    } else {
        $msg = 'Ваша форма отправлена успешно.';
    }
    System::site()->AddTextBox('', '<p align="center">' . $msg . '</p>');
}