Example #1
0
 public function save($value)
 {
     $nc_core = nc_Core::get_object();
     $array_name = $this->parent->get_array_name();
     if (!empty($value['old']) && !empty($value['kill'])) {
         list($filename, $filetype, $filesize, $filepath) = explode(':', $value['old']);
         unlink($nc_core->FILES_FOLDER . $filepath);
         $this->value = $value['old'] = '';
     }
     if ($_FILES[$array_name]['error'][$this->name]) {
         if ($value['old']) {
             $this->value = $value['old'];
         }
         return 0;
     }
     $tmp_name = $_FILES[$array_name]['tmp_name'][$this->name];
     $filetype = $_FILES[$array_name]['type'][$this->name];
     $filename = $_FILES[$array_name]['name'][$this->name];
     // nothing was changed
     if (!empty($value['old']) && empty($value['kill']) && !$filetype) {
         if ($value['old']) {
             $this->value = $value['old'];
         }
         return 0;
     }
     $folder = $nc_core->FILES_FOLDER . 'cs/';
     $put_file_name = nc_transliterate($filename);
     $put_file_name = nc_get_filename_for_original_fs($put_file_name, $folder, array());
     $nc_core->files->create_dir($folder);
     move_uploaded_file($tmp_name, $folder . $put_file_name);
     $filesize = filesize($folder . $put_file_name);
     if ($filesize) {
         $this->value = $filename . ':' . $filetype . ':' . $filesize . ':cs/' . $put_file_name;
     } else {
         $this->value = '';
     }
     $this->upload = true;
     $this->filename = $filename;
     $this->filetype = $filetype;
     $this->filesize = $filesize;
     $this->filepath = $folder . $put_file_name;
 }
Example #2
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;
}
Example #3
0
function ActionSubClassCompleted($type)
{
    global $nc_core, $db, $ClassID;
    global $loc, $ADMIN_FOLDER, $MODULE_FOLDER, $CustomSettings;
    $params = array('Priority', 'Checked', 'SubClassName', 'EnglishName', 'Class_Template_ID', 'DefaultAction', 'isNakedCC', 'AllowTags', 'NL2BR', 'UseCaptcha', 'RecordsPerPage', 'SortBy', 'Read_Access_ID', 'Write_Access_ID', 'Cache_Lifetime', 'Edit_Access_ID', 'Checked_Access_ID', 'Delete_Access_ID', 'Moderation_ID', 'CacheAccessID', 'CacheLifetime', 'CacheForUser', 'CommentAccessID', 'Edit_Class_Template', 'CommentsEditRules', 'CommentsDeleteRules', 'SubClassID', 'SubdivisionID', 'CatalogueID', 'SrcMirror', 'Cache_Access_ID');
    foreach ($params as $v) {
        ${$v} = $nc_core->input->fetch_get_post($v);
    }
    //транслитерация, если пустой EnglishName
    if (empty($EnglishName)) {
        $EnglishName = nc_transliterate($SubClassName, true);
    }
    // проверка на валидность
    $EnglishName = nc_check_english_name((int) $SubClassID, $EnglishName, 2);
    if (nc_module_check_by_keyword("comments")) {
        include_once $MODULE_FOLDER . "comments/function.inc.php";
    }
    if (+$_POST['is_mirror']) {
        $ClassID = $nc_core->sub_class->get_by_id(+$SrcMirror, 'Class_ID');
    }
    if ($Class_Template_ID == $ClassID) {
        $Class_Template_ID = 0;
    }
    if ($Priority === '') {
        $Priority = $db->get_var("SELECT (`Priority` + 1) FROM `Sub_Class` WHERE `Subdivision_ID` = '" . $loc->SubdivisionID . "' ORDER BY `Priority` DESC LIMIT 1");
    }
    if ($type == 1) {
        if (nc_module_check_by_keyword("cache")) {
            $cache_insert_fields = "`Cache_Access_ID`, `Cache_Lifetime`, `CacheForUser`,";
            $cache_insert_values = "'" . $Cache_Access_ID . "', '" . $Cache_Lifetime . "', '" . $CacheForUser . "',";
        } else {
            $cache_insert_fields = "";
            $cache_insert_values = "";
        }
        $insert = "INSERT INTO `Sub_Class` (" . $cache_insert_fields . "`Subdivision_ID`, `Catalogue_ID`, `Class_ID`, `Sub_Class_Name`, `Read_Access_ID`, `Write_Access_ID`, `Edit_Access_ID`, `Checked_Access_ID`, `Delete_Access_ID`, `Subscribe_Access_ID`, `Moderation_ID`, `Checked`, `Priority`, `EnglishName`, `DaysToHold`, `AllowTags`, `NL2BR`, `RecordsPerPage`, `SortBy`, `Created`, `DefaultAction`, `UseCaptcha`, `CustomSettings`, `Class_Template_ID`, `isNaked`, `SrcMirror`)";
        $insert .= " VALUES (" . $cache_insert_values . "'" . $loc->SubdivisionID . "', '" . $loc->CatalogueID . "', '" . $ClassID . "', '" . $db->escape($SubClassName) . "', '" . $Read_Access_ID . "', '" . $Write_Access_ID . "', '" . $Edit_Access_ID . "', '" . $Checked_Access_ID . "','" . $Delete_Access_ID . "','" . $SubscribeAccessID . "', '" . $Moderation_ID . "', '" . $Checked . "', '" . $Priority . "', '" . $EnglishName . "', ";
        $insert .= $DaysToHold == "" ? "NULL, " : "'" . $DaysToHold . "', ";
        $insert .= "'" . $AllowTags . "', ";
        $insert .= "'" . $NL2BR . "', ";
        $insert .= $RecordsPerPage == "" ? "NULL" : "'" . $RecordsPerPage . "'";
        $insert .= ",'{$SortBy}','" . date("Y-m-d H:i:s") . "','" . $DefaultAction . "', '" . $UseCaptcha . "', '" . addcslashes($CustomSettings, "'") . "', '" . $Class_Template_ID . "', '" . $isNakedCC . "', '" . $SrcMirror . "')";
        // execute core action
        $nc_core->event->execute("addSubClassPrep", $loc->CatalogueID, $loc->SubdivisionID, 0);
        $db->query($insert);
        // inserted ID
        $insertedSubClassID = $db->insert_id;
        // execute core action
        $nc_core->event->execute("addSubClass", $loc->CatalogueID, $loc->SubdivisionID, $insertedSubClassID);
        if (nc_module_check_by_keyword("comments")) {
            if ($CommentAccessID > 0) {
                // add comment relation
                $CommentRelationID = nc_comments::addRule($db, array($loc->CatalogueID, $loc->SubdivisionID, $insertedSubClassID), $CommentAccessID, $CommentsEditRules, $CommentsDeleteRules);
                // update inserted data
                $db->query("UPDATE `Sub_Class` SET `Comment_Rule_ID` = '" . (int) $CommentRelationID . "' WHERE `Sub_Class_ID` = '" . (int) $insertedSubClassID . "'");
            }
        }
        return $insertedSubClassID;
    }
    if ($type == 2) {
        $cur_checked = $db->get_var("SELECT `Checked` FROM `Sub_Class` WHERE `Sub_Class_ID` = '" . $SubClassID . "'");
        if (nc_module_check_by_keyword("comments")) {
            $CommentData = nc_comments::getRuleData($db, array($loc->CatalogueID, $loc->SubdivisionID, $SubClassID));
            $CommentRelationID = $CommentData['ID'];
            switch (true) {
                case $CommentAccessID > 0 && $CommentRelationID:
                    // update comment rules
                    nc_comments::updateRule($db, array($loc->CatalogueID, $loc->SubdivisionID, $SubClassID), $CommentAccessID, $CommentsEditRules, $CommentsDeleteRules);
                    break;
                case $CommentAccessID > 0 && !$CommentRelationID:
                    // add comment relation
                    $CommentRelationID = nc_comments::addRule($db, array($loc->CatalogueID, $loc->SubdivisionID, $SubClassID), $CommentAccessID, $CommentsEditRules, $CommentsDeleteRules);
                    break;
                case $CommentAccessID <= 0 && $CommentRelationID:
                    // delete comment rules
                    nc_comments::dropRuleSubClass($db, $SubClassID);
                    $CommentRelationID = 0;
                    break;
            }
        }
        $update = "UPDATE `Sub_Class` SET ";
        $update .= "`Sub_Class_Name` = '" . $db->escape($SubClassName) . "',";
        $update .= "`Read_Access_ID` = '" . $Read_Access_ID . "',";
        $update .= "`Write_Access_ID` = '" . $Write_Access_ID . "',";
        $update .= "`Edit_Access_ID` = '" . $Edit_Access_ID . "',";
        $update .= "`Checked_Access_ID` = '" . $Checked_Access_ID . "',";
        $update .= "`Delete_Access_ID` = '" . $Delete_Access_ID . "',";
        $update .= "`Subscribe_Access_ID` = '" . $SubscribeAccessID . "',";
        if (nc_module_check_by_keyword("cache")) {
            $update .= "`Cache_Access_ID` = '" . $Cache_Access_ID . "',";
            $update .= "`Cache_Lifetime` = '" . $Cache_Lifetime . "',";
            $update .= "`CacheForUser` = '" . $CacheForUser . "',";
        }
        if (nc_module_check_by_keyword("comments")) {
            $update .= "`Comment_Rule_ID` = '" . $CommentRelationID . "',";
        }
        $update .= "`Moderation_ID` = '" . $Moderation_ID . "',";
        $update .= "`Checked` = '" . $Checked . "',";
        //$update.= "`Priority` = '" . $Priority . "',";
        $update .= "`EnglishName` = '" . $EnglishName . "',";
        $update .= "`DefaultAction` = '" . $DefaultAction . "',";
        $update .= $DaysToHold == "" ? "`DaysToHold` = NULL," : "`DaysToHold` = '" . $DaysToHold . "',";
        $update .= "`AllowTags` = '" . $AllowTags . "',";
        $update .= "`NL2BR` = '" . $NL2BR . "',";
        $update .= $RecordsPerPage == "" ? "`RecordsPerPage` = NULL," : "`RecordsPerPage` = '" . $RecordsPerPage . "',";
        $update .= "`SortBy` = '" . $SortBy . "',";
        $update .= "`UseCaptcha` = '" . $UseCaptcha . "', ";
        $update .= "`CustomSettings` = '" . $db->escape(addcslashes($CustomSettings, "'")) . "', ";
        $update .= "`Class_Template_ID` = '" . $Class_Template_ID . "', ";
        $update .= "`Edit_Class_Template` = '" . $Edit_Class_Template . "', ";
        $update .= "`isNaked` = '" . $isNakedCC . "', ";
        $update .= "`SrcMirror` = '" . $SrcMirror . "', ";
        $update .= "`AllowRSS` = '" . intval($nc_core->input->fetch_get_post('AllowRSS' . $SubClassID)) . "',";
        $update .= "`AllowXML` = '" . intval($nc_core->input->fetch_get_post('AllowXML' . $SubClassID)) . "'";
        $update .= " WHERE `Sub_Class_ID` = '" . $SubClassID . "'";
        $subclass_data = $nc_core->sub_class->get_by_id($SubClassID);
        $nc_core->event->execute("updateSubClassPrep", $subclass_data['Catalogue_ID'], $subclass_data['Subdivision_ID'], $SubClassID);
        if ($cur_checked != $Checked) {
            $nc_core->event->execute($Checked ? "checkSubClassPrep" : "uncheckSubClassPrep", $subclass_data['Catalogue_ID'], $subclass_data['Subdivision_ID'], $SubClassID);
        }
        $db->query($update);
        if ($db->is_error) {
            throw new nc_Exception_DB_Error($db->last_query, $db->last_error);
        }
        // execute core action
        $nc_core->event->execute("updateSubClass", $subclass_data['Catalogue_ID'], $subclass_data['Subdivision_ID'], $SubClassID);
        // произошло включение / выключение
        if ($cur_checked != $Checked) {
            $nc_core->event->execute($Checked ? "checkSubClass" : "uncheckSubClass", $subclass_data['Catalogue_ID'], $subclass_data['Subdivision_ID'], $SubClassID);
        }
        return $db->rows_affected;
    }
}
Example #4
0
 private function cleanString($string, $allowed = array())
 {
     $allow = null;
     if (!empty($allowed)) {
         foreach ($allowed as $value) {
             $allow .= "\\{$value}";
         }
     }
     if (is_array($string)) {
         $cleaned = array();
         foreach ($string as $key => $clean) {
             if (preg_match("/^[{$allow}a-zA-Z0-9]*\$/", $clean)) {
                 $cleaned[$key] = $clean;
             } else {
                 $cleaned[$key] = nc_transliterate($clean);
                 $cleaned[$key] = str_replace('\'', '', $cleaned[$key]);
             }
         }
     } else {
         if (preg_match("/^[{$allow}a-zA-Z0-9]*\$/", $string)) {
             $cleaned = $string;
         } else {
             $cleaned = nc_transliterate($string);
             $cleaned = str_replace('\'', '', $cleaned);
         }
     }
     return $cleaned;
 }
Example #5
0
 private function cleanString($string, $allowed = array())
 {
     $allow = null;
     if (!empty($allowed)) {
         foreach ($allowed as $value) {
             $allow .= "\\{$value}";
         }
     }
     $mapping = array('Š' => 'S', 'š' => 's', 'Đ' => 'Dj', 'đ' => 'dj', 'Ž' => 'Z', 'ž' => 'z', 'Č' => 'C', 'č' => 'c', 'Ć' => 'C', 'ć' => 'c', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O', 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'ű' => 'u', 'û' => 'u', 'ý' => 'y', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y', 'Ŕ' => 'R', 'ŕ' => 'r', ' ' => '_', "'" => '_', '/' => '');
     $nc_core = nc_Core::get_object();
     $CKEditorAllowCyrilicFolder = (int) $nc_core->get_settings('CKEditorAllowCyrilicFolder');
     if (is_array($string)) {
         $cleaned = array();
         foreach ($string as $key => $clean) {
             $clean = strtr($clean, $mapping);
             if (!$CKEditorAllowCyrilicFolder) {
                 $string = nc_transliterate($string);
                 $clean = preg_replace("/[^{$allow}_a-zA-Z0-9]/u", '', $string);
                 // $clean = preg_replace("/[^{$allow}_a-zA-Z0-9\x{0430}-\x{044F}\x{0410}-\x{042F}]/u", '', $clean); // allow only latin alphabet with cyrillic
             }
             $cleaned[$key] = preg_replace('/[_]+/', '_', $clean);
             // remove double underscore
         }
     } else {
         $clean = $string = strtr($string, $mapping);
         if (!$CKEditorAllowCyrilicFolder) {
             $string = nc_transliterate($string);
             $clean = preg_replace("/[^{$allow}_a-zA-Z0-9]/u", '', $string);
             // $clean = preg_replace("/[^{$allow}_a-zA-Z0-9\x{0430}-\x{044F}\x{0410}-\x{042F}]/u", '', $string); // allow only latin alphabet with cyrillic
         }
         $cleaned = preg_replace('/[_]+/', '_', $clean);
         // remove double underscore
     }
     return $cleaned;
 }
Example #6
0
         require_once $ADMIN_FOLDER . "array_to_form.inc.php";
         $a2f = new nc_a2f($settings_array, 'CustomSettings');
         if (!$a2f->validate($CustomSettings)) {
             $error = $a2f->get_validation_errors();
         } else {
             $a2f->save($CustomSettings);
             $CustomSettings = $a2f->get_values_as_string();
         }
     } else {
         $CustomSettings = "";
     }
     // транслитерация, если пустой EnglishName
     if (empty($EnglishName)) {
         // здесь не нужна проверка на уникальность, поскольку далее
         // значение используется лишь для проверки на валидность
         $EnglishName = nc_transliterate($SubClassName, true);
     }
     // проверка значений
     if ($SubClassName == "") {
         $error = CONTROL_CONTENT_SUBDIVISION_SUBCLASS_ERROR_NAME;
     } elseif (!$nc_core->sub_class->validate_english_name($EnglishName)) {
         $error = CONTROL_CONTENT_SUBDIVISION_SUBCLASS_ERROR_KEYWORD_INVALID;
     } elseif (!IsAllowedSubClassEnglishName($EnglishName, $SubdivisionID, (int) $SubClassID) || $EnglishName == "") {
         $error = CONTROL_CONTENT_SUBDIVISION_SUBCLASS_ERROR_KEYWORD;
     } elseif (is_object($a2f) && $a2f->has_errors()) {
         $error = CONTROL_CLASS_CUSTOM_SETTINGS_HAS_ERROR . "<br>" . $a2f->get_validation_errors();
     }
 }
 // of сохранение формы
 switch ($phase) {
     case 1:
Example #7
0
/**
 * Сгенерировать имя файла для записи на диск
 *
 * @param str оригинальное имя файла
 * @param str путь к файлу
 * @param array массив строк с недопустимыми именами
 * @return str
 */
function nc_get_filename_for_original_fs($file_name, $path, $disallow = null)
{
    global $nc_core;
    $use_index = false;
    // надо ли к файлу добавлять индекс
    if (!empty($disallow) && in_array($file_name, $disallow)) {
        $use_index = true;
    }
    $file_name = nc_transliterate($file_name);
    $file_name = nc_preg_replace("/[^a-z0-9.]/is", "_", $file_name);
    if (file_exists($path . $file_name)) {
        $use_index = true;
    }
    if (!$use_index) {
        return $file_name;
    }
    $k = 0;
    $ext = substr($file_name, strrpos($file_name, "."));
    while (file_exists($path . ($temp = substr($file_name, 0, strrpos($file_name, ".")) . "_" . $k . $ext)) || in_array($temp, (array) $disallow)) {
        $k++;
    }
    $file_name = $temp;
    return $file_name;
}
Example #8
0
             // В общем случае - меняем только если прислали хотя бы одно поле
             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]));
     if ($fldType[$i] == 8 && empty($fldValue[$i])) {
         $fldValue[$i] = "NULL";
     } else {
         $fldValue[$i] = "\"" . $fldValue[$i] . "\"";
     }
 }
Example #9
0
function nc_subdivision_add()
{
    $nc_core = nc_Core::get_object();
    $db = $nc_core->db;
    $CatalogueID = intval($nc_core->input->fetch_get_post('CatalogueID'));
    $ParentSubID = intval($nc_core->input->fetch_get_post('ParentSubID'));
    $Template_ID = intval($nc_core->input->fetch_get_post('Template_ID'));
    $input = $nc_core->input->fetch_get_post();
    // проверка названия раздела
    $Subdivision_Name = trim($nc_core->input->fetch_get_post('Subdivision_Name'));
    if (!$Subdivision_Name) {
        throw new Exception(CONTROL_CONTENT_SUBDIVISION_INDEX_ERROR_THREE_NAME);
    }
    // проверка ключевого слова
    $EnglishName = trim($nc_core->input->fetch_get_post('EnglishName'));
    if (empty($EnglishName)) {
        $EnglishName = nc_transliterate($Subdivision_Name, true);
    }
    // проверка на валидность
    $EnglishName = nc_check_english_name(0, $EnglishName, 1);
    if (!$nc_core->subdivision->validate_english_name($EnglishName)) {
        throw new Exception(CONTROL_CONTENT_SUBDIVISION_SUBCLASS_ERROR_KEYWORD_INVALID);
    }
    // проверка уникальности ключевого слова
    if (!IsAllowedSubdivisionEnglishName($EnglishName, $ParentSubID, 0, $CatalogueID)) {
        throw new Exception(CONTROL_CONTENT_SUBDIVISION_INDEX_ERROR_THREE_KEYWORD);
    }
    // визуальные настройки
    $TemplateSettings = "";
    if ($_POST['is_parent_template'] == 'true') {
        $Template_ID = 0;
    }
    if ($Template_ID) {
        $settings = $nc_core->db->get_var("SELECT `CustomSettings` FROM `Template` WHERE `Template_ID` = '" . $Template_ID . "'");
        if ($settings) {
            require_once $nc_core->ADMIN_FOLDER . "array_to_form.inc.php";
            $a2f = new nc_a2f($settings, 'TemplateSettings');
            if (!$a2f->validate($_POST['TemplateSettings'])) {
                throw new Exception($a2f->get_validation_errors());
            }
            if (isset($_POST['TemplateSettings']) && !empty($_POST['TemplateSettings'])) {
                $a2f->save($_POST['TemplateSettings']);
                $TemplateSettings = $a2f->get_values_as_string();
            }
        }
    }
    // execute core action
    $nc_core->event->execute("addSubdivisionPrep", $CatalogueID, 0);
    // добавление раздела
    $db->query("\n        INSERT INTO `Subdivision`\n            SET `Created` = NOW(),\n                `Subdivision_Name` = '" . $db->escape($Subdivision_Name) . "',\n                `EnglishName` = '" . $db->escape($EnglishName) . "',\n                `Parent_Sub_ID` = '" . $ParentSubID . "',\n                `Catalogue_ID` = '" . $CatalogueID . "',\n                `Checked` = '" . intval($input['Checked']) . "',\n                `Priority` = '" . intval($input['Priority']) . "',\n                `Favorite` = '" . intval($input['Favorite']) . "',\n                `UseMultiSubClass` = 1,\n                `Template_ID` = '" . $Template_ID . "',\n                `TemplateSettings` = '" . $db->escape($TemplateSettings) . "',\n                `UseEditDesignTemplate` = '" . intval($input['UseEditDesignTemplate']) . "',\n                `DisplayType` = '" . $db->escape($nc_core->input->fetch_get_post('DisplayType')) . "'");
    if ($db->is_error) {
        throw new nc_Exception_DB_Error($db->last_query, $db->last_error);
    }
    $SubdivisionID = $db->insert_id;
    // обновим Hidden_URL
    $hidden_url = GetHiddenURL($ParentSubID);
    UpdateHiddenURL($hidden_url ? $hidden_url : "/", $ParentSubID, $CatalogueID);
    $nc_core->event->execute("addSubdivision", $CatalogueID, $SubdivisionID);
    // добавление компонента в разделе
    $Class_ID = intval($input['Class_ID']);
    $Class_Template_ID = intval($input['Class_Template_ID']);
    if ($Class_ID) {
        // визуальные настройки
        $CustomSettings = "";
        $settings_array = $db->get_var("SELECT `CustomSettingsTemplate` FROM `Class`\n      WHERE `Class_ID` = '" . ($Class_Template_ID ? $Class_Template_ID : $Class_ID) . "'");
        if ($settings_array) {
            require_once $nc_core->ADMIN_FOLDER . "array_to_form.inc.php";
            $a2f = new nc_a2f($settings_array, 'CustomSettings');
            if (!$a2f->validate($_POST['CustomSettings'])) {
                $error = $a2f->get_validation_errors();
            } else {
                $a2f->save($_POST['CustomSettings']);
                $CustomSettings = $a2f->get_values_as_string();
            }
        }
        $nc_core->event->execute("addSubClassPrep", $CatalogueID, $SubdivisionID, 0);
        $db->query("INSERT INTO `Sub_Class`\n      (`Subdivision_ID`, `Catalogue_ID`, `Class_ID`, `Sub_Class_Name`, `Checked`, `EnglishName`, `Created`, `CustomSettings`, `Class_Template_ID`)\n       VALUES\n       ('" . $SubdivisionID . "', '" . $CatalogueID . "', '" . $Class_ID . "', '" . $Subdivision_Name . "', 1, '" . $EnglishName . "',  '" . date("Y-m-d H:i:s") . "',  '" . addcslashes($CustomSettings, "'") . "', '" . $Class_Template_ID . "')");
        if ($SubClassID = $db->insert_id) {
            $nc_core->event->execute("addSubClass", $CatalogueID, $SubdivisionID, $SubClassID);
        }
    }
    return $SubdivisionID;
}