예제 #1
0
 public function create($type, $settings)
 {
     $path = $this->template->path_to_root_folder . '/' . $this->id . '/' . $type;
     nc_create_folder(nc_standardize_path_to_folder($path));
     foreach ($settings as $field_name => $tmp) {
         nc_save_file(nc_standardize_path_to_file($path . '/' . $field_name . $this->template->extension), $settings[$field_name]);
     }
 }
예제 #2
0
function nc_check_availability_candidates_for_delete_in_multifile_and_delete()
{
    if (isset($_POST['del_multifile'][0])) {
        $nc_core = nc_Core::get_object();
        $db = $nc_core->db;
        $del_multifile = array_map('intval', $_POST['del_multifile']);
        $SQL = "SELECT Path,\n                       Preview\n                    FROM Multifield\n                        WHERE ID IN (" . join(', ', $del_multifile) . ")";
        $file_for_del = $db->get_results($SQL);
        if ($file_for_del) {
            $array_file_for_del = array();
            foreach ($file_for_del as $file) {
                $array_file_for_del[] = $file->Path;
                if ($file->Preview) {
                    $array_file_for_del[] = $file->Preview;
                }
            }
        }
        $SQL = "DELETE \n                FROM Multifield\n                    WHERE ID IN(" . join(', ', $del_multifile) . ")";
        $db->query($SQL);
        foreach ($array_file_for_del as $file) {
            $file = nc_standardize_path_to_file(join('/', array($nc_core->DOCUMENT_ROOT, $nc_core->SUB_FOLDER, $file)));
            if (file_exists($file)) {
                @unlink($file);
            }
        }
    }
}
예제 #3
0
파일: admin.inc.php 프로젝트: Blu2z/implsk
/**
 * Копирование объекта из одного шаблона в разделе в другой.
 *
 * Пользователь должен обладать правами: изменение в разделе, где
 * находится объект, и удаление в разделе, куда переносится объект.
 *
 * @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;
}
예제 #4
0
파일: copy.php 프로젝트: Blu2z/implsk
function nc_copy_subdivision($sub_ids, $dest_catalogue_id, $dest_parent_sub_id, $with_child = 1, $with_сс = 1, $with_object = 1, $templates = array())
{
    $nc_core = nc_Core::get_object();
    global $db;
    if (!is_array($sub_ids)) {
        $sub_ids = array($sub_ids);
    }
    if (!$with_сс) {
        $with_object = 0;
    }
    if (!$templates['sub_name']) {
        $templates['sub_name'] = '%NAME%';
    }
    if (!$templates['sub_keyword']) {
        $templates['sub_keyword'] = '%KEYWORD%';
    }
    if (!$templates['cc_name']) {
        $templates['cc_name'] = '%NAME%';
    }
    if (!$templates['cc_keyword']) {
        $templates['cc_keyword'] = '%KEYWORD%';
    }
    // разделы для копирования
    $subdivisions = $db->get_results("SELECT * FROM `Subdivision`\n                                    WHERE `Subdivision_ID` IN (" . join(',', $sub_ids) . ")\n                                    ORDER BY `Subdivision_ID` ", ARRAY_A);
    if (empty($subdivisions)) {
        return 0;
    }
    if ($dest_parent_sub_id && in_array($dest_parent_sub_id, $sub_ids)) {
        throw new Exception(TOOLS_COPYSUB_ERROR_LEVEL_COUNT);
    }
    // копирование в определенный раздел - можно вычислить сайт
    if ($dest_parent_sub_id) {
        $dest_subdivision = $db->get_row("SELECT `Catalogue_ID`, `Hidden_URL`, `EnglishName` FROM `Subdivision` WHERE `Subdivision_ID` = '" . $dest_parent_sub_id . "'", ARRAY_A);
        $dest_catalogue_id = $dest_subdivision['Catalogue_ID'];
        $hidden_url = $dest_subdivision['Hidden_URL'];
        $english_name = $dest_subdivision['EnglishName'];
        $child_english_names = $db->get_col("SELECT `EnglishName` FROM `Subdivision` WHERE `Parent_Sub_ID` = '" . $dest_parent_sub_id . "' ");
    } else {
        $hidden_url = '/';
        $child_english_names = $db->get_col("SELECT `EnglishName` FROM `Subdivision` WHERE `Parent_Sub_ID` = '0' AND `Catalogue_ID` = '" . $dest_catalogue_id . "' ");
    }
    if (!$child_english_names) {
        $child_english_names = array();
    }
    $fields = array_keys($subdivisions[0]);
    $query_fields_subdivisions = array();
    $insert_values_subdivisions = array();
    unset($fields[0]);
    foreach ($fields as $v) {
        $query_fields_subdivisions[] = "`" . $v . "`";
    }
    foreach ($subdivisions as $subdivision) {
        $rel[$subdivision['Subdivision_ID']] = 0;
        // связка между старыми и новыми id
        $subdivision['Subdivision_Name'] = str_replace('%NAME%', $subdivision['Subdivision_Name'], $templates['sub_name']);
        $subdivision['Subdivision_Name'] = str_replace('%KEYWORD%', $subdivision['EnglishName'], $subdivision['Subdivision_Name']);
        $subdivision['EnglishName'] = str_replace('%KEYWORD%', $subdivision['EnglishName'], $templates['sub_keyword']);
        $subdivision['Parent_Sub_ID'] = $dest_parent_sub_id;
        $subdivision['Catalogue_ID'] = $dest_catalogue_id;
        $subdivision['Created'] = $subdivision['LastUpdated'] = date("Y-m-d H:i:s");
        $subdivision['Hidden_URL'] = $hidden_url . $subdivision['EnglishName'] . '/';
        if (!$nc_core->subdivision->validate_english_name($subdivision['EnglishName'])) {
            throw new Exception(CONTROL_CONTENT_SUBDIVISION_INDEX_ERROR_THREE_KEYWORD_INVALID . "<br/>" . $subdivision['EnglishName']);
        }
        //if ( $english_name == $subdivision['EnglishName'] ) {
        //  throw new Exception(TOOLS_COPYSUB_ERROR_KEYWORD_EXIST);
        //}
        if (in_array($subdivision['EnglishName'], $child_english_names)) {
            throw new Exception(TOOLS_COPYSUB_ERROR_KEYWORD_EXIST);
        }
        // нельзя скопировать раздел в подраздел этого же раздела
        if ($dest_parent_sub_id) {
            $childs = nc_get_subdivision_children($subdivision['Subdivision_ID']);
            if (!empty($childs) && in_array($dest_parent_sub_id, $childs)) {
                throw new Exception(TOOLS_COPYSUB_ERROR_LEVEL_COUNT);
            }
        }
        $query_values = array();
        foreach ($fields as $v) {
            $query_values[] = "'" . $db->escape($subdivision[$v]) . "'";
        }
        $insert_values_subdivisions[$subdivision['Subdivision_ID']] = "(" . join(',', $query_values) . ")";
    }
    $nc_core->event->execute("addSubdivisionPrep", $dest_catalogue_id, 0);
    foreach ($insert_values_subdivisions as $Subdivision_ID => $insert_value_subdivisions) {
        $db->query("INSERT INTO `Subdivision` (" . join(',', $query_fields_subdivisions) . ")  VALUES {$insert_value_subdivisions}");
        if ($db->is_error) {
            throw new nc_Exception_DB_Error($db->last_query, $db->last_error);
        }
        $inserted_id = $db->insert_id;
        $rel[$Subdivision_ID] = $inserted_id;
        if (!is_dir($nc_core->FILES_FOLDER . $inserted_id)) {
            @mkdir($nc_core->FILES_FOLDER . $inserted_id, $nc_core->DIRCHMOD);
            @chmod($nc_core->FILES_FOLDER . $inserted_id, $nc_core->DIRCHMOD);
        }
    }
    $nc_core->event->execute("addSubdivision", $dest_catalogue_id, $rel);
    // компоненты в разделе для копирования
    $sub_classes = !$with_сс ? null : $db->get_results("SELECT * FROM `Sub_Class`\n                                                     WHERE `Subdivision_ID` IN (" . join(',', $sub_ids) . ")\n                                                     ORDER BY `Sub_Class_ID`", ARRAY_A);
    $query_fields_subclasses = array();
    $insert_values_subclasses = array();
    if (!empty($sub_classes)) {
        $fields = array_keys($sub_classes[0]);
        unset($fields[0]);
        foreach ($fields as $v) {
            $query_fields_subclasses[] = "`" . $v . "`";
        }
        foreach ($sub_classes as $sub_class) {
            $rel_cc[$sub_class['Sub_Class_ID']] = 0;
            $sub_class['Subdivision_ID'] = $rel[$sub_class['Subdivision_ID']];
            $sub_class['Sub_Class_Name'] = str_replace('%NAME%', $sub_class['Sub_Class_Name'], $templates['cc_name']);
            $sub_class['EnglishName'] = str_replace('%KEYWORD%', $sub_class['EnglishName'], $templates['cc_keyword']);
            $sub_class['Created'] = $sub_class['LastUpdated'] = date("Y-m-d H:i:s");
            $sub_class['Catalogue_ID'] = $dest_catalogue_id;
            if (!$nc_core->sub_class->validate_english_name($sub_class['EnglishName'])) {
                throw new Exception(CONTROL_CONTENT_SUBDIVISION_INDEX_ERROR_THREE_KEYWORD_INVALID . "<br/>" . $sub_class['EnglishName']);
            }
            $query_values = array();
            foreach ($fields as $v) {
                $query_values[] = "'" . $db->escape($sub_class[$v]) . "'";
            }
            $insert_values_subclasses[$sub_class['Sub_Class_ID']] = "(" . join(',', $query_values) . ")";
        }
        foreach ($sub_classes as $sub_class) {
            $nc_core->event->execute("addSubClassPrep", $dest_catalogue_id, $sub_class['Subdivision_ID'], 0);
            $db->query("INSERT INTO `Sub_Class` (" . join(',', $query_fields_subclasses) . ")  VALUES {$insert_values_subclasses[$sub_class['Sub_Class_ID']]}");
            if ($db->is_error) {
                throw new nc_Exception_DB_Error($db->last_query, $db->last_error);
            }
            $inserted_id = $db->insert_id;
            $k = $sub_class['Sub_Class_ID'];
            $rel_cc[$k] = $inserted_id;
            $class_id = $sub_class['Class_ID'];
            $is_system_table = $db->get_var("SELECT `System_Table_ID` FROM `Class` WHERE `Class_ID` = '" . $class_id . "' ");
            $sub_id = $rel[$sub_class['Subdivision_ID']];
            $nc_core->event->execute("addSubClass", $dest_catalogue_id, $sub_id, $rel_cc[$k]);
            if (!is_dir($nc_core->FILES_FOLDER . $sub_id . "/" . $rel_cc[$k])) {
                @mkdir($nc_core->FILES_FOLDER . $sub_id . "/" . $rel_cc[$k], $nc_core->DIRCHMOD);
                @chmod($nc_core->FILES_FOLDER . $sub_id . "/" . $rel_cc[$k], $nc_core->DIRCHMOD);
            }
            // объекты для копирования
            $messages = !$with_object || $is_system_table ? null : $db->get_results("SELECT * FROM `Message" . $class_id . "` WHERE `Sub_Class_ID` = '" . $k . "' ORDER BY `Message_ID`", ARRAY_A);
            $query_fields_messages = array();
            $insert_values_messages = array();
            if (!empty($messages)) {
                $fields = array_keys($messages[0]);
                unset($fields[0]);
                foreach ($fields as $v) {
                    $query_fields_messages[] = "`" . $v . "`";
                }
                $msg_ids = array();
                $rel_message = array();
                foreach ($messages as $message) {
                    $rel_message[$message['Message_ID']] = 0;
                    $message['Subdivision_ID'] = $rel[$message['Subdivision_ID']];
                    $message['Sub_Class_ID'] = $rel_cc[$message['Sub_Class_ID']];
                    $message['Created'] = $message['LastUpdated'] = date("Y-m-d H:i:s");
                    $msg_ids[] = $message['Message_ID'];
                    $query_values = array();
                    foreach ($fields as $v) {
                        $query_values[] = "'" . $db->escape($message[$v]) . "'";
                    }
                    $insert_values_messages[$message['Message_ID']] = "(" . join(',', $query_values) . ")";
                }
                // копирование файлов объекта
                $file_fields = array();
                $tmp = $db->get_results("SELECT `Field_ID` AS `id`, `Field_Name` AS `name` FROM `Field` WHERE `Class_ID`='" . $class_id . "' AND `TypeOfData_ID` = '6' ", ARRAY_A);
                if ($tmp) {
                    foreach ($tmp as $v) {
                        $file_fields[$v['id']] = $v['name'];
                    }
                    $filetable = $db->get_results("SELECT * FROM `Filetable`\n                                   WHERE `Field_ID` IN (" . join(',', array_keys($file_fields)) . ")\n                                   AND `Message_ID` IN (" . join(',', $msg_ids) . ") ", ARRAY_A);
                }
                // Поля типа "множественная загрузка" в компоненте
                $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 ($messages as $message) {
                    $message_id = $message['Message_ID'];
                    // событие
                    $nc_core->event->execute("addMessagePrep", $dest_catalogue_id, $rel[$message['Subdivision_ID']], $rel_cc[$message['Sub_Class_ID']], $class_id, 0);
                    $db->query("INSERT INTO `Message" . $class_id . "` (" . join(',', $query_fields_messages) . ")  VALUES {$insert_values_messages[$message_id]}");
                    if ($db->is_error) {
                        throw new nc_Exception_DB_Error($db->last_query, $db->last_error);
                    }
                    $inserted_id = $db->insert_id;
                    $k = $message_id;
                    $rel_message[$k] = $inserted_id;
                    // событие
                    $nc_core->event->execute("addMessage", $dest_catalogue_id, $rel[$message['Subdivision_ID']], $rel_cc[$message['Sub_Class_ID']], $class_id, $rel_message[$message_id]);
                    if (!empty($file_fields)) {
                        foreach ($file_fields as $field_id => $field_name) {
                            if ($value = $message[$field_name]) {
                                $is_copy = 0;
                                if (!empty($filetable)) {
                                    foreach ($filetable as $v) {
                                        if ($v['Message_ID'] == $message_id && $v['Field_ID'] == $field_id) {
                                            $file_path = rtrim($nc_core->FILES_FOLDER, '/') . $v['File_Path'] . $v['Virt_Name'];
                                            $new_name = md5($file_path . date("H:i:s d.m.Y") . uniqid("netcat"));
                                            $new_file_path = $rel[$message['Subdivision_ID']] . "/" . $rel_cc[$message['Sub_Class_ID']];
                                            @copy($file_path, $nc_core->FILES_FOLDER . $new_file_path . "/" . $new_name);
                                            $to_filetable[] = "('" . $db->escape($v['Real_Name']) . "', '" . $new_name . "', '/" . $new_file_path . "/',\n                                   '" . $v['File_Type'] . "', '" . $v['File_Size'] . "', '" . $rel_message[$message_id] . "',\n                                   '" . $field_id . "', '" . $v['Content_Disposition'] . "')";
                                            $is_copy = 1;
                                        }
                                    }
                                }
                                if ($is_copy) {
                                    continue;
                                }
                                $file_data = explode(':', $value);
                                $file_name = $file_data[0];
                                $ext = nc_substr($file_name, nc_strrpos($file_name, "."));
                                // расширение файла
                                if ($file_data[3]) {
                                    $new_name = nc_get_filename_for_original_fs($file_name, $nc_core->FILES_FOLDER . $rel[$message['Subdivision_ID']] . "/" . $rel_cc[$message['Sub_Class_ID']] . "/");
                                    @copy($nc_core->FILES_FOLDER . $file_data[3], $nc_core->FILES_FOLDER . $rel[$message['Subdivision_ID']] . "/" . $rel_cc[$message['Sub_Class_ID']] . "/" . $new_name);
                                    $dt = $file_data[0] . ":" . $file_data[1] . ":" . $file_data[2] . ":" . $rel[$message['Subdivision_ID']] . "/" . $rel_cc[$message['Sub_Class_ID']] . "/" . $new_name;
                                    $db->query("UPDATE `Message" . $class_id . "` SET `" . $field_name . "` = '" . $dt . "' WHERE `Message_ID` = '" . $rel_message[$message_id] . "'  ");
                                } else {
                                    @copy($nc_core->FILES_FOLDER . $field_id . "_" . $message_id . $ext, $nc_core->FILES_FOLDER . $field_id . "_" . $rel_message[$message_id] . $ext);
                                }
                            }
                        }
                    }
                    // проходим по каждому полю
                    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);
                                    $new_file_name = nc_get_filename_for_original_fs($file_name, $settings_path);
                                    @copy($settings_path . $file_name, $settings_path . $new_file_name);
                                    $file[$path] = $settings_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}, {$rel_message[$message_id]}, {$priority}, '{$name}', {$size}, '{$path}', '{$preview}')";
                            $db->query($sql);
                        }
                    }
                }
            }
        }
    }
    //при копировании разделов проставлялись нули, если поле RecordsPerPage было не заполнено
    $sub_cc_ids = join(', ', (array) $rel_cc);
    if (!empty($sub_cc_ids)) {
        $db->query("UPDATE `Sub_Class`\n                    SET `RecordsPerPage` = NULL\n                        WHERE `RecordsPerPage`= 0\n                          AND `Sub_Class_ID` IN ({$sub_cc_ids})");
    }
    // копирование файлов
    $system_fields = $nc_core->get_system_table_fields("Subdivision");
    $file_fields = array();
    if (!empty($system_fields)) {
        foreach ($system_fields as $v) {
            if ($v['type'] == 6) {
                $file_fields[$v['id']] = $v['name'];
            }
        }
    }
    if (!empty($file_fields)) {
        $filetable = $db->get_results("SELECT * FROM `Filetable`\n                                   WHERE `Field_ID` IN (" . join(',', array_keys($file_fields)) . ")\n                                   AND `Message_ID` IN (" . join(',', $sub_ids) . ") ", ARRAY_A);
        foreach ($subdivisions as $subdivision) {
            $sub_id = $subdivision['Subdivision_ID'];
            foreach ($file_fields as $field_id => $field_name) {
                if ($value = $subdivision[$field_name]) {
                    $is_copy = 0;
                    if (!empty($filetable)) {
                        foreach ($filetable as $v) {
                            if ($v['Message_ID'] == $sub_id && $v['Field_ID'] == $field_id) {
                                $file_path = rtrim($nc_core->FILES_FOLDER, '/') . $v['File_Path'] . $v['Virt_Name'];
                                $new_name = md5($file_path . date("H:i:s d.m.Y") . uniqid("netcat"));
                                @copy($file_path, $nc_core->FILES_FOLDER . $rel[$sub_id] . "/" . $new_name);
                                $to_filetable[] = " ('" . $db->escape($v['Real_Name']) . "', '" . $new_name . "', '/" . $rel[$sub_id] . "/',\n                                   '" . $v['File_Type'] . "', '" . $v['File_Size'] . "', '" . $rel[$sub_id] . "',\n                                   '" . $field_id . "', '" . $v['Content_Disposition'] . "')";
                                // $db->debug();
                                $is_copy = 1;
                            }
                        }
                    }
                    if ($is_copy) {
                        continue;
                    }
                    $file_data = explode(':', $value);
                    $file_name = $file_data[0];
                    $ext = nc_substr($file_name, nc_strrpos($file_name, "."));
                    // расширение файла
                    if ($file_data[3]) {
                        $new_name = nc_get_filename_for_original_fs($file_name, $nc_core->FILES_FOLDER . $rel[$sub_id] . "/");
                        @copy($nc_core->FILES_FOLDER . $file_data[3], $nc_core->FILES_FOLDER . $rel[$sub_id] . "/" . $new_name);
                        $dt = $file_data[0] . ":" . $file_data[1] . ":" . $file_data[3] . ":" . $rel[$sub_id] . "/" . $new_name;
                        $db->query("UPDATE `Subdivision` SET `" . $field_name . "` = '" . $dt . "' WHERE `Subdivision_ID` = '" . $rel[$sub_id] . "'  ");
                        //   $db->debug();
                    } else {
                        @copy($nc_core->FILES_FOLDER . $field_id . "_" . $sub_id . $ext, $nc_core->FILES_FOLDER . $field_id . "_" . $rel[$sub_id] . $ext);
                    }
                }
            }
        }
    }
    // update filetable
    if (!empty($to_filetable)) {
        $db->query("INSERT INTO `Filetable` (`Real_Name`, `Virt_Name`, `File_Path`,\n                                         `File_Type`, `File_Size`, `Message_ID`, `Field_ID`, `Content_Disposition` )\n                          VALUES " . join(',', $to_filetable) . " ");
    }
    // рекурсивное копирование подразделов
    if ($with_child) {
        foreach ($rel as $k => $v) {
            $childs = $db->get_col("SELECT `Subdivision_ID` FROM `Subdivision` WHERE `Parent_Sub_ID` = '" . $k . "' ");
            if ($childs) {
                nc_copy_subdivision($childs, 0, $v, $with_child, $with_сс, $with_object, $templates);
            }
        }
    }
    return 0;
}
예제 #5
0
function nc_check_changes($hash, $path, $type)
{
    return md5(file_get_contents(nc_standardize_path_to_file($path . '/' . $type . '.html'))) == $hash;
}
예제 #6
0
function DeleteFieldsFiles($fields)
{
    global $db, $FILES_FOLDER;
    // set as array
    $fields = (array) $fields;
    $file_fields_to_delete = array();
    // validate for security reason
    $fields = array_map("intval", $fields);
    // return if array is empty
    if (empty($fields)) {
        return 0;
    }
    $deleted = 0;
    //поле "Файл"
    // get files info to delete
    $files_to_delete = (array) $db->get_results("SELECT ft.`Field_ID`, ft.`Virt_Name`, ft.`File_Path`, fl.`System_Table_ID` FROM `Filetable` AS ft\n    LEFT JOIN `Field` as fl ON ft.`Field_ID` = fl.`Field_ID`\n    WHERE ft.`Field_ID` IN (" . join(", ", $fields) . ") AND fl.`TypeOfData_ID` = 6", ARRAY_A);
    foreach ($files_to_delete as $_file_to_delete) {
        // set full path to file
        $file_to_delete_path = $FILES_FOLDER . $_file_to_delete['File_Path'] . $_file_to_delete['Virt_Name'];
        // try to delete file from disk
        if (is_writable($file_to_delete_path)) {
            @unlink($file_to_delete_path);
            $file_fields_to_delete[] = $_file_to_delete['Field_ID'];
        }
    }
    // drop rows form `Filetable` table
    if (!empty($file_fields_to_delete)) {
        $db->query("DELETE FROM `Filetable` WHERE `Field_ID` IN (" . join(", ", $file_fields_to_delete) . ")");
        $deleted += $db->rows_affected;
    }
    //поле "Мультифайл"
    $multifield_delete = array();
    $nc_core = nc_Core::get_object();
    $sql = "SELECT m.`Field_ID`, m.`Path`, m.`Preview` FROM `Multifield` AS m " . "LEFT JOIN `Field` as f ON m.`Field_ID` = f.`Field_ID` " . "WHERE m.`Field_ID` IN (" . join(", ", $fields) . ") AND f.`TypeOfData_ID` = 11";
    $multifields = (array) $db->get_results($sql, ARRAY_A);
    foreach ($multifields as $multifield) {
        $field_id = $multifield['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);
        foreach (array('Path', 'Preview') as $path) {
            $file_path = $multifield[$path];
            if ($file_path) {
                $parts = explode('/', nc_standardize_path_to_file($file_path));
                $file_name = array_pop($parts);
                @unlink($settings_path . $file_name);
            }
        }
        if (!in_array($field_id, $multifield_delete)) {
            $multifield_delete[] = $field_id;
        }
    }
    if (count($multifield_delete) > 0) {
        $db->query("DELETE FROM `Multifield` WHERE `Field_ID` IN (" . join(", ", $multifield_delete) . ")");
        $deleted += $db->rows_affected;
    }
    return $deleted;
}