Example #1
0
 public function add($fields, $groups, $password, $add_fields = array(), $registration_code = null)
 {
     $user_table = new nc_Component(0, 3);
     if (!is_array($groups)) {
         $groups = explode(',', $groups);
     }
     $groups = array_unique(array_map('intval', $groups));
     $checked = 1;
     if (isset($add_fields['Checked'])) {
         $checked = (bool) $add_fields['Checked'];
         $checked = (int) $checked;
     }
     $add_fields['UserType'] = $this->db->escape($add_fields['UserType']);
     $insert_fields = array('`Password`', '`Created`', '`Checked`', '`PermissionGroup_ID`', 'UserType');
     $insert_values = array($this->core->MYSQL_ENCRYPT . '("' . $password . '")', "'" . date("Y-m-d H:i:s") . "'", $checked, min($groups), "'" . $add_fields['UserType'] . "'");
     if ($registration_code) {
         $insert_fields[] = '`RegistrationCode`';
         $insert_values[] = "'" . $this->db->escape($registration_code) . "'";
     }
     $user_fields = $user_table->get_fields();
     if (!empty($user_fields)) {
         foreach ($user_fields as $v) {
             if (isset($fields[$v['name']]) && $v['type'] != NC_FIELDTYPE_FILE) {
                 $insert_fields[] = "`" . $this->db->escape($v['name']) . "`";
                 $insert_values[] = "'" . $this->db->escape($fields[$v['name']]) . "'";
             }
             if (isset($fields[$v['name']]) && $v['type'] == NC_FIELDTYPE_FILE) {
                 $user_file[$v['id']] = array('path' => $fields[$v['name']]);
             }
         }
     }
     $this->db->query("INSERT INTO `User`(" . join(',', $insert_fields) . ") VALUES (" . join(',', $insert_values) . ") ");
     if ($this->db->is_error) {
         throw new nc_Exception_DB_Error($this->db->last_query, $this->db->last_error);
     }
     $user_id = $this->db->insert_id;
     foreach ($groups as $group_id) {
         $this->db->query("INSERT INTO `User_Group` (`User_ID`, `PermissionGroup_ID`) VALUES ('" . $user_id . "','" . $group_id . "') ");
     }
     if (!empty($user_file)) {
         foreach ($user_file as $field_id => $v) {
             $v['name'] = substr($v['path'], strrpos($v['path'], '/') + 1);
             $this->core->files->save_file('User', $field_id, $user_id, $v);
         }
     }
     return $user_id;
 }
Example #2
0
             echo sprintf(CONTROL_CLASS_CLASSFORM_CHECK_ERROR, CONTROL_CLASS_CLASS_OBJECTSLIST_SHOWOBJ_SYSTEM);
         }
     }
     $nc_parent_field_path = null;
     $nc_field_path = null;
 } else {
     if ($cc_env["Settings"]) {
         eval($cc_env["Settings"]);
     }
 }
 // cache eval section
 if (nc_module_check_by_keyword("cache") && $current_cc['Cache_Access_ID'] == 1 && is_object($nc_cache_full) && $cached_eval && $cached_result != -1) {
     eval("echo \"" . $cached_data . "\";");
     break;
 }
 $component = new nc_Component($classID, $cc_env['System_Table_ID']);
 $component->make_query();
 $field_vars = $component->get_fields_vars();
 $date_field = $component->get_date_field();
 $cond_date = false;
 if (!$ignore_user) {
     $cond_user = "******" . (int) $AUTH_USER_ID . "'";
 }
 if (!$admin_mode && !$ignore_check) {
     $cond_mod = " AND a.`Checked` = 1";
 }
 if ($date) {
     $cond_date = " AND a.`" . $date_field . "` LIKE '" . $db->escape($date) . "%'";
 }
 // ignore section
 if (!$ignore_sub && !$user_table_mode) {
Example #3
0
function ActionTemplateCompleted($type, $File_Mode)
{
    global $nc_core, $db, $ROOT_FOLDER, $FILES_FOLDER;
    global $systemTableID, $systemTableName, $systemMessageID;
    global $loc, $perm, $admin_mode;
    global $INCLUDE_FOLDER;
    global $FILECHMOD, $DIRCHMOD;
    if ($File_Mode) {
        $template_editor = new nc_template_editor($nc_core->TEMPLATE_FOLDER, $nc_core->db);
    }
    require_once $INCLUDE_FOLDER . "s_files.inc.php";
    $is_there_any_files = getFileCount(0, $systemTableID);
    $params = array('TemplateID', 'ParentTemplateID', 'Description', 'Settings', 'Header', 'Footer', 'CustomSettings', 'posting');
    foreach ($params as $v) {
        global ${$v};
    }
    $st = new nc_Component(0, 4);
    foreach ($st->get_fields() as $v) {
        $name = 'f_' . $v['name'];
        global ${$name};
        if ($v['type'] == 6) {
            global ${$name . "_old"};
            global ${"f_KILL" . $v['id']};
        }
    }
    $action = $type == 1 ? "add" : "change";
    $message = $TemplateID;
    require $ROOT_FOLDER . "message_fields.php";
    require $ROOT_FOLDER . "message_put.php";
    //  ADD template
    if ($type == 1) {
        if ($File_Mode) {
            $fields = array('Settings' => $Settings, 'Header' => $Header, 'Footer' => $Footer);
            $Settings = $Header = $Footer = '';
            if (!is_writable($nc_core->TEMPLATE_FOLDER)) {
                nc_print_status(NETCAT_CAN_NOT_WRITE_FILE, 'error');
                return false;
            }
        }
        $insert = "INSERT INTO `Template` (";
        for ($i = 0; $i < $fldCount; $i++) {
            $insert .= $fld[$i] . ",";
        }
        $insert .= "`Description`, `Parent_Template_ID`, `Settings`, `Header`, `Footer`, `CustomSettings`) ";
        $insert .= "VALUES (";
        for ($i = 0; $i < $fldCount; $i++) {
            if (isset(${$fld[$i] . 'Defined'}) && ${$fld[$i] . 'Defined'} == true) {
                $insert .= ${$fld[$i] . 'NewValue'} . ",";
            } else {
                $insert .= $fldValue[$i] . ",";
            }
        }
        $insert .= "'" . $Description . "'," . $ParentTemplateID . ", '" . $Settings . "', '" . $Header . "', '" . $Footer . "', '" . $CustomSettings . "')";
        $nc_core->event->execute("addTemplatePrep", 0);
        $Result = $db->query($insert);
        $message = $db->insert_id;
        if ($File_Mode) {
            if ($ParentTemplateID) {
                $template_editor->load_template($ParentTemplateID);
                $template_editor->load_new_child($message);
            } else {
                $template_editor->load_template($message, "/{$message}/");
            }
            $template_editor->save_new_template(array_map('stripslashes', $fields), $ParentTemplateID ? true : false);
        }
        $nc_core->event->execute("addTemplate", $message);
        // EDIT template
    } else {
        if ($File_Mode) {
            $template_editor->load_template($TemplateID);
            $template_editor->save_fields(array_map('stripslashes', array('Settings' => $Settings, 'Header' => $Header, 'Footer' => $Footer)));
            $Settings = $Header = $Footer = '';
        }
        $update = "UPDATE `Template` SET ";
        for ($i = 0; $i < $fldCount; $i++) {
            if (isset(${$fld[$i] . 'Defined'}) && ${$fld[$i] . 'Defined'} == true) {
                $update .= $fld[$i] . "=" . ${$fld[$i] . 'NewValue'} . ",";
            } else {
                $update .= $fld[$i] . "=" . $fldValue[$i] . ",";
            }
        }
        $update .= "Description='" . $Description . "',";
        $update .= "Settings='" . $Settings . "',";
        $update .= "Header='" . $Header . "',";
        $update .= "Footer='" . $Footer . "',";
        $update .= "CustomSettings='" . $CustomSettings . "'";
        $update .= " where Template_ID=" . $TemplateID;
        $message = $TemplateID;
        // execute core action
        $nc_core->event->execute("updateTemplatePrep", $message);
        $Result = $db->query($update);
        // execute core action
        $nc_core->event->execute("updateTemplate", $message);
    }
    // Обновление в таблице с файлами
    if (!empty($filetable_lastid)) {
        $db->query("UPDATE `Filetable` SET `Message_ID`='" . $message . "' WHERE ID IN (" . join(',', $filetable_lastid) . ")");
    }
    @mkdir($FILES_FOLDER . "t/", $DIRCHMOD);
    for ($i = 0; $i < count($tmpFile); $i++) {
        eval("\$tmpNewFile[\$i] = \"" . $tmpNewFile[$i] . "\";");
        @rename($FILES_FOLDER . $tmpFile[$i], $FILES_FOLDER . $File_Path[$i] . $tmpNewFile[$i]);
        @chmod($FILES_FOLDER . $File_Path[$i] . $tmpNewFile[$i], $FILECHMOD);
    }
    if ($posting == 0) {
        echo $warnText;
        TemplateForm($TemplateID, $phase, $type, $File_Mode);
        return false;
    }
    return $message;
}
Example #4
0
function nc_admin_select_field($table, $disc, $name, $value = '')
{
    $c = new nc_Component(0, 3);
    $fields = $c->get_fields();
    if (is_array($value)) {
        $value = $value[$name];
    }
    $res = "<div style='margin:5px 0; _padding:0;'>" . $disc . " ";
    if (!empty($fields)) {
        $res .= "<select class='chosen-select' name='" . $name . "'>\n";
        foreach ($fields as $v) {
            $res .= "\t<option value='" . $v['name'] . "' " . ($value == $v['name'] ? "selected='selected'" : "") . ">" . $v['description'] . "</option>\n";
        }
        $res .= "</select>\n";
    }
    $res .= "</div>";
    return $res;
}
Example #5
0
/**
 * Вывод поля типа "Число с плавающей запятой" в альтернативных формах шаблона
 * @param string имя поля
 * @param string дополнительные свойства для <input ...>
 * @param int идентификатор компонента, его стоит указывать при вызове функции т.к. в функции s_list_class() его глобальное значение будет иное
 * @param bool выводить описание поля или нет
 * @return string
 */
function nc_float_field($field_name, $style = "", $classID = "", $caption = false, $value = null)
{
    // для получения значения поля
    global $fldValue, $fldID, $systemTableID;
    $nc_core = nc_Core::get_object();
    // текущее значение компонента
    if (!$classID) {
        $classID = $nc_core->sub_class->get_current('Class_ID');
    }
    $show_field_errors = $classID == $nc_core->sub_class->get_current('Class_ID');
    $sysTable = $systemTableID ? $systemTableID : $nc_core->component->get_by_id($classID, 'System_Table_ID');
    $component = new nc_Component($classID, $sysTable);
    $fields = $component->get_fields(NC_FIELDTYPE_FLOAT);
    // поиск поля
    $field = 0;
    foreach ($fields as $v) {
        if ($v['name'] == $field_name) {
            $field = $v;
        }
    }
    // поля не существует
    if (!$field) {
        if ($show_field_errors) {
            trigger_error("<b>nc_float_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);
    }
    # если поле обязательно для заполнения
    if ($value == NULL && $field['default'] != NULL) {
        $value = $field['default'];
    }
    # проверим, есть ли в параметре "style", атрибуты
    $style_attr = nc_reg_search_html_attr($style);
    # прописываем параметры из $style
    $style_opt = "";
    if (!in_array("maxlength", $style_attr)) {
        $style_opt .= "maxlength='12'";
    }
    if (!in_array("size", $style_attr)) {
        $style_opt .= ($style_opt ? " " : "") . "size='12'";
    }
    if (!in_array("type", $style_attr)) {
        $style_opt .= ($style_opt ? " " : "") . "type='text'";
    }
    if ($style_opt) {
        $style_opt = " " . $style_opt;
    }
    $result .= "<input name='f_" . $field_name . "'" . $style_opt . ($style ? " " . $style : "") . " value='" . $value . "' />";
    //$result .= nc_field_validation('input', 'f_'.$field_name, $field['id'], 'float', $field['not_null']);
    return $result;
}
Example #6
0
 if (!$alter_goBackLink_true) {
     if ($admin_mode) {
         $goBackLink = $admin_url_prefix . "?catalogue=" . $catalogue . "&sub=" . $sub . "&cc=" . $cc . "&curPos=" . $curPos;
     } else {
         $goBackLink = ($user_table_mode ? nc_folder_url($current_sub['Subdivision_ID']) : nc_infoblock_url($current_cc['Sub_Class_ID'])) . ($curPos ? "?curPos=" . $curPos : "");
     }
 } else {
     $goBackLink = $alter_goBackLink;
 }
 $goBack = "<a href=" . $goBackLink . ">" . NETCAT_MODERATION_BACKTOSECTION . "</a>";
 // визуальные настройки
 $cc_settings = nc_get_visual_settings($cc);
 // удаление или включение/выключение одного объекта
 // нужно загрузить все данные полей
 if (($delete || $checked) && $message && !is_array($message) && $posting) {
     $component = new nc_Component($classID, $user_table_mode ? 3 : 0);
     $component->make_query();
     $field_names = $component->get_fields_query();
     $field_vars = $component->get_fields_vars();
     $multilist_fileds = $component->get_fields(10);
     //$date_field = $component->get_date_field(); #not used
     $message_select = "\n            SELECT  " . $field_names . "\n            FROM (" . ($user_table_mode ? "`User`" : "`Message" . $classID . "`") . " AS a )" . $component->get_joins() . "\n            WHERE  " . ($user_table_mode ? "a.`User_ID`" : "a.`Message_ID`") . " = '" . (int) $message . "'";
     eval("list(" . $field_vars . ") = \$db->get_row(\$message_select, ARRAY_N);");
     // Multiselect
     $multilist_fileds = $component->get_fields(10);
     if (!empty($multilist_fileds)) {
         // просмотр каждого поля типа multiselect
         foreach ($multilist_fileds as $multilist_filed) {
             // таблицу с элементами можно взять их кэша, если ее там нет - то добавить
             if (!$_cache['classificator'][$multilist_filed['table']]) {
                 $db_res = $db->get_results("SELECT `" . $multilist_filed['table'] . "_ID` AS ID, `" . $multilist_filed['table'] . "_Name` AS Name, `Value`\n                                     FROM `Classificator_" . $multilist_filed['table'] . "`", ARRAY_A);
Example #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;
 }
Example #8
0
function ActionCatalogueCompleted($CatalogueID, $type)
{
    global $nc_core, $db, $ROOT_FOLDER, $admin_mode;
    global $systemTableID, $systemTableName;
    global $FILES_FOLDER, $INCLUDE_FOLDER;
    global $FILECHMOD, $DIRCHMOD, $ADMIN_FOLDER, $MODULE_FOLDER;
    global $CatalogueID;
    if (isset($_POST['nc_shop_mode_' . $CatalogueID]) && +$_POST['nc_shop_mode_' . $CatalogueID] != $nc_core->get_settings('nc_shop_mode_' . $CatalogueID)) {
        $nc_core->set_settings('nc_shop_mode_' . $CatalogueID, +$_POST['nc_shop_mode_' . $CatalogueID]);
    }
    require_once $INCLUDE_FOLDER . "s_files.inc.php";
    $is_there_any_files = getFileCount(0, $systemTableID);
    $lm_type = $nc_core->page->get_field_name('last_modified_type');
    if ($type == 1) {
        $action = "add";
    }
    if ($type == 2) {
        $CatalogueID = intval($CatalogueID);
        $action = "change";
        $message = $CatalogueID;
    }
    $sm_field = $nc_core->page->get_field_name('sitemap_include');
    $sm_change_field = $nc_core->page->get_field_name('sitemap_changefreq');
    $sm_priority_field = $nc_core->page->get_field_name('sitemap_priority');
    $params = array('Catalogue_Name', 'Domain', 'Template_ID', 'Read_Access_ID', 'Write_Access_ID', 'Edit_Access_ID', 'Subscribe_Access_ID', 'Checked_Access_ID', 'Delete_Access_ID', 'Moderation_ID', 'Checked', 'Priority', 'Mirrors', 'Robots', 'Cache_Access_ID', 'Cache_Lifetime', 'TitleSubIDName', 'DisplayType', 'TitleSubIDKeyword', 'TitleTemplateID', 'E404SubIDName', 'E404SubIDKeyword', 'TitleSubID', 'E404SubID', 'E404TemplateID', 'CommentsEditRules', 'CommentAccessID', 'CommentsDeleteRules', 'posting', 'last_modified_type', 'DisallowIndexing', 'ncOfflineText', 'ncMobile', 'ncMobileSrc', 'ncMobileRedirect', 'ncMobileIdentity');
    if ($nc_core->modules->get_by_keyword('search')) {
        $params = array_merge($params, array($sm_field, $sm_change_field, $sm_priority_field));
    }
    foreach ($params as $v) {
        global ${$v};
    }
    $st = new nc_Component(0, 1);
    foreach ($st->get_fields() as $v) {
        $name = 'f_' . $v['name'];
        global ${$name};
        if ($v['type'] == 6) {
            global ${$name . "_old"};
            global ${"f_KILL" . $v['id']};
        }
        if ($v['type'] == 8) {
            global ${$name . "_day"};
            global ${$name . "_month"};
            global ${$name . "_year"};
            global ${$name . "_hours"};
            global ${$name . "_minutes"};
            global ${$name . "_seconds"};
        }
    }
    $Checked = intval($Checked);
    $Mirrors = str_replace(array("http://", "https://", "/"), "", $Mirrors);
    $Priority += 0;
    $Template_ID = intval($Template_ID);
    $posting = 1;
    // prepare template custom settings
    $settings = $db->get_var("SELECT CustomSettings FROM Template WHERE Template_ID = '" . $Template_ID . "'");
    if ($settings) {
        require_once $ADMIN_FOLDER . "array_to_form.inc.php";
        $a2f = new nc_a2f($settings, 'TemplateSettings');
        if ($a2f->has_errors()) {
            $warnText = $a2f->get_validation_errors();
            $posting = 0;
        }
        $a2f->save($_POST['TemplateSettings']);
        $TemplateSettings = $a2f->get_values_as_string();
        $TemplateSettings = addcslashes($TemplateSettings, "'");
    } else {
        $TemplateSettings = "";
    }
    require $ROOT_FOLDER . "message_fields.php";
    if ($posting == 0) {
        nc_print_status($warnText, 'error');
        CatalogueForm($CatalogueID, 3, "index.php", $type, $action);
        return false;
    }
    require $ROOT_FOLDER . "message_put.php";
    if (nc_module_check_by_keyword("comments")) {
        include_once $MODULE_FOLDER . "comments/function.inc.php";
    }
    switch ($ncMobile) {
        case 2:
            $ncMobile = 0;
            $ncResponsive = 1;
            break;
        case 1:
            $ncMobile = 1;
            $ncResponsive = 0;
            break;
        default:
            $ncMobile = 0;
            $ncResponsive = 0;
            break;
    }
    if ($type == 1) {
        $insert = "INSERT INTO `Catalogue` (";
        for ($i = 0; $i < $fldCount; $i++) {
            if ($fldTypeOfEdit[$i] == 3) {
                continue;
            }
            $insert .= $fld[$i] . ",";
        }
        if (nc_module_check_by_keyword("cache")) {
            $insert .= "`Cache_Access_ID`, `Cache_Lifetime`,";
        }
        $insert .= "`Catalogue_Name`, `Domain`, `" . $nc_core->page->get_field_name('language') . "`, `Template_ID`,  `Read_Access_ID`, `Write_Access_ID`, `Edit_Access_ID`, `Checked_Access_ID`, `Delete_Access_ID`, `Subscribe_Access_ID`, `Moderation_ID`, `Checked`, `Priority`, `Created`, `Mirrors`, `Robots`, `" . $lm_type . "`, `TemplateSettings` , `ncOfflineText`, `ncMobile`, `ncMobileSrc`, `ncMobileRedirect`, `ncMobileIdentity`, `ncResponsive`) ";
        $insert .= "VALUES (";
        for ($i = 0; $i < $fldCount; $i++) {
            if ($fldTypeOfEdit[$i] == 3 || $fldTypeOfEdit[$i] == 2 && !nc_field_check_admin_perm()) {
                continue;
            }
            // поле недоступно никому или доступно администратору но нет прав администратора
            if (isset(${$fld[$i] . 'Defined'}) && ${$fld[$i] . 'Defined'} == true) {
                $insert .= ${$fld[$i] . 'NewValue'} . ",";
            } else {
                $insert .= $fldValue[$i] . ",";
            }
        }
        if (nc_module_check_by_keyword("cache")) {
            $insert .= "'" . intval($Cache_Access_ID) . "',";
            $insert .= "'" . intval($Cache_Lifetime) . "',";
        }
        $insert .= "'" . $db->escape($Catalogue_Name) . "',";
        $insert .= "'" . $db->escape($Domain) . "',";
        $insert .= "'" . $db->escape($nc_core->input->fetch_get_post('language') != '' ? $nc_core->input->fetch_get_post('language') : MAIN_LANG) . "',";
        $insert .= "'" . $db->escape($Template_ID) . "',";
        $insert .= "'" . intval($Read_Access_ID) . "',";
        $insert .= "'" . intval($Write_Access_ID) . "',";
        $insert .= "'" . intval($Edit_Access_ID) . "',";
        $insert .= "'" . intval($Checked_Access_ID) . "',";
        $insert .= "'" . intval($Delete_Access_ID) . "',";
        $insert .= "'" . intval($Subscribe_Access_ID) . "',";
        $insert .= "'" . intval($Moderation_ID) . "',";
        $insert .= "'" . intval($Checked) . "',";
        $insert .= "'" . intval($Priority) . "',";
        $insert .= "'" . date("Y-m-d H:i:s") . "',";
        $insert .= "'" . $db->escape($Mirrors) . "',";
        $insert .= "'" . $db->escape($Robots) . "',";
        $insert .= "'" . intval($last_modified_type) . "',";
        $insert .= "'" . $db->escape($TemplateSettings) . "',";
        $insert .= "'" . $db->escape($ncOfflineText) . "',";
        $insert .= "'" . intval($ncMobile) . "',";
        $insert .= "'" . intval($ncMobileSrc) . "',";
        $insert .= "'" . intval($ncMobileRedirect) . "',";
        $insert .= "'" . intval($ncMobileIdentity) . "',";
        $insert .= "'" . intval($ncResponsive) . "'";
        $insert .= ")";
        // execute core action
        $nc_core->event->execute("addCataloguePrep", 0);
        $db->query($insert);
        if ($db->is_error) {
            throw new nc_Exception_DB_Error($db->last_query, $db->last_error);
        }
        $CatalogueID = $db->insert_id;
        // execute core action
        $nc_core->event->execute("addCatalogue", $CatalogueID);
        $message = $CatalogueID;
        if (nc_module_check_by_keyword("comments")) {
            if ($CommentAccessID > 0) {
                // add comment relation
                $CommentRelationID = nc_comments::addRule($db, array($message), $CommentAccessID, $CommentsEditRules, $CommentsDeleteRules);
                // update inserted data
                $db->query("UPDATE `Catalogue` SET `Comment_Rule_ID` = '" . (int) $CommentRelationID . "' WHERE `Catalogue_ID` = '" . (int) $message . "'");
            }
        }
        // проверка названия раздела
        if (!$TitleSubIDName || !$E404SubIDName) {
            nc_print_status(CONTROL_CONTENT_SUBDIVISION_INDEX_ERROR_THREE_NAME, 'error');
            return false;
        }
        // проверка символов для ключевого слова
        if (!$nc_core->subdivision->validate_hidden_url($TitleSubIDKeyword) || !$nc_core->subdivision->validate_hidden_url($E404SubIDKeyword)) {
            nc_print_status(CONTROL_CONTENT_SUBDIVISION_SUBCLASS_ERROR_KEYWORD_INVALID, 'error');
            return false;
        }
        // execute core action
        $nc_core->event->execute("addSubdivisionPrep", $CatalogueID, 0);
        // Добавление раздела для титульной страницы
        $db->query("INSERT INTO `Subdivision`\n      SET `Catalogue_ID` = '" . intval($CatalogueID) . "',\n      `Parent_Sub_ID` = 0,\n      `Subdivision_Name` = '" . $db->escape($TitleSubIDName) . "',\n      `Template_ID` = '" . intval($TitleTemplateID) . "',\n      `Checked` = 0,\n      `EnglishName` = '" . $db->escape($TitleSubIDKeyword) . "',\n      `Hidden_URL` = '/" . $db->escape($TitleSubIDKeyword) . "/',\n      `Priority` = 0");
        $title_sub_id = $db->insert_id;
        // execute core action
        $nc_core->event->execute("addSubdivision", $CatalogueID, $title_sub_id);
        // execute core action
        $nc_core->event->execute("addSubdivisionPrep", $CatalogueID, 0);
        // Добавление раздела для титульной страницы
        $db->query("INSERT INTO `Subdivision`\n      SET `Catalogue_ID` = '" . $CatalogueID . "',\n      `Parent_Sub_ID` = 0,\n      `Subdivision_Name` = '" . $db->escape($E404SubIDName) . "',\n      `Template_ID` = '" . intval($E404TemplateID) . "',\n      `Checked` = 0,\n      `EnglishName` = '" . $db->escape($E404SubIDKeyword) . "',\n      `Hidden_URL` = '/" . $db->escape($E404SubIDKeyword) . "/',\n      `Priority` = 1");
        $e404_sub_id = $db->insert_id;
        // execute core action
        $nc_core->event->execute("addSubdivision", $CatalogueID, $e404_sub_id);
        // для этого апдейта не нужно вызывать трансляцию события
        $db->query("UPDATE `Catalogue` SET `Title_Sub_ID` = '" . $title_sub_id . "', `E404_Sub_ID` = '" . $e404_sub_id . "' WHERE `Catalogue_ID` = '" . $CatalogueID . "'");
        //добавление системной настройки режима работы магазина.
        if (nc_module_check_by_keyword("netshop")) {
            $db->query("INSERT INTO `Settings` (`Key`, `Value`, `Module`, `Catalogue_ID`) VALUES ('nc_shop_mode_" . $CatalogueID . "', '2', 'system', '0')");
        }
    }
    if ($type == 2) {
        $cur_checked = $db->get_var("SELECT `Checked` FROM `Catalogue` WHERE `Catalogue_ID` = '" . $CatalogueID . "'");
        if (nc_module_check_by_keyword("comments")) {
            // get rule id
            $CommentData = nc_comments::getRuleData($db, array($CatalogueID));
            $CommentRelationID = $CommentData['ID'];
            // do something
            switch (true) {
                case $CommentAccessID > 0 && $CommentRelationID:
                    // update comment rules
                    nc_comments::updateRule($db, array($CatalogueID), $CommentAccessID, $CommentsEditRules, $CommentsDeleteRules);
                    break;
                case $CommentAccessID > 0 && !$CommentRelationID:
                    // add comment relation
                    $CommentRelationID = nc_comments::addRule($db, array($CatalogueID), $CommentAccessID, $CommentsEditRules, $CommentsDeleteRules);
                    break;
                case $CommentAccessID <= 0 && $CommentRelationID:
                    // delete comment rules
                    nc_comments::dropRuleCatalogue($db, $CatalogueID);
                    $CommentRelationID = 0;
                    break;
            }
        }
        $update = " UPDATE `Catalogue` SET ";
        for ($i = 0; $i < $fldCount; $i++) {
            if ($fldTypeOfEdit[$i] == 3) {
                continue;
            }
            // поле недоступно никому
            if (isset(${$fld[$i] . 'Defined'}) && ${$fld[$i] . 'Defined'} == true) {
                $update .= $fld[$i] . "=" . ${$fld[$i] . 'NewValue'} . ",";
            } else {
                $update .= $fld[$i] . "=" . $fldValue[$i] . ",";
            }
        }
        $update .= "`Catalogue_Name` = '" . $db->escape($Catalogue_Name) . "',";
        $update .= "`Domain` = '" . $db->escape($Domain) . "',";
        $update .= "`Template_ID` = " . intval($Template_ID) . ",";
        $update .= "`Read_Access_ID` = '" . intval($Read_Access_ID) . "',";
        $update .= "`Write_Access_ID` = '" . intval($Write_Access_ID) . "',";
        $update .= "`Edit_Access_ID` = '" . intval($Edit_Access_ID) . "',";
        $update .= "`Checked_Access_ID` = '" . intval($Checked_Access_ID) . "',";
        $update .= "`Delete_Access_ID` = '" . intval($Delete_Access_ID) . "',";
        $update .= "`Subscribe_Access_ID` = '" . intval($Subscribe_Access_ID) . "',";
        if (nc_module_check_by_keyword("cache")) {
            $update .= "`Cache_Access_ID` = '" . intval($Cache_Access_ID) . "',";
            $update .= "`Cache_Lifetime` = '" . intval($Cache_Lifetime) . "',";
        }
        if (nc_module_check_by_keyword("comments")) {
            $update .= "`Comment_Rule_ID` = '" . intval($CommentRelationID) . "',";
        }
        $update .= "`Moderation_ID` = '" . intval($Moderation_ID) . "',";
        $update .= "`Checked` = '" . intval($Checked) . "',";
        $update .= "`Priority` = '" . intval($Priority) . "',";
        $update .= "`Mirrors` = '" . $db->escape($Mirrors) . "',";
        $update .= "`Robots` = '" . $db->escape($Robots) . "',";
        $update .= "`Title_Sub_ID` = '" . intval($TitleSubID) . "',";
        $update .= "`E404_Sub_ID` = '" . intval($E404SubID) . "',";
        $update .= "`" . $lm_type . "` = '" . intval($last_modified_type) . "',";
        $update .= "`DisallowIndexing`= '" . intval($DisallowIndexing) . "',";
        $update .= "`" . $nc_core->page->get_field_name('language') . "` = '" . $nc_core->input->fetch_get_post('language') . "',";
        if ($nc_core->modules->get_by_keyword('search')) {
            $update .= "`" . $sm_field . "` = '" . $nc_core->input->fetch_get_post('sitemap_include') . "',";
            $update .= "`" . $sm_change_field . "` = '" . $nc_core->input->fetch_get_post('sitemap_changefreq') . "',";
            $update .= "`" . $sm_priority_field . "` = '" . str_replace(',', '.', sprintf("%.1f", doubleval($nc_core->input->fetch_get_post('sitemap_priority')))) . "',";
        }
        $update .= "`TemplateSettings` = '" . $db->escape($TemplateSettings) . "',";
        $update .= "`ncOfflineText` = '" . $db->escape($ncOfflineText) . "',";
        $update .= "`ncMobile` = '" . intval($ncMobile) . "',";
        $update .= "`ncMobileSrc` = '" . intval($ncMobileSrc) . "',";
        $update .= "`ncMobileRedirect` = '" . intval($ncMobileRedirect) . "',";
        $update .= "`ncMobileIdentity` = '" . intval($ncMobileIdentity) . "',";
        $update .= "`ncResponsive` = '" . intval($ncResponsive) . "',";
        $update .= "`DisplayType` = '" . $db->escape($DisplayType) . "'";
        $update .= " WHERE `Catalogue_ID` = " . $CatalogueID;
        // execute core action
        $nc_core->event->execute("updateCataloguePrep", $CatalogueID);
        if ($cur_checked != $Checked) {
            $nc_core->event->execute($Checked ? "checkCataloguePrep" : "uncheckCataloguePrep", $CatalogueID);
        }
        $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("updateCatalogue", $CatalogueID);
        // произошло включение / выключение
        if ($cur_checked != $Checked) {
            $nc_core->event->execute($Checked ? "checkCatalogue" : "uncheckCatalogue", $CatalogueID);
        }
    }
    /*     * */
    if (is_array($filetable_lastid) && !empty($filetable_lastid)) {
        foreach ($filetable_lastid as $id) {
            $db->query("UPDATE `Filetable` SET `Message_ID` = '" . $message . "' WHERE `ID` = '" . intval($id) . "'");
        }
    }
    /*     * */
    if ($tmpFile) {
        @mkdir($FILES_FOLDER . "c/", $DIRCHMOD);
    }
    for ($i = 0; $i < count($tmpFile); $i++) {
        eval("\$tmpNewFile[\$i] = \"" . $tmpNewFile[$i] . "\";");
        if ($FileFS[$i] == NC_FS_PROTECTED || $FileFS[$i] == NC_FS_ORIGINAL) {
            @rename($nc_core->FILES_FOLDER . $tmpNewFile[$i], $nc_core->FILES_FOLDER . $File_PathNew[$i] . $tmpNewFile[$i]);
        } else {
            @rename($nc_core->FILES_FOLDER . $tmpFile[$i], $nc_core->FILES_FOLDER . $File_Path[$i] . $tmpNewFile[$i]);
        }
        @chmod($FILES_FOLDER . "c/" . $tmpNewFile[$i], $FILECHMOD);
    }
    // сброс
    $nc_core->catalogue->load_all();
    return true;
}
Example #9
0
 public function recovery($trash_ids)
 {
     // Приводим все к массиву
     if (!is_array($trash_ids)) {
         $trash_ids = array($trash_ids);
     }
     $trash_ids = array_map('intval', $trash_ids);
     $db = $this->db;
     $TRASH_FOLDER = $this->core->TRASH_FOLDER;
     $comment_insert_value = array();
     $recovered = 0;
     $trashed_objects = $db->get_results("\n    SELECT `Trash_ID`, `Type`, `Message_ID`, `Class_ID`, `Subdivision_ID`, `Sub_Class_ID`,\n    `System_Table_ID`, `Created`, `XML_Filename`, `XML_Filesize`, `IP`, `UserAgent`, `User_ID`\n    FROM `Trash_Data`\n    WHERE `Trash_ID` IN (" . join(', ', $trash_ids) . ")", ARRAY_A);
     if (!$trashed_objects) {
         return 0;
     }
     if ($trashed_objects[0]['Type'] == self::TYPE_COMMENT) {
         return $this->recovery_comment($trash_ids);
     }
     // узнаем номера всех компонентов и файлов, а так же различные связки
     $class_ids = array();
     $xml_filepaths = array();
     $class_file = array();
     // связь между компонентом  и файлом
     $message_file = array();
     // все объект, находящиеся в данном файле
     foreach ($trashed_objects as $v) {
         $class_ids[] = $v['Class_ID'];
         $filepath = $this->xml_file_name($v);
         $xml_filepaths[] = $filepath;
         $class_file[$filepath] = $v['Class_ID'];
         $message_file[$filepath][] = $v['Message_ID'];
     }
     $class_ids = array_unique($class_ids);
     $xml_filepaths = array_unique($xml_filepaths);
     // получаем все поля каждого компонента
     $fields = array();
     foreach ($class_ids as $class_id) {
         $component = new nc_Component($class_id);
         $fields[$class_id] = $component->get_fields(0, 0);
         unset($component);
     }
     $sys_fields = array('Message_ID', 'User_ID', 'Subdivision_ID', 'Sub_Class_ID', 'Priority', 'Checked', 'IP', 'UserAgent', 'Parent_Message_ID', 'Created', 'LastUpdated', 'LastUser_ID', 'LastIP', 'LastUserAgent', 'Keyword');
     // открываем каждый файл, ищем нужные объекты
     foreach ($xml_filepaths as $xml_filepath) {
         $doc = new DOMDocument('1.0', 'utf-8');
         $doc->load($this->core->TRASH_FOLDER . $xml_filepath);
         $xpath = new DOMXPath($doc);
         $class_id = $class_file[$xml_filepath];
         //смотрим поля на момент удаления
         $del_fields = array();
         $fields_node = $doc->getElementsByTagName('fields')->item(0);
         foreach ($fields_node->childNodes as $field_node) {
             if ($field_node->childNodes) {
                 foreach ($field_node->childNodes as $v) {
                     if ($v->nodeName == 'Field_Name') {
                         $del_fields[] = $v->nodeValue;
                     }
                 }
             }
         }
         // поля, которые будем восстанавливать
         $r_fields = array_intersect($del_fields, $fields[$class_id]);
         $r_fields = array_merge($r_fields, $sys_fields);
         // ищем каждый восстанавливаемый объект в файле
         foreach ($message_file[$xml_filepath] as $id) {
             $node = $xpath->query("/netcatml/messages/message[@message_id='" . $id . "']");
             $node = $node->item(0);
             if (!is_object($node)) {
                 continue;
             }
             $cc_id = intval($node->getAttribute('sub_class_id'));
             $set_value = array();
             $set_value[] = " `Message_ID` = '" . intval($node->getAttribute('message_id')) . "' ";
             $set_value[] = " `Subdivision_ID` = '" . intval($node->getAttribute('subdivision_id')) . "' ";
             $set_value[] = " `Sub_Class_ID` = '" . intval($cc_id) . "' ";
             foreach ($node->childNodes as $v) {
                 if (!in_array($v->nodeName, $r_fields)) {
                     continue;
                 }
                 $set_value[] = " `" . $db->escape($v->nodeName) . "` = '" . $db->escape($v->nodeValue) . "' ";
             }
             $db->query("INSERT INTO `Message" . $class_id . "` SET " . $this->encode_to_system(join(',', $set_value)));
             $recovered++;
             $comments = $xpath->query("/netcatml/comments/comment[@message_id='" . $id . "' and @sub_class_id='" . $cc_id . "']");
             if ($comments) {
                 foreach ($comments as $comment) {
                     $comment_id = intval($comment->getAttribute('comment_id'));
                     $parent_comment_id = intval($comment->getAttribute('parent_comment_id'));
                     foreach ($comment->childNodes as $v) {
                         if ($v->nodeName == 'Comment') {
                             $text = $db->escape($v->nodeValue);
                         }
                         if ($v->nodeName == 'User_ID') {
                             $comment_user_id = intval($v->nodeValue);
                         }
                         if ($v->nodeName == 'Date') {
                             $comment_date = $db->escape($v->nodeValue);
                         }
                         if ($v->nodeName == 'Updated') {
                             $comment_updated = $db->escape($v->nodeValue);
                         }
                     }
                     $comment_insert_value[] = "('" . $comment_id . "', '" . $parent_comment_id . "', '" . $comment_user_id . "',\n                              '" . $text . "', '" . $comment_date . "', '" . $comment_updated . "',\n                              '" . $cc_id . "', '" . $id . "' )";
                     $comment->parentNode->removeChild($comment);
                 }
             }
             $node->parentNode->removeChild($node);
             $doc->save($this->core->TRASH_FOLDER . $xml_filepath);
         }
         unset($xpath, $doc);
     }
     if ($this->core->modules->get_by_keyword('comments')) {
         if (!empty($comment_insert_value)) {
             $db->query("INSERT INTO `Comments_Text` (`id`,`Parent_Comment_ID`,`User_ID`,`Comment`,\n                                                 `Date`,`Updated`,`Sub_Class_ID`, `Message_ID`)\n                    VALUES " . $this->encode_to_system(join(',', $comment_insert_value)));
             require_once $this->core->MODULE_FOLDER . "comments/nc_comments_admin.class.php";
             $nc_comments_admin = new nc_comments_admin();
             $nc_comments_admin->optimizeSave();
         }
     }
     $db->query("DELETE FROM `Trash_Data` WHERE `Trash_ID` IN (" . join(', ', $trash_ids) . ")");
     $this->remove_xml_files($xml_filepaths);
     return $recovered;
 }
Example #10
0
function ActionUserCompleted($action_file, $type)
{
    global $nc_core, $db, $ROOT_FOLDER, $admin_mode, $perm;
    global $systemTableID, $systemTableName, $systemMessageID;
    global $FILES_FOLDER, $INCLUDE_FOLDER;
    global $DIRCHMOD, $FILECHMOD, $AUTHORIZE_BY;
    $params = array('Checked', 'InsideAdminAccess', 'PermissionGroupID', 'Catalogue_ID', 'Password1', 'Password2', 'UserID', 'posting');
    foreach ($params as $v) {
        global ${$v};
    }
    $st = new nc_Component(0, 3);
    foreach ($st->get_fields() as $v) {
        $name = 'f_' . $v['name'];
        global ${$name};
        if ($v['type'] == 6) {
            global ${$name . "_old"};
            global ${"f_KILL" . $v['id']};
        }
        if ($v['type'] == 8) {
            global ${$name . "_day"};
            global ${$name . "_month"};
            global ${$name . "_year"};
            global ${$name . "_hours"};
            global ${$name . "_minutes"};
            global ${$name . "_seconds"};
        }
    }
    $UserID = intval($UserID);
    $Checked = intval($Checked);
    $ret = 0;
    // возврщаемое значение (текст ошибки или 0)
    require_once $INCLUDE_FOLDER . "s_files.inc.php";
    $is_there_any_files = getFileCount(0, $systemTableID);
    $user_table_mode = true;
    if ($type == 1) {
        $action = "add";
    } else {
        $action = "change";
        $message = $UserID;
    }
    $Priority += 0;
    nc_check_availability_candidates_for_delete_in_multifile_and_delete();
    nc_rename_multifile();
    require $ROOT_FOLDER . "message_fields.php";
    if ($posting == 0) {
        return $warnText;
    }
    require $ROOT_FOLDER . "message_put.php";
    if (empty($PermissionGroupID)) {
        return CONTROL_USER_FUNC_GROUP_ERROR;
    }
    // значение, которое пойдет в таблицу User
    // для совместимости со старыми версиями
    $mainPermissionGroupID = intval(min($PermissionGroupID));
    $groups_with_more_rights = $perm->GetGroupWithMoreRights();
    //нельзя добавить в группу с большими правами
    $add_groups_with_more_rights = array_intersect($PermissionGroupID, $groups_with_more_rights);
    if (!empty($add_groups_with_more_rights)) {
        return $warnText = NETCAT_MODERATION_ERROR_NORIGHT;
    }
    eval("\$Login = \$f_{$AUTHORIZE_BY};");
    if ($type == 1) {
        $Password = $Password1;
        for ($i = 0; $i < $fldCount; $i++) {
            if (isset(${$fld[$i] . 'Defined'}) && ${$fld[$i] . 'Defined'} == true) {
                $fieldString .= "`" . $fld[$i] . "`,";
                $valueString .= ${$fld[$i] . 'NewValue'} . ",";
            }
        }
        $insert = "INSERT INTO User ( " . $fieldString;
        $insert .= "PermissionGroup_ID, Catalogue_ID, Password, Checked, Created,InsideAdminAccess) values ( " . $valueString;
        $insert .= "'" . $mainPermissionGroupID . "', ";
        if (isset($_POST['Catalogue_ID'])) {
            $insert .= +$_POST['Catalogue_ID'] . ", ";
        } else {
            $insert .= "0, ";
        }
        $insert .= $nc_core->MYSQL_ENCRYPT . "('" . $Password . "'),'{$Checked}','" . date("Y-m-d H:i:s") . "', '" . (int) $InsideAdminAccess . "')";
        // execute core action
        $nc_core->event->execute("addUserPrep", 0);
        $Result = $db->query($insert);
        $UserID = $db->insert_id;
        $message = $UserID;
        if ($Result) {
            // execute core action
            $nc_core->event->execute("addUser", $message);
            nc_print_status(CONTROL_USER_NEW_ADDED, 'ok');
            foreach ($PermissionGroupID as $v) {
                nc_usergroup_add_to_group($UserID, $v);
            }
        } else {
            return CONTROL_USER_NEW_NOTADDED . "<br/>" . sprintf(NETCAT_ERROR_SQL, $db->last_query, $db->last_error);
        }
    }
    if ($type == 2) {
        $cur_checked = $db->get_var("SELECT `Checked` FROM `User` WHERE `User_ID` = '" . $UserID . "'");
        $update = "update User set ";
        for ($i = 0; $i < $fldCount; $i++) {
            if ($fldTypeOfEdit[$i] == 3 || $fldTypeOfEdit[$i] == 2 && !nc_field_check_admin_perm()) {
                continue;
            }
            // поле недоступно никому или доступно администратору но нет прав администратора
            if (isset(${$fld[$i] . 'Defined'}) && ${$fld[$i] . 'Defined'} == true) {
                $update .= $fld[$i] . "=" . ${$fld[$i] . 'NewValue'} . ",";
            } else {
                $update .= $fld[$i] . "=" . ($fldValue[$i] ? $fldValue[$i] : "NULL") . ",";
            }
        }
        $update .= "Checked=\"" . $Checked . "\",";
        $update .= "PermissionGroup_ID=\"" . $mainPermissionGroupID . "\",";
        $update .= "InsideAdminAccess=" . (int) $InsideAdminAccess;
        if (isset($_POST['Catalogue_ID'])) {
            $update .= ", Catalogue_ID=" . (int) $_POST['Catalogue_ID'];
        }
        $update .= " where User_ID=" . $UserID;
        // execute core action
        $nc_core->event->execute("updateUserPrep", $UserID);
        if ($cur_checked != $Checked) {
            $nc_core->event->execute($Checked ? "checkUserPrep" : "uncheckUserPrep", $UserID);
        }
        $Result = $db->query($update);
        // execute core action
        $nc_core->event->execute("updateUser", $UserID);
        $db->query("DELETE FROM `User_Group` WHERE `User_ID`='" . intval($UserID) . "'");
        foreach ($PermissionGroupID as $v) {
            nc_usergroup_add_to_group($UserID, $v, 0);
        }
        // произошла смена состояния пользователя
        if ($cur_checked != $Checked) {
            $nc_core->event->execute($Checked ? "checkUser" : "uncheckUser", $UserID);
        }
    }
    if (is_array($SQL_multifield)) {
        nc_multifield_sql_exec($message, $SQL_multifield);
    }
    // Обновление в таблице с файлами
    if (!empty($filetable_lastid)) {
        $db->query("UPDATE `Filetable` SET `Message_ID`='" . $message . "' WHERE ID IN (" . join(',', $filetable_lastid) . ")");
    }
    // create dir
    @mkdir($FILES_FOLDER . "u/", $DIRCHMOD);
    /*     * */
    for ($i = 0; $i < count($tmpFile); $i++) {
        eval("\$tmpNewFile[\$i] = \"" . $tmpNewFile[$i] . "\";");
        @rename($FILES_FOLDER . $tmpFile[$i], $FILES_FOLDER . $File_Path[$i] . $tmpNewFile[$i]);
        @chmod($FILES_FOLDER . $File_Path[$i] . $tmpNewFile[$i], $FILECHMOD);
    }
    // привязка токена
    $nc_token_login = $nc_core->input->fetch_get_post('nc_token_login');
    $nc_token_key = $nc_core->input->fetch_get_post('nc_token_key');
    if ($nc_token_login && $nc_token_key && $UserID) {
        $db->query("INSERT INTO `Auth_Token`\n                  SET `Login` = '" . $db->escape($nc_token_login) . "',\n                      `PublicKey` = '" . $db->escape($nc_token_key) . "',\n                      `User_ID` = '" . $UserID . "' ");
    }
    $nc_token_destroy = $nc_core->input->fetch_get_post('nc_token_destroy');
    if ($nc_token_destroy) {
        $nc_auth_token = new nc_auth_token();
        $nc_auth_token->delete_by_id($nc_token_destroy);
    }
    return 0;
}
Example #11
0
function nc_classtemplate_make_trash($class_id)
{
    $component = new nc_Component($class_id);
    $File_Mode = nc_get_file_mode('Class', $class_id);
    // поля, которые могут попасть в ленту
    $fields = $component->get_fields();
    $string_fields = $component->get_fields(NC_FIELDTYPE_STRING);
    $text_fields = $component->get_fields(NC_FIELDTYPE_TEXT);
    // ищем поле для titl'a
    $title = '';
    if (!empty($string_fields)) {
        foreach ($string_fields as $v) {
            if (nc_preg_match('/(titl|caption|name|subject)/i', $v['name'])) {
                $title = 'f_' . $v['name'];
                break;
            }
        }
    }
    if (empty($title) && !empty($string_fields)) {
        $title = 'f_' . $string_fields[0]['name'];
    } elseif (empty($title) && empty($string_fields) && !empty($text_fields)) {
        $title = 'f_' . $text_fields[0]['name'];
    } elseif (empty($title) && !empty($fields)) {
        $title = 'f_' . $fields[0]['name'] . ($fields[0]['type'] == 6 ? '_name' : NULL);
    } elseif (empty($title)) {
        $title = 'f_RowID';
    }
    $record = $File_Mode ? '<?php echo "' : '';
    $record .= '$f_AdminButtons $' . $title . "<br /><br />\r\n";
    $record .= $File_Mode ? '"; ?>' : '';
    return array('RecordTemplate' => $record);
}
Example #12
0
function nc_subdivision_form_fields_save()
{
    // глобальные переменные нужны в файлах message_put, message_fields
    global $systemTableID, $systemTableName, $systemMessageID, $message, $db;
    global $FILES_FOLDER, $HTTP_FILES_PATH, $SUB_FOLDER, $DIRCHMOD;
    $nc_core = nc_Core::get_object();
    $sub_id = intval($nc_core->input->fetch_get_post('SubdivisionID'));
    $posting = 1;
    $systemMessageID = $message = $sub_id;
    $action = "change";
    $st = new nc_Component(0, 2);
    foreach ($st->get_fields() as $v) {
        $name = 'f_' . $v['name'];
        global ${$name};
        if ($v['type'] == 6) {
            global ${$name . "_old"};
            global ${"f_KILL" . $v['id']};
        }
    }
    require $nc_core->ROOT_FOLDER . "message_fields.php";
    if (!$posting) {
        echo $warnText;
        return false;
    }
    require $nc_core->ROOT_FOLDER . "message_put.php";
    $update = "UPDATE `Subdivision` SET ";
    $update_inherited = array();
    for ($i = 0; $i < $fldCount; $i++) {
        if ($fldTypeOfEdit[$i] == 3) {
            continue;
        }
        // поле недоступно никому
        if ($fldInheritance[$i] == 1) {
            $update_inherited[$fld[$i]] = $fldValue[$i];
        }
        if (isset(${$fld[$i] . 'Defined'}) && ${$fld[$i] . 'Defined'} == true) {
            $update .= "`" . $fld[$i] . "` =" . ${$fld[$i] . 'NewValue'} . ",";
        } else {
            $update .= "`" . $fld[$i] . "` = " . $fldValue[$i] . ", ";
        }
    }
    $update .= " `Checked` = `Checked` WHERE `Subdivision_ID` = '" . $sub_id . "'";
    $db->query($update);
    if (!empty($update_inherited)) {
        $SQL = "UPDATE `Subdivision` SET ";
        foreach ($update_inherited as $key => $value) {
            $update_inherited[$key] = "`" . $key . "` = " . $value;
        }
        $SQL .= implode(', ', $update_inherited) . " WHERE `Parent_Sub_ID` = '" . $sub_id . "'";
        $db->query($SQL);
    }
    // default value
    if (!isset($nc_core->DIRCHMOD)) {
        $nc_core->DIRCHMOD = 0777;
    }
    // create dir
    @mkdir($nc_core->FILES_FOLDER . $message . "/", $nc_core->DIRCHMOD);
    for ($i = 0; $i < count($tmpFile); $i++) {
        eval("\$tmpNewFile[\$i] = \"" . $tmpNewFile[$i] . "\";");
        eval("\$File_PathNew[\$i] = \"" . $File_PathNew[$i] . "\";");
        eval("\$File_Path[\$i] = \"" . $File_Path[$i] . "\";");
        if ($fld_name[$i]) {
            $db->query("UPDATE `Subdivision`\n       SET `" . $fld_name[$i] . "` = REPLACE(" . $fld_name[$i] . ", '\$message', Subdivision_ID )\n       WHERE Subdivision_ID = '" . $message . "'");
            if (!empty($update_inherited)) {
                $sql = "UPDATE `Subdivision`\n       SET `" . $fld_name[$i] . "` = REPLACE(" . $fld_name[$i] . ", '\$message', Parent_Sub_ID )\n       WHERE Parent_Sub_ID = '" . $message . "'";
                $db->query($sql);
            }
        }
        if ($FileFS[$i] == NC_FS_PROTECTED || $FileFS[$i] == NC_FS_ORIGINAL) {
            @rename($nc_core->FILES_FOLDER . $tmpNewFile[$i], $nc_core->FILES_FOLDER . $File_PathNew[$i] . $tmpNewFile[$i]);
        } else {
            @rename($nc_core->FILES_FOLDER . $tmpFile[$i], $nc_core->FILES_FOLDER . $File_Path[$i] . $tmpNewFile[$i]);
        }
        @chmod($nc_core->FILES_FOLDER . $File_PathNew[$i] . $tmpNewFile[$i], $nc_core->FILECHMOD);
    }
    if (!empty($filetable_lastid)) {
        $db->query("UPDATE `Filetable`\n          SET `Message_ID` = '" . $message . "', `File_Path` = '/" . $message . "/'\n          WHERE `ID`  IN(" . join(',', $filetable_lastid) . ")");
    }
    $nc_core->subdivision->update($sub_id, array('Subdivision_ID' => $sub_id));
    return true;
}