Exemple #1
0
/**
 * Копирование объекта из одного шаблона в разделе в другой.
 *
 * Пользователь должен обладать правами: изменение в разделе, где
 * находится объект, и удаление в разделе, куда переносится объект.
 *
 * @param integer ID класса объекта
 * @param integer ID объекта
 * @param integer ID шаблона в разделе, куда переносится объект
 * @return boolean
 */
function nc_copy_message($class_id, $message_id, $destination_cc_id)
{
    global $nc_core, $db;
    $class_id = (int) $class_id;
    $message_id = (int) $message_id;
    $destination_cc_id = (int) $destination_cc_id;
    if (!$class_id || !$message_id || !$destination_cc_id) {
        trigger_error("Wrong parameters for nc_copy_message()", E_USER_WARNING);
        return false;
    }
    // данные о месте назначения
    $dest_subclass = $db->get_row("SELECT sd.Catalogue_ID,\n                                        sc.Sub_Class_ID,\n                                        sc.Subdivision_ID,\n                                        sc.Class_ID,\n                                        IFNULL(MAX(m.Priority)+1,1) as Next_Priority\n                                   FROM (Sub_Class as sc,\n                                        Subdivision as sd)\n                                        LEFT JOIN Message{$class_id} as m\n                                          ON m.Sub_Class_ID=sc.Sub_Class_ID\n                                  WHERE sc.Sub_Class_ID={$destination_cc_id}\n                                    AND sc.Subdivision_ID=sd.Subdivision_ID\n                                  GROUP BY m.Sub_Class_ID\n                                  ", ARRAY_A);
    // переносимый объект
    $message = $db->get_row("SELECT * FROM Message{$class_id} WHERE Message_ID = {$message_id}", ARRAY_A);
    if (!$message || !$dest_subclass) {
        $what = $message ? 'subclass' : 'object';
        trigger_error("nc_copy_message: {$what} doesn't exist", E_USER_WARNING);
        return false;
    }
    if ($dest_subclass['Class_ID'] != $class_id) {
        trigger_error("nc_copy_message: destination subclass belongs to different class", E_USER_WARNING);
        return false;
    }
    //  if ($dest_subclass['Sub_Class_ID'] == $message['Sub_Class_ID']) { return true; } // Проверка на копирование объекта внутри одного $cc
    // права
    // Пользователь должен обладать правами: чтение в разделе, где
    // находится объект, и добавление в разделе, куда переносится объект.
    global $perm;
    $has_rights = false;
    $has_rights = $perm->isSubClass($message['Sub_Class_ID'], 48) && $perm->isSubClass($dest_subclass['Sub_Class_ID'], 48);
    if (!$has_rights) {
        trigger_error("nc_copy_message: insufficient rights", E_USER_WARNING);
        return false;
    }
    // end of права
    global $AUTH_USER_ID, $HTTP_USER_AGENT;
    $message['Message_ID'] = '';
    $message['Subdivision_ID'] = $dest_subclass['Subdivision_ID'];
    $message['Sub_Class_ID'] = $dest_subclass['Sub_Class_ID'];
    $message['Priority'] = $dest_subclass['Next_Priority'];
    $message['Created'] = $message['LastUpdated'] = date("Y-m-d H:i:s");
    $message['UserAgent'] = $message['LastUserAgent'] = $HTTP_USER_AGENT;
    $message['IP'] = $message['LastIP'] = getenv("REMOTE_ADDR");
    $message['Keyword'] = nc_unique_message_keyword($message['Keyword'], $class_id);
    $col_names = array_keys($message);
    if (!empty($col_names)) {
        foreach ($col_names as $k => $v) {
            $col_names[$k] = "`" . $v . "`";
        }
        $col_names_string = join(", ", $col_names);
    }
    $col_values = array_values($message);
    foreach ($col_values as &$value) {
        $value = $db->prepare($value);
    }
    $col_values_string = join("', '", $col_values);
    // execute core action
    $nc_core->event->execute("addMessagePrep", $dest_subclass['Catalogue_ID'], $dest_subclass['Subdivision_ID'], $dest_subclass['Sub_Class_ID'], $class_id, 0);
    $db->query("INSERT INTO Message{$class_id} (" . $col_names_string . ") VALUES ('" . $col_values_string . "')");
    $new_message_id = $db->insert_id;
    // execute core action
    $nc_core->event->execute("addMessage", $dest_subclass['Catalogue_ID'], $dest_subclass['Subdivision_ID'], $dest_subclass['Sub_Class_ID'], $class_id, $new_message_id);
    // копирование детей
    $childs_id = $db->get_col("SELECT `Message_ID` FROM `Message" . $class_id . "` WHERE `Parent_Message_ID` = '" . $message_id . "' ");
    if (!empty($childs_id)) {
        foreach ($childs_id as $child_id) {
            $new_child_id = nc_copy_message($class_id, $child_id, $destination_cc_id);
            // у дочернего объекта Parent message id остался от копируемого объекта
            $db->query("UPDATE `Message" . $class_id . "` SET `Parent_Message_ID` = '" . $new_message_id . "' WHERE `Message_ID` = '" . $new_child_id . "' ");
        }
    }
    // prepare dirs
    global $FILES_FOLDER, $DIRCHMOD, $DOCUMENT_ROOT, $SUB_FOLDER;
    require_once $GLOBALS['INCLUDE_FOLDER'] . "s_common.inc.php";
    // файлы
    // Поля типа "файл" в компоненте
    $file_fields = $db->get_results("SELECT `Field_ID`, `Format`, `Field_Name`\n                                    FROM `Field`\n                                    WHERE Class_ID='" . $class_id . "'\n                                    AND TypeOfData_ID='" . NC_FIELDTYPE_FILE . "'", ARRAY_A);
    if (!empty($file_fields)) {
        // проходим по каждому полю
        foreach ($file_fields as $field) {
            // если нету файл у исходного объекта - то переходим к следующему полю
            if (!$message[$field['Field_Name']]) {
                continue;
            }
            // определение файловой системы для записи нового файла
            $parsedFormat = nc_field_parse_format($field['Format'], NC_FIELDTYPE_FILE);
            $fs = $parsedFormat['fs'];
            //исходный файл
            $src_file_path = nc_file_path($class_id, $message_id, $field['Field_ID']);
            // его путь
            $value_array = explode(':', $message[$field['Field_Name']]);
            $src_file_name = $value_array[0];
            // оригинальное имя
            $src_file_type = $value_array[1];
            // тип
            $src_file_size = $value_array[2];
            // размер
            $ext = substr($src_file_name, strrpos($src_file_name, "."));
            // расширение
            // в зависимости от ФС менятеся папка и имя на диске + значени в БД
            switch ($fs) {
                case NC_FS_SIMPLE:
                    $put_file_name = $field['Field_ID'] . "_" . $new_message_id . $ext;
                    // имя файла: IDполя_IDобъекта.расширение
                    $FilePath = '';
                    // в папку netcat_files
                    $fieldValue = $src_file_name . ":" . $src_file_type . ":" . $src_file_size;
                    // значение в базу
                    break;
                case NC_FS_ORIGINAL:
                    $put_file_name = nc_transliterate($src_file_name);
                    $FilePath = "{$dest_subclass['Subdivision_ID']}/{$dest_subclass['Sub_Class_ID']}/";
                    #check and create dirs
                    $dirs = array($FILES_FOLDER . $dest_subclass['Subdivision_ID'], $FILES_FOLDER . $dest_subclass['Subdivision_ID'] . '/' . $dest_subclass['Sub_Class_ID']);
                    foreach ($dirs as $dir) {
                        if (!file_exists($dir) && !mkdir($dir, $DIRCHMOD)) {
                            return false;
                        }
                        // can't create dir
                    }
                    $k = 0;
                    // файл с таким именем может существовать - нужно добавить индекс
                    if (file_exists($FILES_FOLDER . $FilePath . $put_file_name)) {
                        while (file_exists($FILES_FOLDER . $FilePath . substr($put_file_name, 0, strrpos($put_file_name, ".")) . "_" . $k . $ext)) {
                            $k++;
                        }
                        $put_file_name = substr($put_file_name, 0, strrpos($put_file_name, ".")) . "_" . $k . $ext;
                    }
                    $fieldValue = $src_file_name . ":" . $src_file_type . ":" . $src_file_size . ":" . $FilePath . $put_file_name;
                    // значение в базу
                    break;
                case NC_FS_PROTECTED:
                    #check and create dirs
                    $dirs = array($FILES_FOLDER . $dest_subclass['Subdivision_ID'], $FILES_FOLDER . $dest_subclass['Subdivision_ID'] . '/' . $dest_subclass['Sub_Class_ID']);
                    foreach ($dirs as $dir) {
                        if (!file_exists($dir) && !mkdir($dir, $DIRCHMOD)) {
                            return false;
                        }
                        // can't create dir
                    }
                    // директория
                    $FilePath = "/{$dest_subclass['Subdivision_ID']}/{$dest_subclass['Sub_Class_ID']}/";
                    // имя файла
                    $put_file_name = md5($src_file_name . date("H:i:s d.m.Y") . uniqid("NetCat"));
                    // в таблицу Filetable
                    $db->query("INSERT INTO Filetable (ID, Real_Name, Virt_Name, File_Path, File_Type, File_Size, Message_ID, Field_ID)\n              VALUES ('', '" . $src_file_name . "', '" . $put_file_name . "', '" . $FilePath . "', '" . $src_file_type . "',\n              '" . $src_file_size . "', '" . $new_message_id . "', '" . $field['Field_ID'] . "')");
                    $fieldValue = $src_file_name . ":" . $src_file_type . ":" . $src_file_size;
                    // значение в базу
                    break;
            }
            // копирование файла
            copy($DOCUMENT_ROOT . $src_file_path, $FILES_FOLDER . $FilePath . $put_file_name);
            // правка в БД
            $db->query("UPDATE `Message" . $class_id . "` SET `" . $field['Field_Name'] . "` = '" . $fieldValue . "' WHERE `Message_ID`='" . $new_message_id . "'");
        }
    }
    // Поля типа "множественная загрузка" в компоненте
    $multifile_fields = $db->get_results("SELECT `Field_ID`, `Format`, `Field_Name`\n                                    FROM `Field`\n                                    WHERE Class_ID='" . $class_id . "'\n                                    AND TypeOfData_ID='" . NC_FIELDTYPE_MULTIFILE . "'", ARRAY_A);
    // проходим по каждому полю
    foreach ((array) $multifile_fields as $field) {
        $field_id = (int) $field['Field_ID'];
        $settings_http_path = nc_standardize_path_to_folder($nc_core->HTTP_FILES_PATH . "/multifile/{$field_id}/");
        $settings_path = nc_standardize_path_to_folder($nc_core->DOCUMENT_ROOT . '/' . $nc_core->SUB_FOLDER . '/' . $settings_http_path);
        //получаем список файлов
        $sql = "SELECT `Priority`, `Name`, `Size`, `Path`, `Preview` FROM `Multifield` WHERE `Field_ID` = {$field_id} AND `Message_ID` = {$message_id}";
        $files = $db->get_results($sql, ARRAY_A);
        foreach ((array) $files as $file) {
            foreach (array('Path', 'Preview') as $path) {
                $file_path = $file[$path];
                if ($file_path) {
                    $parts = explode('/', nc_standardize_path_to_file($file_path));
                    $file_name = array_pop($parts);
                    $file_http_path = nc_standardize_path_to_folder(implode('/', $parts));
                    $file_path = nc_standardize_path_to_folder($nc_core->DOCUMENT_ROOT . '/' . $nc_core->SUB_FOLDER . '/' . $file_http_path);
                    $new_file_name = nc_get_filename_for_original_fs($file_name, $file_path);
                    @copy($file_path . $file_name, $file_path . $new_file_name);
                    $file[$path] = $file_http_path . $new_file_name;
                }
            }
            $priority = (int) $file['Priority'];
            $name = $db->escape($file['Name']);
            $size = (int) $file['Size'];
            $path = $db->escape($file['Path']);
            $preview = $db->escape($file['Preview']);
            $sql = "INSERT INTO `Multifield` (`Field_ID`, `Message_ID`, `Priority`, `Name`, `Size`, `Path`, `Preview`) VALUES " . "({$field_id}, {$new_message_id}, {$priority}, '{$name}', {$size}, '{$path}', '{$preview}')";
            $db->query($sql);
        }
    }
    return $new_message_id;
}
Exemple #2
0
     if ($ignore_link || $cc_env['SrcMirror']) {
         $subLink = nc_folder_path($cc_env['Subdivision_ID']);
         $cc_keyword = $cc_env['EnglishName'];
     }
 }
 // Прежние названия переменных в fetch_row:
 $f_RowID = $resMsg[$user_table_mode ? 'User_ID' : 'Message_ID'];
 $f_UserID = $f_User_ID;
 $f_LastUserID = $f_LastUser_ID;
 $f_UserGroup = $f_PermissionGroup_ID;
 $Hidden_URL = $f_Hidden_URL;
 // разрешить html-теги и перенос строки
 $cc_env['convert2txt'] = "";
 $text_fields = $component->get_fields(3);
 foreach ($text_fields as $field) {
     $format = nc_field_parse_format($field['format'], 3);
     // разрешить html
     if (!$cc_env['AllowTags'] && !$format['html'] || $format['html'] == 2) {
         $cc_env['convert2txt'] .= "\$f_" . $field['name'] . " = htmlspecialchars(\$f_" . $field['name'] . ");";
     }
     // перенос строки
     if ($cc_env['NL2BR'] && !$format['br'] || $format['br'] == 1) {
         $cc_env['convert2txt'] .= "\$f_" . $field['name'] . " = nl2br(\$f_" . $field['name'] . ");";
     }
     if ($format['bbcode']) {
         $cc_env['convert2txt'] .= "\$f_" . $field['name'] . " = nc_bbcode(\$f_" . $field['name'] . ",  '', 1 );";
     }
 }
 $text_fields = $component->get_fields(1);
 foreach ($text_fields as $field) {
     if (!$cc_env['AllowTags']) {
Exemple #3
0
 if ($res_hash || $res_max) {
     echo 'Substitution of data!';
     exit;
 }
 $not_null = $fldNotNull[$i] && count($_FILES["f_{$fld[$i]}_file"]['name']) == 0;
 $not_min = $cnt < $_POST['settings_' . $fld[$i]]['min'];
 if (($not_null || $not_min) && $action != "change") {
     $errCode = 1;
     break;
 }
 $multifile_error_desc = array(NETCAT_MODERATION_MULTIFILE_ZERO, NETCAT_MODERATION_MULTIFILE_ONE, NETCAT_MODERATION_MULTIFILE_TWO);
 $multifile_warnText_array = array();
 $multifile_format_types = array();
 $multifile_format = array_shift(explode(';', $fldFmt[$i]));
 if ($multifile_format) {
     $parsedFormat = nc_field_parse_format($multifile_format, NC_FIELDTYPE_FILE);
     $multifile_format_size = $parsedFormat['size'];
     $multifile_format_types = (array) $parsedFormat['type'];
 }
 foreach ((array) $_FILES["f_{$fld[$i]}_file"]['name'] as $index => $name) {
     $current_file_name = strip_tags($name);
     if (!$fldFmt[$i]) {
         continue;
     }
     if ($multifile_format_size && $_FILES["f_{$fld[$i]}_file"]['size'][$index] > $multifile_format_size) {
         $multifile_warnText_array[1][$start] = $current_file_name;
     }
     if (empty($multifile_format_types[0])) {
         continue;
     }
     $file_type_parsed = explode("/", $_FILES["f_{$fld[$i]}_file"]['type'][$index]);
Exemple #4
0
/**
 * Вывод поля типа "Строка" в альтернативных формах шаблона
 * @param string имя поля
 * @param string дополнительные свойства для <input ...>
 * @param int идентификатор компонента, его стоит указывать при вызове функции т.к. в функции s_list_class() его глобальное значение будет иное
 * @param bool выводить описание поля или нет
 * @return string
 */
function nc_string_field($field_name, $style = "", $classID = "", $caption = false, $value = '', $valid = false, $caption_style = null, $protect = false)
{
    // для получения значения поля
    global $fldValue, $fldID, $systemTableID;
    $nc_core = nc_Core::get_object();
    // текущее значение компонента
    if (!$classID) {
        $classID = $nc_core->sub_class->get_current('Class_ID');
    }
    $sysTable = $systemTableID ? $systemTableID : $nc_core->component->get_by_id($classID, 'System_Table_ID');
    $show_field_errors = $classID == $nc_core->sub_class->get_current('Class_ID');
    $component = new nc_Component($classID, $sysTable);
    $fields = $component->get_fields(NC_FIELDTYPE_STRING);
    // поиск поля
    $field = 0;
    $strAdd = "";
    foreach ($fields as $v) {
        $format_string = nc_field_parse_format($v['format'], NC_FIELDTYPE_STRING);
        if (isset($format_string['transliteration_field']) && $format_string['transliteration_field'] == $field_name) {
            $strAdd .= "data-type='transliterate' data-from='f_" . $v['name'] . "' " . (!empty($format_string['use_url_rules']) ? "data-is-url='yes'" : "");
        }
        if ($v['name'] == $field_name) {
            $field = $v;
        }
    }
    // поля не существует
    if (!$field) {
        if ($show_field_errors) {
            trigger_error("<b>nc_string_field()</b>: Incorrect field name (" . $field_name . ")", E_USER_WARNING);
        }
        return false;
    }
    // поле не доступно для редактирования
    if ($field['edit_type'] == 3 || $field['edit_type'] == 2 && !nc_field_check_admin_perm()) {
        return false;
    }
    // значение поля
    if (!$value && is_array($fldID)) {
        $t = array_flip($fldID);
        $value = $fldValue[$t[$field['id']]];
    }
    // вывод функции
    $result = '';
    # вывод Caption, если нужно
    if ($caption) {
        $result .= nc_field_caption($field, $caption_style);
    }
    if ($valid) {
        $result = "<span id='nc_field_{$fldID}'>{$result}</span>";
    }
    if ($value == NULL) {
        if ($field['format'] == 'url') {
            $value = isURL($field['default']) ? $field['default'] : "http://";
        } elseif ($field['default']) {
            $value = $field['default'];
        }
    }
    # формат поля
    $inputType = $field['format'] == 'password' ? 'password' : 'text';
    //echo $field['format'];
    # проверим, есть ли в параметре "style", атрибуты
    $style_attr = nc_reg_search_html_attr($style);
    # прописываем параметры из $style
    $style_opt = "";
    if (!in_array("maxlength", $style_attr)) {
        $style_opt .= "maxlength='255'";
    }
    if (!in_array("size", $style_attr)) {
        $style_opt .= ($style_opt ? " " : "") . "size='50'";
    }
    if (!in_array("type", $style_attr)) {
        $style_opt .= ($style_opt ? " " : "") . "type='" . $inputType . "'";
    }
    if ($style_opt) {
        $style_opt = " " . $style_opt;
    }
    $result .= "<input name='f_" . $field_name . "'" . $style_opt . ($style ? " " . $style : "") . " value='" . htmlspecialchars($value, ENT_QUOTES) . "' " . $strAdd . " />";
    //$result .= nc_field_validation('input', 'f_'.$field_name, $field['id'], 'string', $field['not_null'], $field['format']);
    if ($protect) {
        $result = json_encode($result);
        $html = "<div id='protect_{$field_name}'></div>";
        $html .= "<script type='text/javascript'>\n            var new_div = document.createElement('div');\n            new_div.innerHTML = {$result};\n            var protected_element = document.getElementById('protect_{$field_name}');\n            if (protected_element) {\n                protected_element.parentNode.replaceChild(new_div, protected_element);\n            }\n        </script>";
        $result = $html;
    }
    return $result;
}
Exemple #5
0
function showSearchForm($fldName, $fldType, $fldDoSearch, $fldFmt)
{
    global $systemTableID, $db, $srchPat, $nc_core;
    $result = '';
    $j = 0;
    for ($i = 0; $i < count($fldName); $i++) {
        $fld_prefix = "<div>";
        $fld_suffix = "</div>\n";
        $fldNameTempl = $fld_prefix . "" . $fldName[$i] . ": ";
        if (!$fldDoSearch[$i]) {
            continue;
        }
        switch ($fldType[$i]) {
            case 1:
                // Char
                $result .= $fldNameTempl . "<br><input type='text' name='srchPat[" . $j . "]' size='50' maxlength='255' value='" . htmlspecialchars(stripcslashes($srchPat[$j]), ENT_QUOTES) . "'>" . $fld_suffix;
                $j++;
                break;
            case 3:
                // Text
                $result .= $fldNameTempl . "<br><input type='text' name='srchPat[" . $j . "]' size='50' maxlength='255' value='" . htmlspecialchars(stripcslashes($srchPat[$j]), ENT_QUOTES) . "'>" . $fld_suffix;
                $j++;
                break;
            case 6:
                // File
                $result .= $fldNameTempl . "<br><input type='text' name='srchPat[" . $j . "]' size='50' maxlength='255' value='" . htmlspecialchars(stripcslashes($srchPat[$j]), ENT_QUOTES) . "'>" . $fld_suffix;
                $j++;
                break;
            case 2:
                // Int
                $result .= $fldNameTempl . "&nbsp;&nbsp;" . NETCAT_MODERATION_MOD_FROM . " <input type='text' name='srchPat[" . $j . "]' size='10' maxlength='16' value='" . ($srchPat[$j] ? (int) $srchPat[$j] : "") . "'>";
                $j++;
                $result .= NETCAT_MODERATION_MOD_DON . "<input type='text' name='srchPat[" . $j . "]' size='10' maxlength='16' value='" . ($srchPat[$j] ? (int) $srchPat[$j] : "") . "'>" . $fld_suffix;
                $j++;
                break;
            case 7:
                // Float
                $result .= $fldNameTempl . "&nbsp;&nbsp;" . NETCAT_MODERATION_MOD_FROM . " <input type='text' name='srchPat[" . $j . "]' size='10' maxlength='16' value='" . ($srchPat[$j] ? (double) $srchPat[$j] : "") . "'>";
                $j++;
                $result .= NETCAT_MODERATION_MOD_DON . "<input name='srchPat[" . $j . "]' type='text' size='10' maxlength='16' value='" . ($srchPat[$j] ? (double) $srchPat[$j] : "") . "'>" . $fld_suffix;
                $j++;
                break;
            case 4:
                // List
                if ($fldFmt[$i]) {
                    $result .= $fldNameTempl . "<br><select name='srchPat[" . $j . "]' size='1'>";
                    $result .= "<option value=''>" . NETCAT_MODERATION_MODA . "</option>";
                    $list_format = explode(":", $fldFmt[$i]);
                    $fldFmt[$i] = $list_format[0];
                    //название таблицы
                    $SortType = $SortDirection = 0;
                    $res = $db->get_row("SELECT `Sort_Type`, `Sort_Direction` FROM `Classificator` WHERE `Table_Name` = '" . $db->escape($fldFmt[$i]) . "'", ARRAY_N);
                    if ($db->num_rows != 0) {
                        $row = $res;
                        $SortType = $row[0];
                        $SortDirection = $row[1];
                    }
                    $s = "SELECT * FROM `Classificator_" . $db->escape($fldFmt[$i]) . "` ORDER BY ";
                    switch ($SortType) {
                        case 1:
                            $s .= "`" . $db->escape($fldFmt[$i]) . "_Name`";
                            break;
                        case 2:
                            $s .= "`" . $db->escape($fldFmt[$i]) . "_Priority`";
                            break;
                        default:
                            $s .= "`" . $db->escape($fldFmt[$i]) . "_ID`";
                    }
                    if ($SortDirection == 1) {
                        $s .= " DESC";
                    }
                    $selected = (int) $srchPat[$j];
                    $lstRes = (array) $db->get_results($s, ARRAY_N);
                    foreach ($lstRes as $q) {
                        list($lstID, $lstName) = $q;
                        $result .= "<option value='" . $lstID . "'" . ($selected == $lstID ? "selected" : "") . ">" . $lstName . "</option>";
                    }
                    $result .= '</select>' . $fld_suffix;
                }
                $j++;
                break;
            case 5:
                // Bool
                $result .= $fldNameTempl;
                $result .= "&nbsp;&nbsp;<input type='radio' name='srchPat[" . $j . "]' id='t" . $j . "_1' value='' style='vertical-align:middle'" . (!$srchPat[$j] ? " checked" : "") . "><label for='t" . $j . "_1'>" . NETCAT_MODERATION_MOD_NOANSWER . '</label> ';
                $result .= "&nbsp;&nbsp;<input type='radio' name='srchPat[" . $j . "]' id='t" . $j . "_2' value='1' style='vertical-align:middle'" . ($srchPat[$j] == '1' ? " checked" : "") . "><label for='t" . $j . "_2'>" . CONTROL_CONTENT_SUBDIVISION_FUNCS_OBJ_YES . '</label> ';
                $result .= "&nbsp;&nbsp;<input type='radio' name='srchPat[" . $j . "]' id='t" . $j . "_3' value='0' style='vertical-align:middle'" . ($srchPat[$j] == '0' ? " checked" : "") . "><label for='t" . $j . "_3'>" . CONTROL_CONTENT_SUBDIVISION_FUNCS_OBJ_NO . '</label>';
                $result .= $fld_suffix;
                $j++;
                break;
            case 8:
                // DateTime
                $format = nc_field_parse_format($fldFmt[$i], 8);
                $result .= $fldNameTempl . "&nbsp;&nbsp;";
                if ($format['calendar']) {
                    $result .= nc_set_calendar(0) . "<br/>";
                }
                $result .= NETCAT_MODERATION_MOD_FROM;
                if ($format['type'] != 'event_time') {
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='2' maxlength='2' value='" . ($srchPat[$j] ? sprintf("%02d", $srchPat[$j]) : "") . "'>.";
                    $j++;
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='2' maxlength='2' value='" . ($srchPat[$j] ? sprintf("%02d", $srchPat[$j]) : "") . "'>.";
                    $j++;
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='4' maxlength='4' value='" . ($srchPat[$j] ? sprintf("%04d", $srchPat[$j]) : "") . "'> ";
                    $j++;
                } else {
                    $j += 3;
                }
                if ($format['type'] != 'event_date') {
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='2' maxlength='2' value='" . ($srchPat[$j] ? sprintf("%02d", $srchPat[$j]) : "") . "'>:";
                    $j++;
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='2' maxlength='2' value='" . ($srchPat[$j] ? sprintf("%02d", $srchPat[$j]) : "") . "'>:";
                    $j++;
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='2' maxlength='2' value='" . ($srchPat[$j] ? sprintf("%02d", $srchPat[$j]) : "") . "'> ";
                    $j++;
                } else {
                    $j += 3;
                }
                if ($format['calendar'] && $format['type'] != 'event_time') {
                    $result .= "<div style='display: inline; position: relative;'>\n                         <img  id='nc_calendar_popup_img_srchPat[" . ($j - 6) . "]' onclick=\\\"nc_calendar_popup('srchPat[" . ($j - 6) . "]', 'srchPat[" . ($j - 5) . "]', 'srchPat[" . ($j - 4) . "]', '0');\\\" src='" . $nc_core->SUB_FOLDER . $nc_core->HTTP_ROOT_PATH . "modules/calendar/images/calendar.jpg' style='cursor: pointer; position: absolute; left: 7px; top: -3px;'/>\n                       </div>\n                       <div style='display: none; z-index: 10000;' id='nc_calendar_popup_srchPat[" . ($j - 6) . "]'></div><br/>";
                }
                $result .= NETCAT_MODERATION_MOD_DON;
                if ($format['type'] != 'event_time') {
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='2' maxlength='2' value='" . ($srchPat[$j] ? sprintf("%02d", $srchPat[$j]) : "") . "'>.";
                    $j++;
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='2' maxlength='2' value='" . ($srchPat[$j] ? sprintf("%02d", $srchPat[$j]) : "") . "'>.";
                    $j++;
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='4' maxlength='4' value='" . ($srchPat[$j] ? sprintf("%04d", $srchPat[$j]) : "") . "'> ";
                    $j++;
                } else {
                    $j += 3;
                }
                if ($format['type'] != 'event_date') {
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='2' maxlength='2' value='" . ($srchPat[$j] ? sprintf("%02d", $srchPat[$j]) : "") . "'>:";
                    $j++;
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='2' maxlength='2' value='" . ($srchPat[$j] ? sprintf("%02d", $srchPat[$j]) : "") . "'>:";
                    $j++;
                    $result .= "<input type='text' class='no_special_style' name='srchPat[" . $j . "]' size='2' maxlength='2' value='" . ($srchPat[$j] ? sprintf("%02d", $srchPat[$j]) : "") . "'> ";
                    $j++;
                } else {
                    $j += 3;
                }
                if ($format['calendar'] && $format['type'] != 'event_time') {
                    $result .= "<div style='display: inline; position: relative;'>\n                         <img  id='nc_calendar_popup_img_srchPat[" . ($j - 6) . "]' onclick=\\\"nc_calendar_popup('srchPat[" . ($j - 6) . "]', 'srchPat[" . ($j - 5) . "]', 'srchPat[" . ($j - 4) . "]', '0');\\\" src='" . $nc_core->SUB_FOLDER . $nc_core->HTTP_ROOT_PATH . "modules/calendar/images/calendar.jpg' style='cursor: pointer; position: absolute; left: 7px; top: -3px;'/>\n                       </div>\n                       <div style='display: none; z-index: 10000;' id='nc_calendar_popup_srchPat[" . ($j - 6) . "]'></div><br/>";
                }
                $result .= $fld_suffix;
                break;
            case 10:
                //Multi List
                if ($fldFmt[$i]) {
                    list($clft_name, $type_element, $type_size) = explode(":", $fldFmt[$i]);
                    if (!$type_element) {
                        $type_element = "select";
                    }
                    if (!$type_size) {
                        $type_size = 3;
                    }
                    $fldFmt[$i] = $clft_name;
                    $SortType = $SortDirection = 0;
                    $res = $db->get_row("SELECT `Sort_Type`, `Sort_Direction` FROM `Classificator` WHERE `Table_Name` = '" . $db->escape($fldFmt[$i]) . "'", ARRAY_N);
                    if ($db->num_rows != 0) {
                        $row = $res;
                        $SortType = $row[0];
                        $SortDirection = $row[1];
                    }
                    $s = "SELECT * FROM Classificator_" . $fldFmt[$i] . " ORDER BY ";
                    switch ($SortType) {
                        case 1:
                            $s .= $fldFmt[$i] . "_Name";
                            break;
                        case 2:
                            $s .= $fldFmt[$i] . "_Priority";
                            break;
                        default:
                            $s .= $fldFmt[$i] . "_ID";
                    }
                    if ($SortDirection == 1) {
                        $s .= " DESC";
                    }
                    $selected = (int) $srchPat[$j];
                    $lstRes = (array) $db->get_results($s, ARRAY_N);
                    $result .= $fldNameTempl . "<br>";
                    if ($type_element == 'select') {
                        $result .= "<select name='srchPat[" . $j . "][]' size='" . $type_size . "' multiple>";
                        $result .= "<option value=''>" . NETCAT_MODERATION_MODA . "</option>";
                    }
                    foreach ($lstRes as $q) {
                        list($lstID, $lstName) = $q;
                        $temp_str = '';
                        if ($lstID == $selected) {
                            $temp_str = $type_element == "select" ? " selected" : " checked";
                        }
                        if ($type_element == 'select') {
                            #TODO сделать возможность передавать селектед в виде массива
                            $result .= "<option value='" . $lstID . "' " . $temp_str . ">" . $lstName . "</option>";
                        } else {
                            $result .= "<input type='checkbox' value='" . $lstID . "' name='srchPat[" . $j . "][]' " . $temp_str . "> " . $lstName . "<br>\r\n";
                        }
                    }
                    if ($type_element == 'select') {
                        $result .= '</select><br>';
                    }
                    //.$fld_suffix;
                    $j++;
                    $result .= "<input type='hidden' name='srchPat[" . $j . "]' value='0'>\n";
                    $result .= $fld_suffix;
                }
                $j++;
                break;
        }
        $result .= "<br>\n";
    }
    if (!$j) {
        return false;
    }
    return $result;
}
Exemple #6
0
 /**
  * Возвращает имя поля с типа дата с форматом event или event_date,
  * если таковое существует, или false
  */
 public function get_date_field()
 {
     $key = $this->_class_id . "-" . $this->_system_table_id;
     if (!isset(self::$event_fields[$key])) {
         self::$event_fields[$key] = false;
         foreach ($this->get_fields() as $field) {
             if ($field['type'] != NC_FIELDTYPE_DATETIME) {
                 continue;
             }
             $format = nc_field_parse_format($field['format'], NC_FIELDTYPE_DATETIME);
             if ($format['type'] == 'event' || $format['type'] == 'event_date') {
                 self::$event_fields[$key] = $field['name'];
                 break;
             }
         }
     }
     return self::$event_fields[$key];
 }
Exemple #7
0
 /**
  *
  * @param string|int $class_id - ID компонента или название системной таблицы(User|Catalogue|Subdivision|Template)
  * @param string|int $field - название или ID поля в которое сохранять
  * @param int $message_id - ID объекта|пользователя|сайта|раздела|макета
  * @param array $file - массив с данными о файле из $_FILES либо
  *      path          — путь к файлу(/netcat/tmp/foto.jpg) или ссылка(http://example.com/foto.jpg)
  *      type          — mime-тип, попытается определить автоматически если не задан, по умолчанию image/jpeg
  *      name          — имя файла, возьмется из ссылки если не задано
  *      folder        — нестандартная папка в которую сохранить файл, только для стандартной ФС
  * @param bool $no еdit           - игнорировать настройки поля изменяющие файл
  * @param bool $message_put - режим работы внутри системы
  * @return array
  *      download_path — ссылка для скачивания под оригинальным именем (ссылка с "h_")
  *      url           — путь к файлу от корня сайта
  *      preview_url   — путь к превью файла от корня сайта
  *      name          — изначальное имя файла
  *      size          — размер
  *      type          — mime-тип
  */
 public function field_save_file($class_id, $field, $message_id, $file, $noеdit = false, $message_put = false)
 {
     $DOCUMENT_ROOT = nc_core('DOCUMENT_ROOT');
     $FILES_FOLDER = nc_core('FILES_FOLDER');
     $files_http_path = nc_core('SUB_FOLDER') . nc_core('HTTP_FILES_PATH');
     $db = nc_core('db');
     $message_id = intval($message_id);
     $component = new nc_Component($class_id);
     $systemTableID = $component->get_system_table_id();
     $systemTableName = $systemTableID ? $class_id : '';
     $fields = $component->get_fields(NC_FIELDTYPE_FILE);
     if (!empty($fields)) {
         foreach ($fields as $v) {
             if ($v['id'] == $field || $v['name'] == $field) {
                 $rawformat = $v['format'];
                 $field_id = $v['id'];
                 $field_name = $v['name'];
             }
         }
     } else {
         return null;
         //wrong class or field
     }
     if (!$systemTableID) {
         $msg = $db->get_row("SELECT `Sub_Class_ID`, `Subdivision_ID` FROM `Message{$class_id}` WHERE `Message_ID` = '{$message_id}'", ARRAY_A);
     } else {
         $msg = $db->get_row("SELECT COUNT(*) FROM `{$systemTableName}` WHERE `{$systemTableName}_ID` = {$message_id}", ARRAY_A);
     }
     if (empty($msg)) {
         return null;
         //wrong message
     }
     $result = array();
     #delete old file
     require_once $this->core->INCLUDE_FOLDER . "s_files.inc.php";
     DeleteFile($field_id, $field_name, $class_id, $systemTableName, $message_id);
     $format = nc_field_parse_format($rawformat, NC_FIELDTYPE_FILE);
     $fileurl = $file['path'];
     $filesrc = $file['tmp_name'];
     if (!$fileurl && !$filesrc) {
         return null;
         //no file to save
     }
     if (!$filesrc && $fileurl && !(preg_match("~^[^=]+://~", $fileurl) && ($buf = @file_get_contents($fileurl))) && !file_exists($DOCUMENT_ROOT . $fileurl)) {
         //и по внутренней нет
         return null;
     }
     $filename = $file['name'] ? $file['name'] : substr($fileurl, strrpos($fileurl, '/') + 1);
     $filename = str_replace(array('<', '>'), '_', $filename);
     $filetype = $file['type'];
     $filesize = $file['size'];
     $folder = trim($file['folder'], '/');
     // расширение файла
     $ext = substr($filename, strrpos($filename, "."));
     if (!$systemTableID) {
         $File_Path = $msg['Subdivision_ID'] . "/" . $msg['Sub_Class_ID'] . "/";
     } elseif ($systemTableID == 1) {
         $File_Path = "c/";
     } elseif ($systemTableID == 3) {
         $File_Path = "u/";
     } elseif ($systemTableID == 4) {
         $File_Path = "t/";
     } else {
         $File_Path = $message_id ? $message_id . "/" : "";
         //sic! why eval?
         $File_PathNew = "\$message/";
     }
     // будущее имя файла на диске + путь
     switch ($format['fs']) {
         case NC_FS_PROTECTED:
             // hash
             // имя файла
             $put_file_name = md5($filename . date("H:i:s d.m.Y") . uniqid("netcat"));
             break;
         case NC_FS_ORIGINAL:
             // пользователь сам указал папку
             if ($folder && preg_match("/^[a-z][a-z0-9\\/]+\$/is", $folder)) {
                 $File_Path = $folder . "/";
             }
             // сгенерировать имя файла
             $put_file_name = nc_get_filename_for_original_fs($filename, $FILES_FOLDER . $File_Path);
             $db_string_path = ":" . ($File_PathNew ? $File_PathNew : $File_Path) . $put_file_name;
             break;
         case NC_FS_SIMPLE:
             // FieldID_MessageID.ext
             $File_Path = '';
             // в папку netcat_files
             //sic! why eval?
             $put_file_name = $field_id . ($message_put ? '_$message' : "_" . $message_id) . $ext;
             break;
     }
     $this->create_dir($FILES_FOLDER . $File_Path);
     //для простой ФС нужно скопировать временный файл
     //он будет обрабатываться и после добавления объекта переименован в FieldID_MessageID.ext
     //при добавлении объекта или раздела пока неизвестен путь, поэтому файл попадет в папку netcat_files и потом перенесен
     $save_mame = $format['fs'] == NC_FS_SIMPLE && $message_put ? $filesrc : $put_file_name;
     $save_path = $FILES_FOLDER . $File_Path . $save_mame;
     $save_path_preview = $FILES_FOLDER . $File_Path . 'preview_' . $save_mame;
     if ($filesrc) {
         @move_uploaded_file($filesrc, $save_path);
     } else {
         if ($buf) {
             @file_put_contents($save_path, $buf);
         } else {
             @copy($DOCUMENT_ROOT . $fileurl, $save_path);
         }
     }
     $resize_format = nc_field_parse_resize_options($rawformat);
     require_once $this->core->INCLUDE_FOLDER . "classes/nc_imagetransform.class.php";
     if (!$noеdit) {
         if ($resize_format['use_preview']) {
             @nc_ImageTransform::imgResize($save_path, $save_path_preview, $resize_format['preview_width'], $resize_format['preview_height']);
         }
         if ($resize_format['use_resize']) {
             @nc_ImageTransform::imgResize($save_path, $save_path, $resize_format['resize_width'], $resize_format['resize_height']);
             $filesize = filesize($save_path);
         }
         if ($resize_format['use_crop']) {
             @nc_ImageTransform::imgCrop($save_path, $save_path, $resize_format['crop_x0'], $resize_format['crop_y0'], $resize_format['crop_x1'], $resize_format['crop_y1'], NULL, 90, 0, 0, $resize_format['crop_ignore'] ? $resize_format['crop_ignore_width'] : 0, $resize_format['crop_ignore'] ? $resize_format['crop_ignore_height'] : 0);
             $filesize = filesize($save_path);
         }
     }
     $filesize = $filesize ? $filesize : filesize($save_path);
     $filetype = $filetype ? $filetype : ($filetype = $this->_guess_content_type($save_path) ? $filetype : "image/jpeg");
     // для защищенной надо записать файл в базу
     if ($format['fs'] == NC_FS_PROTECTED) {
         $query = $db->query("INSERT INTO `Filetable`\n                            (`Real_Name`, `File_Path`, `Virt_Name`, `File_Type`, `File_Size`, `Field_ID`, `Content_Disposition`, `Message_ID`)\n                     VALUES ('" . $db->escape($filename) . "', '/" . $db->escape($File_Path) . "', '" . $db->escape($put_file_name) . "', '" . $db->escape($filetype) . "',\n                            '" . intval($filesize) . "', '" . intval($field_id) . "', '" . intval($format['disposition']) . "', '" . $message_id . "')");
         if ($query) {
             $filetable_lastid = $db->insert_id;
             $result['download_path'] = $files_http_path . $File_Path . 'h_' . $put_file_name;
         }
     }
     $db_string = $filename . ":" . $filetype . ":" . $filesize . $db_string_path;
     $result['url'] = $files_http_path . $File_Path . $put_file_name;
     $result['preview_url'] = $resize_format['use_preview'] ? $files_http_path . $File_Path . 'preview_' . $put_file_name : "";
     $result['name'] = $filename;
     $result['size'] = $filesize;
     $result['type'] = $filetype;
     if (!$message_put) {
         //запишем в объект сущности
         $query = $db->query("UPDATE `" . ($systemTableID ? $systemTableName : "Message" . $class_id) . "`\n                                    SET `{$field_name}` = '" . $db->escape($db_string) . "'\n                                        WHERE `" . ($systemTableID ? $systemTableName : "Message") . "_ID` = {$message_id}");
     } else {
         //данные для использования в скриптах добавления/изменения после message_put.php
         $result['FileFS'] = $format['fs'];
         $result['tmpNewFile'] = $put_file_name;
         $result['File_Path'] = $File_Path;
         $result['File_PathNew'] = $File_PathNew;
         $result['filetable_lastid'] = $filetable_lastid;
         $result['fldValue'] = $db_string;
     }
     return $result;
 }
Exemple #8
0
/**
 * Функция копирует один файл из первого поля во второй
 * в пределах одного объекта
 * новый файл будет в ФС, которая задана в формате поле-приемника
 *
 * @param int message - id объекта
 * @param int field_src - id поля источника
 * @param int field_dst - id поля приемниеп
 * @param int classID (оппоционально) id компонента
 *
 * @todo Реализовать копирование файлов системных таблиц
 * @todo Реализовать копирование файлов различных объектов (возможно, из разных компонентов)
 * @return bool
 */
function nc_copy_filefield($message, $field_src, $field_dst, $classID = 0)
{
    global $nc_core;
    // Если не задан класс, то вытащим его из базы
    if (!$classID) {
        $classID = $nc_core->db->get_var("SELECT `Class_ID` FROM `Field` WHERE  `Field_ID` = '" . intval($field_src) . "'");
    }
    // проверка аргументов
    $message += 0;
    $field_src += 0;
    $field_dst += 0;
    $classID += 0;
    if (!$message || !$field_src || !$field_dst || !$classID) {
        return 0;
    }
    # поиск исходного файла
    // латинское имя поля
    $field_name_src = $nc_core->db->get_var("SELECT `Field_Name` FROM `Field` WHERE `Field_ID` = '" . $field_src . "'");
    if (!$field_name_src) {
        return 0;
    }
    // Значение поля в таблице объектов
    $message_field = $nc_core->db->get_row("SELECT * FROM `Message" . $classID . "` WHERE  `Message_ID` = '" . $message . "'", ARRAY_A);
    $file_data = explode(':', $message_field[$field_name_src]);
    $file_name = $file_data[0];
    $file_type = $file_data[1];
    $file_size = $file_data[2];
    $ext = substr($file_name, strrpos($file_name, "."));
    // расширение файла
    // если ли файл в Filetable ?
    $filetable = $nc_core->db->get_row("SELECT * FROM `Filetable`\n                                          WHERE `Message_ID` = '" . intval($message) . "' AND `Field_ID` = '" . intval($field_src) . "'", ARRAY_A);
    // определения полного пути к файлу
    if ($filetable) {
        // исходный файл в protected
        $path_src = rtrim($nc_core->FILES_FOLDER, '/') . $filetable['File_Path'] . $filetable['Virt_Name'];
    } else {
        if ($file_data[3]) {
            // orignal
            $path_src = $nc_core->FILES_FOLDER . $file_data[3];
        } else {
            // simple
            $path_src = $nc_core->FILES_FOLDER . $field_src . "_" . $message . $ext;
        }
    }
    # копирование
    // получение информации о поле-приемника
    $field_info_desc = $nc_core->db->get_row("SELECT `Field_Name`, `Format` FROM `Field` WHERE `Field_ID` = '" . $field_dst . "'", ARRAY_A);
    if (!$field_info_desc) {
        return 0;
    }
    //удаление старого файла
    require_once $nc_core->INCLUDE_FOLDER . "s_files.inc.php";
    DeleteFile($field_dst, $field_info_desc['Field_Name'], $classID, 0, $message);
    // определение типа фс применика
    $fs = nc_field_parse_format($field_info_desc['Format'], NC_FIELDTYPE_FILE);
    $fs = $fs['fs'];
    // определние имени файла на диске и диретории
    $in_db = $file_name . ":" . $file_type . ":" . $file_size;
    // то, что запишится в БД
    switch ($fs) {
        case NC_FS_PROTECTED:
            $path_dsc = $message_field['Subdivision_ID'] . '/' . $message_field['Sub_Class_ID'] . '/';
            $name_dsc = md5($file_name . date("H:i:s d.m.Y") . uniqid("netcat"));
            $nc_core->db->query("INSERT INTO `Filetable`(Real_Name, Virt_Name, File_Path, File_Type, File_Size, Message_ID, Field_ID)\n                           VALUES('" . $file_name . "', '" . $name_dsc . "', '/" . $path_dsc . "','" . $file_type . "', '" . $file_size . "', '" . $message . "', '" . $field_dst . "')");
            break;
        case NC_FS_ORIGINAL:
            $path_dsc = $message_field['Subdivision_ID'] . '/' . $message_field['Sub_Class_ID'] . '/';
            $name_dsc = nc_get_filename_for_original_fs($file_name, $nc_core->FILES_FOLDER . $path_dsc);
            $in_db .= ":" . $path_dsc . $name_dsc;
            break;
        case NC_FS_SIMPLE:
            $path_dsc = '';
            $name_dsc = $field_dst . "_" . $message . $ext;
            break;
    }
    // обновление инфы в БД
    $nc_core->db->query("UPDATE `Message" . $classID . "` SET `" . $field_info_desc['Field_Name'] . "` = '" . $in_db . "' WHERE `Message_ID` = '" . $message . "'");
    print $nc_core->FILES_FOLDER . $path_dsc . $name_dsc;
    // копирование файла
    copy($path_src, $nc_core->FILES_FOLDER . $path_dsc . $name_dsc);
    return 1;
}
Exemple #9
0
         case "event_time":
             if (!(isset($_REQUEST["f_" . $fld[$i] . "_hours"]) && isset($_REQUEST["f_" . $fld[$i] . "_minutes"]) && isset($_REQUEST["f_" . $fld[$i] . "_seconds"]))) {
                 continue 2;
             }
             break;
         default:
             // В общем случае - меняем только если прислали хотя бы одно поле
             if (!(isset($_REQUEST["f_" . $fld[$i] . "_day"]) || isset($_REQUEST["f_" . $fld[$i] . "_month"]) || isset($_REQUEST["f_" . $fld[$i] . "_year"]) || isset($_REQUEST["f_" . $fld[$i] . "_hours"]) || isset($_REQUEST["f_" . $fld[$i] . "_minutes"]) || isset($_REQUEST["f_" . $fld[$i] . "_seconds"]))) {
                 continue 2;
             }
             break;
     }
 }
 if ($fldType[$i] == NC_FIELDTYPE_STRING || $fldType[$i] == NC_FIELDTYPE_TEXT || $fldType[$i] == NC_FIELDTYPE_DATETIME || $fldType[$i] == NC_FIELDTYPE_MULTISELECT) {
     if (NC_FIELDTYPE_TEXT == $fldType[$i]) {
         $format = nc_field_parse_format($fldFmt[$i], NC_FIELDTYPE_TEXT);
     }
     //транслитерация
     if (NC_FIELDTYPE_STRING == $fldType[$i]) {
         //транслитерируем только, если пользователь сам не ввел значение поля, чтобы позволить ему вводить свои собственные
         if ($format_string[$i]['use_transliteration'] == 1 && empty($_REQUEST['f_' . $format_string[$i]['transliteration_field']])) {
             $fieldValue = nc_transliterate($fldValue[$i], $format_string[$i]['use_url_rules'] == 1 ? true : false);
             if ($format_string[$i]['transliteration_field'] == 'Keyword') {
                 $fieldValue = nc_check_keyword_name($message, $fieldValue, $classID);
             }
             $updateString .= "`" . $format_string[$i]['transliteration_field'] . "` = \"" . $fieldValue . "\", ";
             ${$format_string[$i]['transliteration_field'] . 'Defined'} = true;
             ${$format_string[$i]['transliteration_field'] . 'NewValue'} = "\"" . $fieldValue . "\"";
         }
     }
     $fldValue[$i] = str_replace("\\'", "'", addslashes($fldValue[$i]));
Exemple #10
0
/**
 * Show form to edit field or create new
 *
 * @param int Field id, 0 - if new
 * @param int ClassId or SystemTableId, if 0 - edit field
 * @param bool is field in system table
 * @param string action
 * @param string form name
 * @param string form id
 * @param string Advanced elements
 * @return bool true
 */
function FieldForm($FieldID, $Id, $isSys = 0, $action = "index.php", $FormName = '', $FormID = '', $Additional = '', $isWidget = 0)
{
    global $db, $nc_core;
    global $UI_CONFIG;
    global $field_type_name, $type_of_edit_name;
    $FieldID = intval($FieldID);
    $Id = intval($Id);
    $no_multifile = false;
    if ($isSys) {
        if (!$Id && $FieldID) {
            $sql = "SELECT `System_Table_ID` FROM `Field` WHERE `Field_ID` = {$FieldID}";
            $systemTableId = $db->get_var($sql);
            $no_multifile = $systemTableId != 3;
        } else {
            if ($Id != 3) {
                $no_multifile = true;
            }
        }
    }
    if ($FieldID) {
        $Array = $db->get_row("SELECT `Field_Name`, `Description`, `TypeOfData_ID`, `Format`, `Extension`, `NotNull`, `Priority`, `DoSearch`,\n      `Inheritance`, `DefaultState`, `TypeOfEdit_ID`, `Widget_Class_ID`, `InTableView`\n      FROM `Field`\n      WHERE `Field_ID`='" . $FieldID . "' AND `Checked` = 1", ARRAY_A);
        if ($Array["Widget_Class_ID"]) {
            $isWidget = 1;
        }
    } else {
        $Array = $_POST;
        $where = $isSys ? "`System_Table_ID`" : ($isWidget ? "`Widget_Class_ID`" : "`Class_ID`");
        $where .= "='" . $Id . "'";
        if (!$Array["Priority"]) {
            $res = $db->get_var("SELECT (Priority+1) FROM `Field` WHERE " . $where . " ORDER BY `Priority` DESC LIMIT 1");
            if (!is_null($res)) {
                $Array["Priority"] = $res;
            }
        }
    }
    // js для визульного заполнения "Формата"
    $js = "<script type='text/javascript' language='JavaScript'>\n    " . ($Array["TypeOfData_ID"] || 1 ? "nc_field_additional_format(" . intval($Array["TypeOfData_ID"] ? $Array["TypeOfData_ID"] : 1) . ");" : "") . "\n\n    function nc_field_additional_format(selected_field) {\n\n     //settings for text\n     document.getElementById('div_upload_limits').style.display = ((selected_field == 6 || selected_field == 11 ) ? 'block' : 'none');\n\n    // select FS for file field\n     document.getElementById('div_field_file').style.display = ((selected_field == 6) ? 'block' : 'none');\n\n     //don't show Format field\n     document.getElementById('div_format').style.display = ((selected_field == 3 || selected_field == 1) ? 'none' : 'block');\n\n     //settings for text\n     document.getElementById('div_field_text').style.display = ((selected_field == 3 ) ? 'block' : 'none');\n\n    //settings for string\n     document.getElementById('div_field_string').style.display = ((selected_field == 1 ) ? 'block' : 'none');\n\n     //settings for date\n     document.getElementById('div_field_date').style.display = ((selected_field == 8 ) ? 'block' : 'none');\n\n    document.getElementById('div_file_resize').style.display = ((selected_field == 11 || selected_field == 6) ? 'block' : 'none');";
    if (!$isSys) {
        $js .= "//settings for search\n\t\tdocument.getElementById('dosr').disabled = ((selected_field == 9 || selected_field == 11) ? true : false);\n\t\tdocument.getElementById('dosr').style.background = ( (selected_field == 9 || selected_field == 11) ? '#eee' : '' );";
    }
    $js .= "// default value field\n     var defaultField = document.getElementById('DefaultState');\n\n    if (defaultField) {\n         // default value field disabled\n         defaultField.disabled = ( (selected_field == 11 || selected_field==3 || selected_field==6 || selected_field==8 || selected_field==10) ? true : false );\n         defaultField.style.background = ( (selected_field == 11 || selected_field==3 || selected_field==6 || selected_field==8) ? '#eee' : '' );\n\n         // default value field data\n         defaultField.value = (selected_field==" . intval($Array["TypeOfData_ID"]) . " ? '" . $db->escape($Array["DefaultState"]) . "' : '');\n    }\n     return false;\n    }\n\n    function nc_select_field() {\n     var selected_field = document.getElementById('TypeOfData_ID').selectedIndex + 1 ;\n     nc_field_additional_format (selected_field);\n     nc_field_select_fs();\n     return false;\n    }\n\n    function nc_field_select_fs() {\n      var selected_fs = document.getElementById('Format_FS').selectedIndex + 1;\n      document.getElementById('attachment').disabled = ( selected_fs != 3 );\n      document.getElementById('download').disabled = ( selected_fs != 3 );\n      return false;\n    }\n\n    function nc_field_select_string_format() {\n        document.getElementById('div_field_string_protect_email').style.display = document.getElementById('Format_String').value == 'email' ? 'block' : 'none';\n    }\n\n    function nc_field_select_fck(element) {\n        var \$this = \$nc(element);\n        var \$panel_block = \$nc('#format-panel-block');\n        if (\$this.val() == 2) {\n            \$panel_block.hide();\n        } else {\n            \$panel_block.show();\n        }\n    }\n    function nc_field_select_transliteration(element) {\n        \$nc('#transliteration_field').change(function() {\n          if (\$nc('#transliteration_field').val() == 'Keyword') {\n            \$nc('#use_url_rules').prop('checked', true);\n          }\n        });\n        var \$this = \$nc(element);\n        var \$panel_block = \$nc('#transliteration-fields-panel-block');\n        if (\$this.is(':checked')) {\n            \$panel_block.show();\n            if (\$nc('#transliteration_field').val() == 'Keyword') {\n              \$nc('#use_url_rules').prop('checked', true);\n            }\n        } else {\n            \$panel_block.hide();\n        }\n    }\n    nc_field_select_fs();\n    nc_field_select_string_format();\n  </script>\n";
    print "<fieldset>";
    if ($FieldID) {
        print "<legend>" . ($Array["Description"] ? $Array["Description"] : $Array["Field_Name"]) . "</legend>";
    }
    print "<br/><form method='post' action='" . $action . "' name='" . $FormName . "' id='" . $FormID . "'>";
    $Format_FS = NC_FS_PROTECTED;
    // тип по ФС по умолчанию
    $format_text = nc_field_parse_format("", NC_FIELDTYPE_TEXT);
    // для textarea значения по умолчанию
    if ($FieldID) {
        if (!$isWidget) {
            print CONTROL_FIELD_LIST_NAMELAT . ":<br>" . nc_admin_input_simple('FieldName', $Array["Field_Name"], 50, '', "maxlength='64'") . "<br><br>";
        } else {
            print CONTROL_FIELD_LIST_NAME . ": " . $Array["Field_Name"] . "<br><br>";
        }
        switch ($Array['TypeOfData_ID']) {
            case NC_FIELDTYPE_FILE:
                // определим тип ФС
                $format_file_resize = nc_field_parse_resize_options($Array['Format']);
                $Array['Format'] = array_shift(explode(';', $Array['Format']));
                $format_file = nc_field_parse_format($Array['Format'], $Array['TypeOfData_ID']);
                $Format_FS = $format_file['fs'];
                $file_attach = $format_file['disposition'];
                // закачиваемый или нет?
                $file_download = $format_file['download'];
                $Array['Format'] = nc_preg_replace('/(:?)(fs)(\\d+)/', '', $Array['Format']);
                // уберем из Format тип ФС
                $Array['Format'] = nc_preg_replace('/(:?)(download)/', '', $Array['Format']);
                // уберем download
                $Array['Format'] = nc_preg_replace('/(:?)((attachment)|(inline))/', '', $Array['Format']);
                // уберем attachment
                break;
            case NC_FIELDTYPE_TEXT:
                $format_text = nc_field_parse_format($Array['Format'], $Array['TypeOfData_ID']);
                break;
            case NC_FIELDTYPE_DATETIME:
                $format_date = nc_field_parse_format($Array['Format'], $Array['TypeOfData_ID']);
                $Array['Format'] = $format_date['type'];
                break;
            case NC_FIELDTYPE_STRING:
                $format_string = nc_field_parse_format($Array['Format'], $Array['TypeOfData_ID']);
                $Array['Format'] = $format_string['format'];
                $Array['UseTransliteration'] = $format_string['use_transliteration'];
                $Array['TransliterationField'] = $format_string['transliteration_field'];
                $Array['UseUrlRules'] = $format_string['use_url_rules'];
                break;
            case NC_FIELDTYPE_MULTIFILE:
                $format_file_resize = nc_field_parse_resize_options($Array['Format']);
                $Array['Format'] = array_shift(explode(';', $Array['Format']));
                break;
        }
    } else {
        print CONTROL_FIELD_LIST_NAMELAT . ":<br>" . nc_admin_input_simple('FieldName', $Array["Field_Name"], 50, '', "maxlength='64'") . "<br><br>";
    }
    print CONTROL_FIELD_LIST_DESCRIPTION . ":<br>" . nc_admin_input_simple('Description', htmlspecialchars_decode($Array["Description"]), 50, '', "maxlength='64'") . "<br><br>";
    $openid_possibility = $nc_core->modules->get_by_keyword('auth') && nc_auth_openid_possibility();
    if ($FieldID && $Array['TypeOfData_ID'] == 11 && $openid_possibility) {
        print "<input name='TypeOfData_ID' value='11' type='hidden'>";
    }
    print CONTROL_FIELD_ONE_FTYPE . ":<br><select name='TypeOfData_ID' id='TypeOfData_ID' onchange='nc_select_field(); return false;'" . ($FieldID && $Array['TypeOfData_ID'] == 11 && $openid_possibility ? " disabled='disabled'" : NULL) . ">";
    //print CONTROL_FIELD_ONE_FTYPE.":<br><select name='TypeOfData_ID' id='TypeOfData_ID' onchange='nc_select_field(); return false;'>";
    for ($i = 1; $i <= count($field_type_name); $i++) {
        // Полe тиа "Связь с другими.." для системных полей не нужно
        if (($isSys || $isWidget) && $i === 9) {
            continue;
        }
        if ($i == 11 && $no_multifile) {
            continue;
        }
        print "<option " . ($Array["TypeOfData_ID"] == $i ? "selected" : "") . " value='" . $i . "'>" . $i . ": " . $field_type_name[$i] . "</option>\n";
    }
    print "</select><br><br>";
    $html = "<div id='div_format'>" . CONTROL_FIELD_ONE_FORMAT . ":<br>" . nc_admin_input_simple('Format', $Array["TypeOfData_ID"] != 3 ? $Array["Format"] : "", 50, '', "maxlength='255'") . "<br><br></div>";
    $html .= "<div id='div_field_string'>" . nc_admin_select_simple(CONTROL_FIELD_ONE_FORMAT . ":<br/>", 'Format_String', array('' => CONTROL_FIELD_ONE_FORMAT_NONE, 'email' => CONTROL_FIELD_ONE_FORMAT_EMAIL, 'url' => CONTROL_FIELD_ONE_FORMAT_URL, 'password' => CONTROL_FIELD_ONE_FORMAT_PASSWORD, 'phone' => CONTROL_FIELD_ONE_FORMAT_PHONE, 'tags' => CONTROL_FIELD_ONE_FORMAT_TAGS), $Array["Format"], "id='Format_String' onchange='nc_field_select_string_format();'") . "<br>";
    $html .= "<div id='div_field_string_protect_email'>";
    $html .= nc_admin_checkbox_simple('protect_email', '', CONTROL_FIELD_ONE_PROTECT_EMAIL, $format_string['protect_email']);
    $html .= "</div>";
    $options = GetTransliterateOptions($isSys ? "system" : ($isWidget ? "widget" : "class"), $FieldID, $Id, $systemTableId);
    if (count($options) > 0) {
        $html .= "<div id='div_field_string_use_transliteration'>";
        $html .= nc_admin_checkbox_simple('use_transliteration', '1', CONTROL_FIELD_USE_TRANSLITERATION, $Array['UseTransliteration'], '', "onchange='nc_field_select_transliteration(this); return true;'");
        $html .= "</div>";
        $html .= "<div id='transliteration-fields-panel-block' style='" . ($Array['UseTransliteration'] == 1 ? '' : 'display: none;') . "'>";
        $html .= nc_admin_select_simple(CONTROL_FIELD_TRANSLITERATION_FIELD . ":<br/>", 'transliteration_field', $options, $Array["TransliterationField"], "id='transliteration_field'", "onchange='alert('here'); return true;'") . "<br>";
        $html .= nc_admin_checkbox_simple('use_url_rules', '1', CONTROL_FIELD_USE_URL_RULES, $Array['UseUrlRules'], '');
        $html .= "</div>";
    }
    $html .= "</div>";
    // Вывод ограничений на загрузку файлов для тип поля Файл и множественный выбор файлов
    $html .= "<div id='div_upload_limits' style='display: none;'>" . CONTROL_FIELD_FILE_UPLOADS_LIMITS . "<br />\n            post_max_size (" . CONTROL_FIELD_FILE_POSTMAXSIZE . "): " . ini_get('post_max_size') . " <br />\n            upload_max_filesize (" . CONTROL_FIELD_FILE_UPLOADMAXFILESIZE . "): " . ini_get('upload_max_filesize') . "<br />\n            max_file_uploads (" . CONTROL_FIELD_FILE_MAXFILEUPLOADS . "): " . ini_get('max_file_uploads') . "<br />\n            <br /></div>";
    // расширение формата для Файлов
    $html .= "<div id='div_field_file' style='display: none;'>\r\n" . CLASSIFICATOR_TYPEOFFILESYSTEM . ":\n            <select name='Format_FS' id='Format_FS' onchange='nc_field_select_fs(); return false;' >\r\n\n               <option value='" . NC_FS_SIMPLE . "' " . (NC_FS_SIMPLE == $Format_FS ? 'selected' : '') . ">" . CONTROL_FS_NAME_SIMPLE . "</option>\r\n\n               <option value='" . NC_FS_ORIGINAL . "' " . (NC_FS_ORIGINAL == $Format_FS ? 'selected' : '') . ">" . CONTROL_FS_NAME_ORIGINAL . "</option>\r\n\n               <option value='" . NC_FS_PROTECTED . "' " . (NC_FS_PROTECTED == $Format_FS ? 'selected' : '') . ">" . CONTROL_FS_NAME_PROTECTED . "</option>\r\n\n             </select>\n             <br />" . nc_admin_checkbox_simple('attachment', '', CONTROL_FIELD_ATTACHMENT, $file_attach, '', "disabled") . "\n               <br/>" . nc_admin_checkbox_simple('download', '', CONTROL_FIELD_DOWNLOAD_COUNT, $file_download, '', "disabled") . "\n            </div>";
    // расширение формата для текста
    $html .= "<div id='div_field_text' style='display: none;'>\n  <table class='admin_table' width='40%' >\n  <col width='25%'/><col width='25%'/><col width='25%'/><col width='25%'/>\n  <tr align='center'>\n  <th></th>\n  <th>" . CONTROL_CONTENT_SUBDIVISION_FUNCS_ACCESS_INHERIT . "</th>\n  <th>" . CONTROL_CONTENT_SUBDIVISION_FUNCS_OBJ_YES . "</th>\n  <th>" . CONTROL_CONTENT_SUBDIVISION_FUNCS_OBJ_NO . "</th>\n  </tr>\n  <tr align='center'>\n  <td>" . CONTROL_CLASS_CLASS_OBJECTSLIST_SHOWOBJ_HTML . "</td>";
    // разрешать HTML-теги
    for ($i = 0; $i <= 2; $i++) {
        $html .= "<td bgcolor='" . ($format_text['html'] == $i ? "#E7E7E7" : "#FFFFFF") . "'>" . nc_admin_radio_simple('format_html', $i, '', isset($Array['format_html']) && $Array['format_html'] == $i || $format_text['html'] == $i, '', "class='w'") . "\n      </td>";
    }
    $html .= "</tr><tr align='center'>\n  <td>" . CONTROL_CLASS_CLASS_OBJECTSLIST_SHOWOBJ_BR . "</td>";
    // перенос строки
    for ($i = 0; $i <= 2; $i++) {
        $html .= "<td bgcolor='" . ($format_text['br'] == $i ? "#E7E7E7" : "#FFFFFF") . "'>" . nc_admin_radio_simple('format_br', $i, '', isset($Array['format_br']) && $Array['format_br'] == $i || $format_text['br'] == $i, '', "class='w'") . "\n      </td>";
    }
    $html .= "\n  </tr><tr align='center'>\n  <td>" . CONTROL_FIELD__EDITOR_EMBED_TO_FIELD . "</td>";
    // встроить редактор
    for ($i = 0; $i <= 2; $i++) {
        $html .= "<td bgcolor='" . ($format_text['fck'] == $i ? "#E7E7E7" : "#FFFFFF") . "'>" . nc_admin_radio_simple('format_fck', $i, '', isset($Array['format_fck']) && $Array['format_fck'] == $i || $format_text['fck'] == $i, '', "class='w' onchange='nc_field_select_fck(this); return true;'") . "\n      </td>";
    }
    $html .= "</tr></table><br/>";
    $html .= CONTROL_FIELD__TEXTAREA_SIZE . ":<br/>\n  <table class='admin_table' width='40%' >\n  <col width='50%'/><col width='50%'/>\n    <tr align='center'>\n      <td>" . CONTROL_FIELD_HEIGHT . "</td>\n      <td>" . nc_admin_input_simple('format_height', isset($Array['format_height']) ? $Array['format_height'] : $format_text['rows'], 0, 'width:100%') . "</td></tr>\n    <tr align='center'>\n      <td>" . CONTROL_FIELD_WIDTH . "</td>\n      <td>" . nc_admin_input_simple('format_width', isset($Array['format_height']) ? $Array['format_width'] : $format_text['cols'], 0, 'width:100%') . "</td>\n    </tr>\n  </table>\n  <br />";
    $panels = array(0 => CONTROL_FIELD_PANELS_DEFAULT);
    $sql = "SELECT `Wysiwyg_Panel_ID`, `Name` FROM `Wysiwyg_Panel` " . "WHERE `Editor` = 'ckeditor' " . "ORDER BY `Wysiwyg_Panel_ID` ASC";
    foreach ((array) $db->get_results($sql, ARRAY_A) as $panel) {
        $panels[$panel['Wysiwyg_Panel_ID']] = $panel['Name'];
    }
    $html .= "<div id='format-panel-block' style='" . ($format_text['fck'] == 2 ? 'display: none;' : '') . "'>" . CONTROL_FIELD_PANELS . ":<br><div class='nc-select'>" . nc_admin_select_simple('', 'format_panel', $panels, isset($Array['format_panel']) ? $Array['format_panel'] : $format_text['panel']) . "<i class='nc-caret'></i></div><br><br /></div>";
    $html .= nc_admin_checkbox_simple('format_typo', 1, CONTROL_FIELD_TYPO, isset($Array['format_typo']) ? $Array['format_typo'] : $format_text['typo']) . "\n  <br />" . nc_admin_checkbox_simple('format_bbcode', 1, CONTROL_FIELD_BBCODE_ENABLED, isset($Array['format_bbcode']) ? $Array['format_bbcode'] : $format_text['bbcode']) . "\n  <br/><br/>\n  </div>";
    $html .= "<div id='div_field_date' style='display: none'>" . nc_admin_checkbox_simple('use_calendar', 1, CONTROL_FIELD_USE_CALENDAR, false, 'format_use_calendar', $format_date['calendar'] ? "checked='checked'" : "") . "\n            </div><br/>";
    $html .= "<div id='div_file_resize' style='display: none'>";
    $html .= nc_admin_checkbox_simple('format_use_resize', 1, CONTROL_FIELD_MULTIFIELD_USE_IMAGE_RESIZE, $format_file_resize['use_resize']);
    $html .= "<div>";
    $html .= CONTROL_FIELD_MULTIFIELD_IMAGE_WIDTH . ": " . nc_admin_input_simple('format_resize_width', $format_file_resize['resize_width'], 10) . " ";
    $html .= CONTROL_FIELD_MULTIFIELD_IMAGE_HEIGHT . ": " . nc_admin_input_simple('format_resize_height', $format_file_resize['resize_height'], 10);
    $html .= "</div><br>";
    $html .= nc_admin_checkbox_simple('format_use_crop', 1, CONTROL_FIELD_MULTIFIELD_USE_IMAGE_CROP, $format_file_resize['use_crop']);
    $html .= "<div>";
    $html .= "X0: " . nc_admin_input_simple('format_crop_x0', $format_file_resize['crop_x0'], 10) . " ";
    $html .= "Y0: " . nc_admin_input_simple('format_crop_y0', $format_file_resize['crop_y0'], 10) . "<br>";
    $html .= "X1: " . nc_admin_input_simple('format_crop_x1', $format_file_resize['crop_x1'], 10) . " ";
    $html .= "Y1: " . nc_admin_input_simple('format_crop_y1', $format_file_resize['crop_y1'], 10);
    $html .= "</div><br>";
    $html .= nc_admin_checkbox_simple('format_crop_ignore', 1, CONTROL_FIELD_MULTIFIELD_CROP_IGNORE, $format_file_resize['crop_ignore']);
    $html .= "<div>";
    $html .= CONTROL_FIELD_MULTIFIELD_IMAGE_WIDTH . ": " . nc_admin_input_simple('format_crop_ignore_width', $format_file_resize['crop_ignore_width'], 10) . " ";
    $html .= CONTROL_FIELD_MULTIFIELD_IMAGE_HEIGHT . ": " . nc_admin_input_simple('format_crop_ignore_height', $format_file_resize['crop_ignore_height'], 10);
    $html .= "</div><br/>";
    $html .= nc_admin_checkbox_simple('format_use_preview', 1, CONTROL_FIELD_MULTIFIELD_USE_IMAGE_PREVIEW, $format_file_resize['use_preview']);
    $html .= "<div>";
    $html .= CONTROL_FIELD_MULTIFIELD_IMAGE_WIDTH . ": " . nc_admin_input_simple('format_preview_width', $format_file_resize['preview_width'], 10) . " ";
    $html .= CONTROL_FIELD_MULTIFIELD_IMAGE_HEIGHT . ": " . nc_admin_input_simple('format_preview_height', $format_file_resize['preview_height'], 10);
    $html .= "</div>";
    $html .= "</div><br/>";
    echo $html;
    echo nc_admin_textarea_simple('Extension', $Array['Extension'], CONTROL_FIELD_ONE_EXTENSION . ":<br>", 7, 0, '', 'soft');
    echo "<br><br>";
    print nc_admin_checkbox_simple('NotNull', 1, CONTROL_FIELD_ONE_MUSTBE, $Array["NotNull"], 'notn') . "<br>";
    if ($isSys) {
        print nc_admin_checkbox_simple('Inheritance', 1, CONTROL_FIELD_ONE_INHERITANCE, $Array["Inheritance"], 'inhr') . "<br>";
    } else {
        print nc_admin_checkbox_simple('DoSearch', 1, CONTROL_FIELD_ONE_INDEX, $Array["DoSearch"] && $Array['TypeOfData_ID'] != 9, 'dosr', $Array['TypeOfData_ID'] != 9 ? " disabled='disabled'" : "") . "<br>";
        print nc_admin_checkbox_simple('InTableView', 1, CONTROL_FIELD_ONE_IN_TABLE_VIEW, $Array["InTableView"]) . "<br>";
    }
    print '<br>';
    print CONTROL_CONTENT_CATALOUGE_FUNCS_CATALOGUEFORM_PRIORITY . ": " . nc_admin_input_simple('Priority', $Array["Priority"] + 0, 3, '', "maxlength='5'") . "<br><br>";
    print CONTROL_FIELD_ONE_DEFAULT . "*:<br>";
    print nc_admin_input_simple('DefaultState', $Array["DefaultState"], 50, '', "id='DefaultState' maxlength='255'") . "\n";
    print "<br>* " . CONTROL_FIELD_ONE_DEFAULT_NOTE . ".<br><br>\n";
    print "<table class='admin_table' width='60%' >" . "<col width='25%'/><col width='25%'/><col width='25%'/><col width='25%'/>" . "<tr><td></td>";
    if (!$Array["TypeOfEdit_ID"]) {
        $Array["TypeOfEdit_ID"] = 1;
    }
    for ($i = 1; $i <= count($type_of_edit_name); $i++) {
        print "<td text-align:center'><label for='mod" . $i . "'>" . $type_of_edit_name[$i] . "</label></td>";
    }
    print "</tr><tr><td text-align:center'>" . CONTROL_FIELD_ONE_ACCESS . "</td>";
    for ($i = 1; $i <= count($type_of_edit_name); $i++) {
        print "<td text-align:center'>" . nc_admin_radio_simple('TypeOfEdit_ID', $i, '', $Array["TypeOfEdit_ID"] == $i, "mod" . $i, "class='w'") . "</td>";
    }
    print "</tr>" . "</table>";
    // js для визуальной настройки формата
    print $js;
    if (!$FieldID) {
        $UI_CONFIG->actionButtons[] = array("id" => "submit", "caption" => CONTROL_FIELD_LIST_ADD, "action" => "mainView.submitIframeForm('" . $FormID . "')");
    } else {
        $UI_CONFIG->actionButtons[] = array("id" => "submit", "caption" => CONTROL_CONTENT_CATALOUGE_FUNCS_CATALOGUEFORM_SAVE, "action" => "mainView.submitIframeForm('" . $FormID . "')");
    }
    $name = $isSys ? "SystemTableID" : ($isWidget ? "widgetclass_id" : "ClassID");
    if ($Id) {
        print "<input type='hidden' name='" . $name . "' value='" . $Id . "'>\n";
        print "<input type='hidden' name='phase' value='3'>\n";
    } else {
        if ($isSys) {
            print "<input type='hidden' name='SystemTableID' value='" . $Id . "'>\n";
        }
        print "<input type='hidden' name='FieldID' value='" . $FieldID . "'>\n";
        print "<input type='hidden' name='phase' value='5'>\n";
    }
    print $Additional;
    print $nc_core->token->get_input();
    print "<input type='hidden' name='isSys' value='" . $isSys . "'>\n";
    print "<input type='hidden' name='fs' value='" . +$_REQUEST['fs'] . "'>";
    print "<input type='submit' class='hidden'>\n";
    print "<input type='hidden' name='isWidget' value='{$isWidget}' />";
    print "</form>\n";
    print "</fieldset>";
    return true;
}
 /**
  *  Функции для создания thumbnails для полей типа файл
  *
  *
  * @global  object $nc_core
  * @param   int $classID - идентифиактор класса (компонента)
  * @param   int $message - номер объекты
  * @param   int $field_src_id - идентификатор поля источника
  * @param   int $field_dst_id - идентификатор поля приемника
  * @param   int $width    Ширина нового изображения
  * @param   int $height   Высота нового изображения
  * @param   int $mode     [optional] Режим уменьшения: 0 - пропорционально уменьшает; 1 - вписывает в указанные размеры, обрезая края
  * @param   string $format  [optional] Формат создаваемого изображения (jpg, gif, png, bmp)
  * @param   int $quality  [optional] Качество сжатия изображения (0-100) при $format=='jpg'
  * @param   string $field_name_src
  * @return  bool true в случае удачи, false - в случае ошибки.
  * @access  public
  * @static
  */
 public static function createThumb_byID($classID, $message, $field_src_id, $field_dst_id, $width, $height, $mode = 0, $format = NULL, $quality = 90, $field_name_src = '', $is_sys = false)
 {
     global $nc_core;
     // проверка аргументов
     $message += 0;
     $field_src_id += 0;
     $field_dst_id += 0;
     $classID += 0;
     if (!$message || !$field_src_id || !$field_dst_id || !$classID) {
         return false;
     }
     # поиск исходного файла
     // латинское имя поля
     if (!$field_name_src) {
         $field_name_src = $nc_core->db->get_var("SELECT `Field_Name` FROM `Field` WHERE `Field_ID` = '" . $field_src_id . "'");
     }
     if (!$field_name_src) {
         return 0;
     }
     // Значение поля в таблице объектов
     $message_field = $is_sys ? $nc_core->db->get_row("SELECT * FROM `User` WHERE `User_ID` = '" . $message . "'", ARRAY_A) : $nc_core->db->get_row("SELECT * FROM `Message" . $classID . "` WHERE `Message_ID` = '" . $message . "'", ARRAY_A);
     $file_data = explode(':', $message_field[$field_name_src]);
     $file_name = $file_data[0];
     $file_type = $file_data[1];
     $file_size = $file_data[2];
     $ext = substr($file_name, strrpos($file_name, "."));
     // расширение файла
     $file_name = substr($file_name, 0, strrpos($file_name, "."));
     // имя файла без расширения.
     // если ли файл в Filetable ?
     $filetable = $nc_core->db->get_row("SELECT * FROM `Filetable`\n                                            WHERE `Message_ID` = '" . intval($message) . "' AND `Field_ID` = '" . intval($field_src_id) . "'", ARRAY_A);
     // определения полного пути к файлу
     if ($filetable) {
         // исходный файл в protected
         $path_src = rtrim($nc_core->FILES_FOLDER, '/') . $filetable['File_Path'] . $filetable['Virt_Name'];
     } else {
         if ($file_data[3]) {
             // orignal
             $path_src = $nc_core->FILES_FOLDER . $file_data[3];
         } else {
             // simple
             $path_src = $nc_core->FILES_FOLDER . $field_src_id . "_" . $message . $ext;
         }
     }
     $img_size = getimagesize($path_src);
     if (!$format) {
         $format = strtolower(substr($img_size['mime'], strpos($img_size['mime'], '/') + 1));
     }
     // получение информации о поле-приемника
     $field_info_desc = $nc_core->db->get_row("SELECT `Field_Name`, `Format` FROM `Field` WHERE `Field_ID` = '" . $field_dst_id . "'", ARRAY_A);
     if (!$field_info_desc) {
         return false;
     }
     //удаление старого файла
     require_once $nc_core->INCLUDE_FOLDER . "s_files.inc.php";
     DeleteFile($field_dst_id, $field_info_desc['Field_Name'], $classID, 0, $message);
     // определение типа фс применика
     $fs = nc_field_parse_format($field_info_desc['Format'], NC_FIELDTYPE_FILE);
     $fs = $fs['fs'];
     $file_name .= "_thumb" . ++self::$_thumbPostfix;
     // определние имени файла на диске и диретории
     switch ($fs) {
         case NC_FS_PROTECTED:
             $path_dsc = $is_sys ? 'u/' : $message_field['Subdivision_ID'] . '/' . $message_field['Sub_Class_ID'] . '/';
             $name_dsc = md5($file_name . date("H:i:s d.m.Y") . uniqid("netcat"));
             break;
         case NC_FS_ORIGINAL:
             $path_dsc = $message_field['Subdivision_ID'] . '/' . $message_field['Sub_Class_ID'] . '/';
             $name_dsc = nc_get_filename_for_original_fs($file_name . ($format ? ".{$format}" : ''), $nc_core->FILES_FOLDER . $path_dsc);
             break;
         case NC_FS_SIMPLE:
             $path_dsc = '';
             $name_dsc = $field_dst_id . "_" . $message . ($format ? ".{$format}" : '');
             break;
     }
     // копирование файла
     //copy($path_src, $nc_core->FILES_FOLDER.$path_dsc.$name_dsc);
     // создание thumb
     $path_dest = $is_sys ? $nc_core->FILES_FOLDER . '/u/' . $name_dsc : $nc_core->FILES_FOLDER . $path_dsc . $name_dsc;
     self::imgResize($path_src, $path_dest, $width, $height, $mode, $format, $quality);
     switch ($fs) {
         case NC_FS_PROTECTED:
             $img_size = getimagesize($path_dest);
             if ($img_size === false) {
                 if (file_exists($path_dest)) {
                     unlink($path_dest);
                 }
                 return false;
             }
             $dst_File_Type = $img_size['mime'];
             $dst_File_Size = filesize($path_dest);
             $insert_filetable_sql = "INSERT INTO `Filetable`(Real_Name, Virt_Name, File_Path, File_Type, File_Size, Message_ID, Field_ID)\n                               VALUES('" . $nc_core->db->escape($file_name) . "." . $format . "', '" . $nc_core->db->escape($name_dsc) . "', '/" . $nc_core->db->escape($path_dsc) . "','" . $dst_File_Type . "', '" . $dst_File_Size . "', '" . $message . "', '" . $field_dst_id . "')";
             $nc_core->db->query($insert_filetable_sql);
             $in_db = $file_name . ":" . $dst_File_Type . ":" . $dst_File_Size;
             // то, что запишится в БД
             break;
         case NC_FS_ORIGINAL:
             $in_db = $file_name . "." . $format . ":" . $format . ":" . $file_size;
             // то, что запишится в БД
             $in_db .= ":" . ($is_sys ? 'u/' . $name_dsc : $path_dsc . $name_dsc);
             break;
         default:
             $in_db = $file_name . "." . $format . ":" . $format . ":" . $file_size;
             // то, что запишится в БД
             break;
     }
     $is_sys ? $nc_core->db->query("UPDATE `User` SET `" . $field_info_desc['Field_Name'] . "` = '" . $nc_core->db->escape($in_db) . "' WHERE `User_ID` = '" . $message . "'") : $nc_core->db->query("UPDATE `Message" . $classID . "` SET `" . $field_info_desc['Field_Name'] . "` = '" . $nc_core->db->escape($in_db) . "' WHERE `Message_ID` = '" . $message . "'");
     return true;
 }