Esempio n. 1
0
/**
 * Show confirm deleting object
 *
 * @param array post
 */
function confim_delete_sub_class_object($array)
{
    global $UI_CONFIG, $db, $nc_core;
    $in = array();
    reset($array);
    while (list($key, $val) = each($array)) {
        if (nc_substr($key, 0, 6) == "Delete") {
            $in[] = intval($val);
        }
    }
    $in_array = join(',', $in);
    $sub_class = $db->get_col("SELECT `Sub_Class_Name` FROM `Sub_Class` WHERE Sub_Class_ID IN(" . $in_array . ")");
    if ($db->num_rows) {
        print "<form action='index.php' method='post'>\n\n             <input type='hidden' name='phase' value='4'>\n\n             <input type='hidden' name='sub_class' value='" . $in_array . "'>\n\n             " . $nc_core->token->get_input() . "\n           </form>\n";
        nc_print_status(REPORTS_STAT_CLASS_CONFIRM, 'ok');
        print "<ui>";
        foreach ($sub_class as $v) {
            print "<li>" . $v;
        }
        $UI_CONFIG->actionButtons[] = array("id" => "submit", "caption" => REPORTS_STAT_CLASS_CONFIRM_OK, "action" => "mainView.submitIframeForm()");
    } else {
        nc_print_status(REPORTS_STAT_CLASS_NOT_CC, 'error');
    }
}
Esempio n. 2
0
function echo_widget_form($params, $alter = 0, $action = '')
{
    global $ADMIN_PATH, $db;
    if ($action) {
        $action = "action='{$ADMIN_PATH}{$action}'";
    }
    if (!$alter) {
        $html .= "\n            <legend>" . WIDGETS_PARAMS . "</legend>" . "<form id='adminForm' class='nc-form' method='post' {$action}><br />" . "" . WIDGET_ADD_NAME . ":<br />" . nc_admin_input_simple('Name', isset($params['Name']) ? $params['Name'] : '', 50) . "<br /><br />" . "" . WIDGET_ADD_KEYWORD . ":<br />" . nc_admin_input_simple('Keyword', isset($params['Keyword']) ? $params['Keyword'] : '', 50) . "<br /><br />";
    }
    $widgets = $db->get_results("SELECT `Widget_Class_ID` AS value, CONCAT(`Widget_Class_ID`, '. ', `Name`) AS description, `Category` AS optgroup FROM `Widget_Class` WHERE `InDevelop`='0' ORDER BY `Category`, `Widget_Class_ID`", ARRAY_A);
    $html .= "" . WIDGET_ADD_WK . ":<br />" . "<select name='Widget_Class_ID' id='Widget_Class_ID' onchange='nc_widget_obj.change();return false;'>";
    if (!empty($widgets)) {
        $html .= nc_select_options($widgets, isset($params['Widget_Class_ID']) ? $params['Widget_Class_ID'] : '');
    }
    $html .= "</select><br /><br /><div id='widget_fields'></div>";
    if ($params) {
        foreach ($params as $param_name => $param_value) {
            if (nc_substr($param_name, 0, 1) == 'f') {
                // и в fieldNNN и в f_XXXXXX первая буква f
                $old_values .= "&" . urlencode($param_name) . "=" . urlencode($param_value);
            }
        }
        if ($old_values) {
            $html .= "<input type='hidden' id='__old_values' value='" . $old_values . "&old_widget_class_id=" . urlencode($params['Widget_Class_ID']) . "'>";
        }
    }
    if (!$alter) {
        echo $html;
    } else {
        return $html;
    }
}
Esempio n. 3
0
     #}
 } elseif ($admin_modal) {
     eval($nc_core->template->get_current("Settings"));
 }
 // openstat
 if (NC_OPENSTAT_COUNTER) {
     if (!$admin_mode && !$inside_admin) {
         $pos = nc_strpos($template_header, NC_OPENSTAT_COUNTER);
         if ($pos !== FALSE) {
             $template_header = nc_substr($template_header, 0, $pos) . nc_openstat_get_code() . nc_substr($template_header, $pos + nc_strlen(NC_OPENSTAT_COUNTER));
             $template_header = str_replace(NC_OPENSTAT_COUNTER, "", $template_header);
             $template_footer = str_replace(NC_OPENSTAT_COUNTER, "", $template_footer);
         } else {
             $pos = nc_strpos($template_footer, NC_OPENSTAT_COUNTER);
             if ($pos !== FALSE) {
                 $template_footer = nc_substr($template_footer, 0, $pos) . nc_openstat_get_code() . nc_substr($template_footer, $pos + nc_strlen(NC_OPENSTAT_COUNTER));
                 $template_footer = str_replace(NC_OPENSTAT_COUNTER, "", $template_footer);
             }
         }
     }
 }
 if (!$check_auth && NC_AUTH_IN_PROGRESS !== 1) {
     eval("echo \"" . $template_header . "\";");
     if ($AUTH_USER_ID || !$AUTH_USER_ID && !$nc_core->modules->get_vars('auth')) {
         if ($nc_core->inside_admin) {
             nc_print_status(NETCAT_MODERATION_ERROR_NORIGHTS, 'error');
         } else {
             print NETCAT_MODERATION_ERROR_NORIGHTS;
         }
     } elseif (!$AUTH_USER_ID && $nc_core->modules->get_vars('auth')) {
         $nc_auth->login_form();
Esempio n. 4
0
	<table class='admin_table' width='100%'>
		<tr>
			<th><?php 
        echo REPORTS_SYSMSG_DATE;
        ?>
</th>
			<th width='80%'><?php 
        echo REPORTS_SYSMSG_MSG;
        ?>
</th>
		</tr>
<?php 
        foreach ($res as $Array) {
            //  In MySQL 4.1, TIMESTAMP display format changes to be the same as DATETIME.
            if (substr($Array['Date'], 4, 1) != '-') {
                $Array['Date'] = nc_substr($Array['Date'], 0, 4) . "-" . nc_substr($Array['Date'], 4, 2) . "-" . nc_substr($Array['Date'], 6, 2) . " " . nc_substr($Array['Date'], 8, 2) . ":" . nc_substr($Array['Date'], 10, 2) . ":" . nc_substr($Array['Date'], 12, 2);
            }
            ?>
		<tr>
			<td nowrap><font color=gray><?php 
            echo $Array["Date"];
            ?>
</td>
			<td><a href='system.php?SystemMessageID=<?php 
            echo $Array["SystemMessage_ID"];
            ?>
'><?php 
            echo (!$Array["Checked"] ? "<b>" : "") . $Array["Description"] . (!$Array["Checked"] ? "</b>" : "");
            ?>
</a></td>
		</tr>
Esempio n. 5
0
/**
 * Перемещение объекта из одного шаблона в разделе в другой.
 *
 * Пользователь должен обладать правами: изменение в разделе, где
 * находится объект, и удаление в разделе, куда переносится объект.
 *
 * @param integer ID класса объекта
 * @param integer ID объекта
 * @param integer ID шаблона в разделе, куда переносится объект
 * @return boolean
 */
function nc_move_message($class_id, $message_id, $destination_cc_id)
{
    global $nc_core;
    $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_move_message()", E_USER_WARNING);
        return false;
    }
    $db = $nc_core->db;
    // перемещаемое сообщение
    $message = $db->get_row("SELECT sd.`Catalogue_ID`,\n                                  m.*\n                             FROM `Message" . $class_id . "` AS m,\n                                  `Subdivision` as sd\n                            WHERE m.`Message_ID`='" . $message_id . "'\n                              AND m.`Subdivision_ID`=sd.`Subdivision_ID` ", ARRAY_A);
    // сабкласс назначения
    $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` ", ARRAY_A);
    // существует ли объект и компонент в разделе
    if (!$message || !$dest_subclass) {
        $what = $message ? 'subclass' : 'object';
        trigger_error("nc_move_message: {$what} doesn't exist", E_USER_WARNING);
        return false;
    }
    // перемещать можно только в рамках одного компонента
    if ($dest_subclass['Class_ID'] != $class_id) {
        trigger_error("nc_move_message: destination subclass belongs to different class", E_USER_WARNING);
        return false;
    }
    // перенос в самого себя
    if ($dest_subclass['Sub_Class_ID'] == $message['Sub_Class_ID']) {
        return true;
    }
    // права
    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_move_message: insufficient rights", E_USER_WARNING);
        return false;
    }
    // execute core action
    $nc_core->event->execute("updateMessagePrep", $dest_subclass['Catalogue_ID'], $dest_subclass['Subdivision_ID'], $dest_subclass['Sub_Class_ID'], $dest_subclass['Class_ID'], $message_id);
    // файлы
    $file_fields = $db->get_results("SELECT `Field_ID`, `Field_Name` FROM `Field` WHERE `Class_ID`='" . $class_id . "' AND TypeOfData_ID = '6' ", ARRAY_A);
    if (!empty($file_fields)) {
        $FILES_FOLDER = $nc_core->FILES_FOLDER;
        $DOCUMENT_ROOT = $nc_core->DOCUMENT_ROOT;
        $SUB_FOLDER = $nc_core->SUB_FOLDER;
        $DIRCHMOD = $nc_core->DIRCHMOD;
        $INCLUDE_FOLDER = $nc_core->INCLUDE_FOLDER;
        // создание директорий
        $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
            @chmod($dir, $DIRCHMOD);
        }
        unset($dirs);
        $dest_path = "/{$dest_subclass['Subdivision_ID']}/{$dest_subclass['Sub_Class_ID']}/";
        require_once $INCLUDE_FOLDER . "s_common.inc.php";
        foreach ($file_fields as $field) {
            $value = $message[$field['Field_Name']];
            if (!$value) {
                continue;
            }
            // файла нет
            $file_id = $db->get_var("SELECT `ID` FROM `Filetable` WHERE `Field_ID` = '" . $field['Field_ID'] . "' AND `Message_ID` = '" . $message_id . "'");
            if ($file_id) {
                $file_path = nc_file_path($class_id, $message_id, $field['Field_ID']);
                if ($file_path) {
                    preg_match("#/([0-9a-f]{32})\$#i", $file_path, $regs);
                }
                if (file_exists(rtrim($DOCUMENT_ROOT, '/') . $SUB_FOLDER . $file_path) && !rename($DOCUMENT_ROOT . $SUB_FOLDER . $file_path, rtrim($FILES_FOLDER, '/') . $dest_path . $regs[1])) {
                    return false;
                }
                $db->query("UPDATE `Filetable` SET `File_Path`='" . $dest_path . "' WHERE `ID` = '" . $file_id . "'");
                $is_moved = 1;
            }
            if ($is_moved) {
                continue;
            }
            $file_data = explode(':', $value);
            $file_name = $file_data[0];
            $ext = nc_substr($file_name, nc_strrpos($file_name, "."));
            // расширение файла
            if ($file_data[3]) {
                $new_name = nc_get_filename_for_original_fs($file_name, $nc_core->FILES_FOLDER . $message['Subdivision_ID'] . "/" . $message['Sub_Class_ID']);
                if (file_exists($nc_core->FILES_FOLDER . $file_data[3]) && !rename($nc_core->FILES_FOLDER . $file_data[3], $nc_core->FILES_FOLDER . $dest_path . $new_name)) {
                    return false;
                }
                $dt = $file_data[0] . ":" . $file_data[1] . ":" . $file_data[2] . ":" . ltrim($dest_path, '/') . $new_name;
                $db->query("UPDATE `Message" . $class_id . "` SET `" . $field['Field_Name'] . "` = '" . $dt . "' WHERE `Message_ID` = '" . $message_id . "'  ");
            }
        }
    }
    // сообствено перемещение
    $db->query("UPDATE Message{$class_id}\n                 SET Subdivision_ID={$dest_subclass[Subdivision_ID]},\n                     Sub_Class_ID={$dest_subclass[Sub_Class_ID]},\n                     Priority = {$dest_subclass[Next_Priority]}\n               WHERE Message_ID = {$message_id}");
    // обновление приоритетов
    $db->query("UPDATE Message{$class_id}\n                 SET Created=Created, LastUpdated=LastUpdated,\n                     Priority = Priority-1\n               WHERE Sub_Class_ID = {$message[Sub_Class_ID]}\n                 AND Priority > {$message['Priority']}");
    //перемещение комментариев объекта
    if ($nc_core->modules->get_by_keyword('comments')) {
        $db->query("UPDATE `Comments_Text`\n                     SET `Sub_Class_ID`={$dest_subclass[Sub_Class_ID]}\n                   WHERE `Message_ID` = {$message_id}\n                     AND `Sub_Class_ID`={$message[Sub_Class_ID]}");
        $db->query("UPDATE `Comments_Count`\n                     SET `Sub_Class_ID`={$dest_subclass[Sub_Class_ID]}\n                   WHERE `Message_ID` = {$message_id}\n                     AND `Sub_Class_ID`={$message[Sub_Class_ID]}");
    }
    // execute core action
    $nc_core->event->execute("updateMessage", $dest_subclass['Catalogue_ID'], $dest_subclass['Subdivision_ID'], $dest_subclass['Sub_Class_ID'], $dest_subclass['Class_ID'], $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) {
            nc_move_message($class_id, $child_id, $destination_cc_id);
        }
    }
    return true;
}
Esempio n. 6
0
 public function prepare_extract()
 {
     $nc_core = nc_Core::get_object();
     static $result = array();
     $nc_core->REQUEST_URI = isset($_GET['REQUEST_URI']) ? $_GET['REQUEST_URI'] : (isset($_POST['REQUEST_URI']) ? $_POST['REQUEST_URI'] : (isset($_ENV['REQUEST_URI']) ? $_ENV['REQUEST_URI'] : getenv("REQUEST_URI")));
     if (nc_substr($nc_core->REQUEST_URI, 0, 1) != "/") {
         $nc_core->REQUEST_URI = "/" . $nc_core->REQUEST_URI;
     }
     $nc_core->REQUEST_URI = trim($nc_core->REQUEST_URI);
     $url = "http" . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "s" : "") . "://" . getenv("HTTP_HOST") . $nc_core->REQUEST_URI;
     $parsed_url = @parse_url($url);
     if (is_array($parsed_url) && array_key_exists('query', $parsed_url) && $parsed_url['query']) {
         parse_str($parsed_url['query'], $parsed_query_arr);
         $parsed_query_arr = $this->clear_system_vars($parsed_query_arr);
         $_GET = $parsed_query_arr ? $parsed_query_arr : array();
     }
     if (!empty($result)) {
         return $result;
     }
     // XSS clean
     if (isset($nc_core->security) && $nc_core->SECURITY_XSS_CLEAN) {
         if (!function_exists('array_map_recursive')) {
             function array_map_recursive($fn, $arr)
             {
                 $rarr = array();
                 foreach ($arr as $k => $v) {
                     $rarr[$k] = is_array($v) ? array_map_recursive($fn, $v) : (is_array($fn) ? call_user_func($fn, $v) : $fn($v));
                 }
                 return $rarr;
             }
         }
         $_COOKIE = array_map_recursive(array($nc_core->security, 'xss_clean'), $_COOKIE);
         $_GET = array_map_recursive(array($nc_core->security, 'xss_clean'), $_GET);
         $_ENV = array_map_recursive(array($nc_core->security, 'xss_clean'), $_ENV);
         $_SERVER = array_map_recursive(array($nc_core->security, 'xss_clean'), $_SERVER);
     }
     $superglobals = array("_COOKIE" => $_COOKIE, "_GET" => $_GET, "_POST" => $_POST, "_FILES" => $_FILES, "_ENV" => $_ENV, "_SERVER" => $_SERVER);
     foreach ($superglobals as $key => $super_array) {
         $result = array_merge($result, $super_array);
         $this->{$key} = $this->prepare_superglobals($super_array);
     }
     $result = $this->filter($this->clear_system_vars($result));
     foreach ($this->_variables as $var) {
         if ((array_key_exists($var, $superglobals) || $this->in_superglobal($var)) && !in_array($var, array('HTTP_HOST', 'DOCUMENT_ROOT', 'REDIRECT_STATUS'))) {
             continue;
         }
         global ${$var};
         $nc_core->set_variable($var, ${$var});
     }
     if (!$nc_core->NC_CHARSET) {
         $nc_core->NC_CHARSET = 'windows-1251';
     }
     if (!$nc_core->NC_JQUERY_PATH) {
         $nc_core->NC_JQUERY_PATH = $nc_core->SUB_FOLDER . $nc_core->HTTP_TEMPLATE_PATH . 'jquery/jquery.min.js';
     }
     $nc_core->MYSQL_ENCRYPT = strtoupper($nc_core->MYSQL_ENCRYPT);
     if (!$nc_core->MYSQL_ENCRYPT || !in_array($nc_core->MYSQL_ENCRYPT, array('PASSWORD', 'OLD_PASSWORD', 'MD5', 'SHA', 'SHA1'))) {
         $nc_core->MYSQL_ENCRYPT = 'PASSWORD';
     }
     if (!$nc_core->NC_UNICODE && ($_POST["NC_HTTP_REQUEST"] || $_SERVER['HTTP_X_REQUESTED_WITH'])) {
         $result = $nc_core->utf8->array_utf2win($result);
         foreach ($superglobals as $key => $super_array) {
             $this->{$key} = $nc_core->utf8->array_utf2win($this->{$key});
         }
     }
     if (!get_magic_quotes_gpc()) {
         $result = $this->recursive_add_slashes($result);
     }
     return $result;
 }
Esempio n. 7
0
         $errCode = 1;
     }
     if ($fldValue[$i] != "" && !preg_match("/^\\-?[0-9]+(\\.[0-9]+)?\$/is", str_replace(",", ".", $fldValue[$i]))) {
         $errCode = 2;
     }
     if (preg_match("/,/is", $fldValue[$i])) {
         $fldValue[$i] = str_replace(",", ".", $fldValue[$i]);
     }
     break;
     #datetime
 #datetime
 case NC_FIELDTYPE_DATETIME:
     if ($fldNotNull[$i] && $fldValue[$i] == "") {
         $errCode = 1;
     }
     if ($fldValue[$i] != "" && $fldValue[$i] != '0000-00-00 00:00:00' && $fldFmt[$i] != 'event_time' && !checkdate(nc_substr($fldValue[$i], 5, 2), nc_substr($fldValue[$i], 8, 2), nc_substr($fldValue[$i], 0, 4))) {
         $errCode = 2;
         $fldValue[$i] = "";
     }
     break;
     #relation
 #relation
 case NC_FIELDTYPE_RELATION:
     if ($fldValue[$i]) {
         $fldValue[$i] = (int) $fldValue[$i];
     }
     if ($fldNotNull[$i] && !$fldValue[$i]) {
         $errCode = 1;
     }
     break;
     #multiselect
Esempio n. 8
0
function ShowMenu($CatalogueID, $phase1, $action1, $phase2, $action2)
{
    global $db, $perm;
    global $EDIT_DOMAIN, $HTTP_ROOT_PATH, $DOMAIN_NAME, $ADMIN_PATH, $SUB_FOLDER;
    global $UI_CONFIG;
    $CatalogueID = intval($CatalogueID);
    $is_admin = $perm->isCatalogueAdmin($CatalogueID);
    $Array = $db->get_row("SELECT * FROM `Catalogue` WHERE `Catalogue_ID`='" . $CatalogueID . "'");
    if (!$Array) {
        nc_print_status(CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWCATALOGUELIST_DBERROR, 'error');
        EndHtml();
        exit;
    }
    $countChild = HighLevelChildrenNumber($CatalogueID);
    $ModerationType = $Array->Moderation_ID == 2 ? CLASSIFICATOR_TYPEOFMODERATION_MODERATION : CLASSIFICATOR_TYPEOFMODERATION_RIGHTAWAY;
    $UserGroupName = array(1 => CLASSIFICATOR_USERGROUP_ALL, 2 => CLASSIFICATOR_USERGROUP_REGISTERED, 3 => CLASSIFICATOR_USERGROUP_AUTHORIZED);
    //  In MySQL 4.1, TIMESTAMP display format changes to be the same as DATETIME.
    if (nc_strpos($Array->LastUpdated[4], '-')) {
        $Array->LastUpdated = nc_substr($Array->LastUpdated, 0, 4) . "-" . nc_substr($Array->LastUpdated, 4, 2) . "-" . nc_substr($Array->LastUpdated, 6, 2) . " " . nc_substr($Array->LastUpdated, 8, 2) . ":" . nc_substr($Array->LastUpdated, 10, 2) . ":" . nc_substr($Array->LastUpdated, 12, 2);
    }
    echo "<br />\n\t<table border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td>\n\t<table border='0' cellpadding='0' cellspacing='1' width='100%'><tr><td>\n \t<table border='0' cellpadding='0' cellspacing='0' width='100%' class='border-bottom'>\n \t<tr><td width='50%'>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_CREATED . ":</td><td>" . $Array->Created . "</td></tr>\n \t<tr><td>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_UPDATED . ":</td><td>" . $Array->LastUpdated . "</td></tr>\n \t</table>\n\t</td></tr><tr><td>\n \t<table border='0' cellpadding='0' cellspacing='0' width='100%' class='border-bottom'>\n  <tr><td width='50%'>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_SECTIONSCOUNT . ":</td>";
    echo "<td>" . $countChild;
    if ($countChild) {
        echo " ( <a href='" . $ADMIN_PATH . "subdivision/index.php?CatalogueID=" . $CatalogueID . "&amp;ParentSubID=0'>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWCATALOGUELIST_LIST . "</a>\n          " . ($is_admin ? ", <a href='" . $ADMIN_PATH . "subdivision/index.php?phase=2&amp;ParentSubID=0&amp;CatalogueID=" . $CatalogueID . "'>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_ADD . "\n          </a> )" : ")") . "";
    }
    echo "</td></tr>\n \t<tr><td>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_SITESTATUS . ":</td><td>" . ($Array->Checked ? CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_ON : CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_OFF) . "</td></tr>\n \t</table>\n\t</td></tr><tr><td>\n \t<table border='0' cellpadding='0' cellspacing='0' width='100%' class='border-bottom'>\n \t<tr><td width=50%>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_READACCESS . ":</td><td>" . $UserGroupName[$Array->Read_Access_ID] . " " . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_USERS . "</td></tr>\n  <tr><td>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_ADDACCESS . ":</td><td>" . $UserGroupName[$Array->Write_Access_ID] . " " . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_USERS . "</td></tr>\n \t<tr><td>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_EDITACCESS . ":</td><td>" . $UserGroupName[$Array->Edit_Access_ID] . " " . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_USERS . "</td></tr>\n \t<tr><td>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_SUBSCRIBEACCESS . ":</td><td>" . $UserGroupName[$Array->Subscribe_Access_ID] . " " . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_USERS . "</td></tr>\n \t<tr><td>" . CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_PUBLISHACCESS . ":</td><td>" . $ModerationType . "</td></tr>\n \t</table>\n\t</td></tr></table></td></tr></table>";
    $UI_CONFIG->actionButtons[] = array("id" => "delete", "caption" => CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_DELETE, "location" => "site.delete(" . $CatalogueID . ")", "red_border" => true);
    $UI_CONFIG->actionButtons[] = array("id" => "preview", "caption" => CONTROL_CONTENT_CATALOUGE_FUNCS_SHOWMENU_VIEW, "action" => "urlDispatcher.load('http://" . ($Array->Domain ? strstr($Array->Domain, ".") ? $Array->Domain : $Array->Domain . "." . $DOMAIN_NAME : $DOMAIN_NAME) . $SUB_FOLDER . (nc_strlen(session_id()) > 0 ? "?" . session_name() . "=" . session_id() . "" : "") . "', '1')");
}
Esempio n. 9
0
function nc_copy_subdivision($sub_ids, $dest_catalogue_id, $dest_parent_sub_id, $with_child = 1, $with_сс = 1, $with_object = 1, $templates = array())
{
    $nc_core = nc_Core::get_object();
    global $db;
    if (!is_array($sub_ids)) {
        $sub_ids = array($sub_ids);
    }
    if (!$with_сс) {
        $with_object = 0;
    }
    if (!$templates['sub_name']) {
        $templates['sub_name'] = '%NAME%';
    }
    if (!$templates['sub_keyword']) {
        $templates['sub_keyword'] = '%KEYWORD%';
    }
    if (!$templates['cc_name']) {
        $templates['cc_name'] = '%NAME%';
    }
    if (!$templates['cc_keyword']) {
        $templates['cc_keyword'] = '%KEYWORD%';
    }
    // разделы для копирования
    $subdivisions = $db->get_results("SELECT * FROM `Subdivision`\n                                    WHERE `Subdivision_ID` IN (" . join(',', $sub_ids) . ")\n                                    ORDER BY `Subdivision_ID` ", ARRAY_A);
    if (empty($subdivisions)) {
        return 0;
    }
    if ($dest_parent_sub_id && in_array($dest_parent_sub_id, $sub_ids)) {
        throw new Exception(TOOLS_COPYSUB_ERROR_LEVEL_COUNT);
    }
    // копирование в определенный раздел - можно вычислить сайт
    if ($dest_parent_sub_id) {
        $dest_subdivision = $db->get_row("SELECT `Catalogue_ID`, `Hidden_URL`, `EnglishName` FROM `Subdivision` WHERE `Subdivision_ID` = '" . $dest_parent_sub_id . "'", ARRAY_A);
        $dest_catalogue_id = $dest_subdivision['Catalogue_ID'];
        $hidden_url = $dest_subdivision['Hidden_URL'];
        $english_name = $dest_subdivision['EnglishName'];
        $child_english_names = $db->get_col("SELECT `EnglishName` FROM `Subdivision` WHERE `Parent_Sub_ID` = '" . $dest_parent_sub_id . "' ");
    } else {
        $hidden_url = '/';
        $child_english_names = $db->get_col("SELECT `EnglishName` FROM `Subdivision` WHERE `Parent_Sub_ID` = '0' AND `Catalogue_ID` = '" . $dest_catalogue_id . "' ");
    }
    if (!$child_english_names) {
        $child_english_names = array();
    }
    $fields = array_keys($subdivisions[0]);
    $query_fields_subdivisions = array();
    $insert_values_subdivisions = array();
    unset($fields[0]);
    foreach ($fields as $v) {
        $query_fields_subdivisions[] = "`" . $v . "`";
    }
    foreach ($subdivisions as $subdivision) {
        $rel[$subdivision['Subdivision_ID']] = 0;
        // связка между старыми и новыми id
        $subdivision['Subdivision_Name'] = str_replace('%NAME%', $subdivision['Subdivision_Name'], $templates['sub_name']);
        $subdivision['Subdivision_Name'] = str_replace('%KEYWORD%', $subdivision['EnglishName'], $subdivision['Subdivision_Name']);
        $subdivision['EnglishName'] = str_replace('%KEYWORD%', $subdivision['EnglishName'], $templates['sub_keyword']);
        $subdivision['Parent_Sub_ID'] = $dest_parent_sub_id;
        $subdivision['Catalogue_ID'] = $dest_catalogue_id;
        $subdivision['Created'] = $subdivision['LastUpdated'] = date("Y-m-d H:i:s");
        $subdivision['Hidden_URL'] = $hidden_url . $subdivision['EnglishName'] . '/';
        if (!$nc_core->subdivision->validate_english_name($subdivision['EnglishName'])) {
            throw new Exception(CONTROL_CONTENT_SUBDIVISION_INDEX_ERROR_THREE_KEYWORD_INVALID . "<br/>" . $subdivision['EnglishName']);
        }
        //if ( $english_name == $subdivision['EnglishName'] ) {
        //  throw new Exception(TOOLS_COPYSUB_ERROR_KEYWORD_EXIST);
        //}
        if (in_array($subdivision['EnglishName'], $child_english_names)) {
            throw new Exception(TOOLS_COPYSUB_ERROR_KEYWORD_EXIST);
        }
        // нельзя скопировать раздел в подраздел этого же раздела
        if ($dest_parent_sub_id) {
            $childs = nc_get_subdivision_children($subdivision['Subdivision_ID']);
            if (!empty($childs) && in_array($dest_parent_sub_id, $childs)) {
                throw new Exception(TOOLS_COPYSUB_ERROR_LEVEL_COUNT);
            }
        }
        $query_values = array();
        foreach ($fields as $v) {
            $query_values[] = "'" . $db->escape($subdivision[$v]) . "'";
        }
        $insert_values_subdivisions[$subdivision['Subdivision_ID']] = "(" . join(',', $query_values) . ")";
    }
    $nc_core->event->execute("addSubdivisionPrep", $dest_catalogue_id, 0);
    foreach ($insert_values_subdivisions as $Subdivision_ID => $insert_value_subdivisions) {
        $db->query("INSERT INTO `Subdivision` (" . join(',', $query_fields_subdivisions) . ")  VALUES {$insert_value_subdivisions}");
        if ($db->is_error) {
            throw new nc_Exception_DB_Error($db->last_query, $db->last_error);
        }
        $inserted_id = $db->insert_id;
        $rel[$Subdivision_ID] = $inserted_id;
        if (!is_dir($nc_core->FILES_FOLDER . $inserted_id)) {
            @mkdir($nc_core->FILES_FOLDER . $inserted_id, $nc_core->DIRCHMOD);
            @chmod($nc_core->FILES_FOLDER . $inserted_id, $nc_core->DIRCHMOD);
        }
    }
    $nc_core->event->execute("addSubdivision", $dest_catalogue_id, $rel);
    // компоненты в разделе для копирования
    $sub_classes = !$with_сс ? null : $db->get_results("SELECT * FROM `Sub_Class`\n                                                     WHERE `Subdivision_ID` IN (" . join(',', $sub_ids) . ")\n                                                     ORDER BY `Sub_Class_ID`", ARRAY_A);
    $query_fields_subclasses = array();
    $insert_values_subclasses = array();
    if (!empty($sub_classes)) {
        $fields = array_keys($sub_classes[0]);
        unset($fields[0]);
        foreach ($fields as $v) {
            $query_fields_subclasses[] = "`" . $v . "`";
        }
        foreach ($sub_classes as $sub_class) {
            $rel_cc[$sub_class['Sub_Class_ID']] = 0;
            $sub_class['Subdivision_ID'] = $rel[$sub_class['Subdivision_ID']];
            $sub_class['Sub_Class_Name'] = str_replace('%NAME%', $sub_class['Sub_Class_Name'], $templates['cc_name']);
            $sub_class['EnglishName'] = str_replace('%KEYWORD%', $sub_class['EnglishName'], $templates['cc_keyword']);
            $sub_class['Created'] = $sub_class['LastUpdated'] = date("Y-m-d H:i:s");
            $sub_class['Catalogue_ID'] = $dest_catalogue_id;
            if (!$nc_core->sub_class->validate_english_name($sub_class['EnglishName'])) {
                throw new Exception(CONTROL_CONTENT_SUBDIVISION_INDEX_ERROR_THREE_KEYWORD_INVALID . "<br/>" . $sub_class['EnglishName']);
            }
            $query_values = array();
            foreach ($fields as $v) {
                $query_values[] = "'" . $db->escape($sub_class[$v]) . "'";
            }
            $insert_values_subclasses[$sub_class['Sub_Class_ID']] = "(" . join(',', $query_values) . ")";
        }
        foreach ($sub_classes as $sub_class) {
            $nc_core->event->execute("addSubClassPrep", $dest_catalogue_id, $sub_class['Subdivision_ID'], 0);
            $db->query("INSERT INTO `Sub_Class` (" . join(',', $query_fields_subclasses) . ")  VALUES {$insert_values_subclasses[$sub_class['Sub_Class_ID']]}");
            if ($db->is_error) {
                throw new nc_Exception_DB_Error($db->last_query, $db->last_error);
            }
            $inserted_id = $db->insert_id;
            $k = $sub_class['Sub_Class_ID'];
            $rel_cc[$k] = $inserted_id;
            $class_id = $sub_class['Class_ID'];
            $is_system_table = $db->get_var("SELECT `System_Table_ID` FROM `Class` WHERE `Class_ID` = '" . $class_id . "' ");
            $sub_id = $rel[$sub_class['Subdivision_ID']];
            $nc_core->event->execute("addSubClass", $dest_catalogue_id, $sub_id, $rel_cc[$k]);
            if (!is_dir($nc_core->FILES_FOLDER . $sub_id . "/" . $rel_cc[$k])) {
                @mkdir($nc_core->FILES_FOLDER . $sub_id . "/" . $rel_cc[$k], $nc_core->DIRCHMOD);
                @chmod($nc_core->FILES_FOLDER . $sub_id . "/" . $rel_cc[$k], $nc_core->DIRCHMOD);
            }
            // объекты для копирования
            $messages = !$with_object || $is_system_table ? null : $db->get_results("SELECT * FROM `Message" . $class_id . "` WHERE `Sub_Class_ID` = '" . $k . "' ORDER BY `Message_ID`", ARRAY_A);
            $query_fields_messages = array();
            $insert_values_messages = array();
            if (!empty($messages)) {
                $fields = array_keys($messages[0]);
                unset($fields[0]);
                foreach ($fields as $v) {
                    $query_fields_messages[] = "`" . $v . "`";
                }
                $msg_ids = array();
                $rel_message = array();
                foreach ($messages as $message) {
                    $rel_message[$message['Message_ID']] = 0;
                    $message['Subdivision_ID'] = $rel[$message['Subdivision_ID']];
                    $message['Sub_Class_ID'] = $rel_cc[$message['Sub_Class_ID']];
                    $message['Created'] = $message['LastUpdated'] = date("Y-m-d H:i:s");
                    $msg_ids[] = $message['Message_ID'];
                    $query_values = array();
                    foreach ($fields as $v) {
                        $query_values[] = "'" . $db->escape($message[$v]) . "'";
                    }
                    $insert_values_messages[$message['Message_ID']] = "(" . join(',', $query_values) . ")";
                }
                // копирование файлов объекта
                $file_fields = array();
                $tmp = $db->get_results("SELECT `Field_ID` AS `id`, `Field_Name` AS `name` FROM `Field` WHERE `Class_ID`='" . $class_id . "' AND `TypeOfData_ID` = '6' ", ARRAY_A);
                if ($tmp) {
                    foreach ($tmp as $v) {
                        $file_fields[$v['id']] = $v['name'];
                    }
                    $filetable = $db->get_results("SELECT * FROM `Filetable`\n                                   WHERE `Field_ID` IN (" . join(',', array_keys($file_fields)) . ")\n                                   AND `Message_ID` IN (" . join(',', $msg_ids) . ") ", ARRAY_A);
                }
                // Поля типа "множественная загрузка" в компоненте
                $multifile_fields = $db->get_results("SELECT `Field_ID`, `Format`, `Field_Name`\n                                    FROM `Field`\n                                    WHERE Class_ID='" . $class_id . "'\n                                    AND TypeOfData_ID='" . NC_FIELDTYPE_MULTIFILE . "'", ARRAY_A);
                foreach ($messages as $message) {
                    $message_id = $message['Message_ID'];
                    // событие
                    $nc_core->event->execute("addMessagePrep", $dest_catalogue_id, $rel[$message['Subdivision_ID']], $rel_cc[$message['Sub_Class_ID']], $class_id, 0);
                    $db->query("INSERT INTO `Message" . $class_id . "` (" . join(',', $query_fields_messages) . ")  VALUES {$insert_values_messages[$message_id]}");
                    if ($db->is_error) {
                        throw new nc_Exception_DB_Error($db->last_query, $db->last_error);
                    }
                    $inserted_id = $db->insert_id;
                    $k = $message_id;
                    $rel_message[$k] = $inserted_id;
                    // событие
                    $nc_core->event->execute("addMessage", $dest_catalogue_id, $rel[$message['Subdivision_ID']], $rel_cc[$message['Sub_Class_ID']], $class_id, $rel_message[$message_id]);
                    if (!empty($file_fields)) {
                        foreach ($file_fields as $field_id => $field_name) {
                            if ($value = $message[$field_name]) {
                                $is_copy = 0;
                                if (!empty($filetable)) {
                                    foreach ($filetable as $v) {
                                        if ($v['Message_ID'] == $message_id && $v['Field_ID'] == $field_id) {
                                            $file_path = rtrim($nc_core->FILES_FOLDER, '/') . $v['File_Path'] . $v['Virt_Name'];
                                            $new_name = md5($file_path . date("H:i:s d.m.Y") . uniqid("netcat"));
                                            $new_file_path = $rel[$message['Subdivision_ID']] . "/" . $rel_cc[$message['Sub_Class_ID']];
                                            @copy($file_path, $nc_core->FILES_FOLDER . $new_file_path . "/" . $new_name);
                                            $to_filetable[] = "('" . $db->escape($v['Real_Name']) . "', '" . $new_name . "', '/" . $new_file_path . "/',\n                                   '" . $v['File_Type'] . "', '" . $v['File_Size'] . "', '" . $rel_message[$message_id] . "',\n                                   '" . $field_id . "', '" . $v['Content_Disposition'] . "')";
                                            $is_copy = 1;
                                        }
                                    }
                                }
                                if ($is_copy) {
                                    continue;
                                }
                                $file_data = explode(':', $value);
                                $file_name = $file_data[0];
                                $ext = nc_substr($file_name, nc_strrpos($file_name, "."));
                                // расширение файла
                                if ($file_data[3]) {
                                    $new_name = nc_get_filename_for_original_fs($file_name, $nc_core->FILES_FOLDER . $rel[$message['Subdivision_ID']] . "/" . $rel_cc[$message['Sub_Class_ID']] . "/");
                                    @copy($nc_core->FILES_FOLDER . $file_data[3], $nc_core->FILES_FOLDER . $rel[$message['Subdivision_ID']] . "/" . $rel_cc[$message['Sub_Class_ID']] . "/" . $new_name);
                                    $dt = $file_data[0] . ":" . $file_data[1] . ":" . $file_data[2] . ":" . $rel[$message['Subdivision_ID']] . "/" . $rel_cc[$message['Sub_Class_ID']] . "/" . $new_name;
                                    $db->query("UPDATE `Message" . $class_id . "` SET `" . $field_name . "` = '" . $dt . "' WHERE `Message_ID` = '" . $rel_message[$message_id] . "'  ");
                                } else {
                                    @copy($nc_core->FILES_FOLDER . $field_id . "_" . $message_id . $ext, $nc_core->FILES_FOLDER . $field_id . "_" . $rel_message[$message_id] . $ext);
                                }
                            }
                        }
                    }
                    // проходим по каждому полю
                    foreach ((array) $multifile_fields as $field) {
                        $field_id = (int) $field['Field_ID'];
                        $settings_http_path = nc_standardize_path_to_folder($nc_core->HTTP_FILES_PATH . "/multifile/{$field_id}/");
                        $settings_path = nc_standardize_path_to_folder($nc_core->DOCUMENT_ROOT . '/' . $nc_core->SUB_FOLDER . '/' . $settings_http_path);
                        //получаем список файлов
                        $sql = "SELECT `Priority`, `Name`, `Size`, `Path`, `Preview` FROM `Multifield` WHERE `Field_ID` = {$field_id} AND `Message_ID` = {$message_id}";
                        $files = $db->get_results($sql, ARRAY_A);
                        foreach ((array) $files as $file) {
                            foreach (array('Path', 'Preview') as $path) {
                                $file_path = $file[$path];
                                if ($file_path) {
                                    $parts = explode('/', nc_standardize_path_to_file($file_path));
                                    $file_name = array_pop($parts);
                                    $new_file_name = nc_get_filename_for_original_fs($file_name, $settings_path);
                                    @copy($settings_path . $file_name, $settings_path . $new_file_name);
                                    $file[$path] = $settings_http_path . $new_file_name;
                                }
                            }
                            $priority = (int) $file['Priority'];
                            $name = $db->escape($file['Name']);
                            $size = (int) $file['Size'];
                            $path = $db->escape($file['Path']);
                            $preview = $db->escape($file['Preview']);
                            $sql = "INSERT INTO `Multifield` (`Field_ID`, `Message_ID`, `Priority`, `Name`, `Size`, `Path`, `Preview`) VALUES " . "({$field_id}, {$rel_message[$message_id]}, {$priority}, '{$name}', {$size}, '{$path}', '{$preview}')";
                            $db->query($sql);
                        }
                    }
                }
            }
        }
    }
    //при копировании разделов проставлялись нули, если поле RecordsPerPage было не заполнено
    $sub_cc_ids = join(', ', (array) $rel_cc);
    if (!empty($sub_cc_ids)) {
        $db->query("UPDATE `Sub_Class`\n                    SET `RecordsPerPage` = NULL\n                        WHERE `RecordsPerPage`= 0\n                          AND `Sub_Class_ID` IN ({$sub_cc_ids})");
    }
    // копирование файлов
    $system_fields = $nc_core->get_system_table_fields("Subdivision");
    $file_fields = array();
    if (!empty($system_fields)) {
        foreach ($system_fields as $v) {
            if ($v['type'] == 6) {
                $file_fields[$v['id']] = $v['name'];
            }
        }
    }
    if (!empty($file_fields)) {
        $filetable = $db->get_results("SELECT * FROM `Filetable`\n                                   WHERE `Field_ID` IN (" . join(',', array_keys($file_fields)) . ")\n                                   AND `Message_ID` IN (" . join(',', $sub_ids) . ") ", ARRAY_A);
        foreach ($subdivisions as $subdivision) {
            $sub_id = $subdivision['Subdivision_ID'];
            foreach ($file_fields as $field_id => $field_name) {
                if ($value = $subdivision[$field_name]) {
                    $is_copy = 0;
                    if (!empty($filetable)) {
                        foreach ($filetable as $v) {
                            if ($v['Message_ID'] == $sub_id && $v['Field_ID'] == $field_id) {
                                $file_path = rtrim($nc_core->FILES_FOLDER, '/') . $v['File_Path'] . $v['Virt_Name'];
                                $new_name = md5($file_path . date("H:i:s d.m.Y") . uniqid("netcat"));
                                @copy($file_path, $nc_core->FILES_FOLDER . $rel[$sub_id] . "/" . $new_name);
                                $to_filetable[] = " ('" . $db->escape($v['Real_Name']) . "', '" . $new_name . "', '/" . $rel[$sub_id] . "/',\n                                   '" . $v['File_Type'] . "', '" . $v['File_Size'] . "', '" . $rel[$sub_id] . "',\n                                   '" . $field_id . "', '" . $v['Content_Disposition'] . "')";
                                // $db->debug();
                                $is_copy = 1;
                            }
                        }
                    }
                    if ($is_copy) {
                        continue;
                    }
                    $file_data = explode(':', $value);
                    $file_name = $file_data[0];
                    $ext = nc_substr($file_name, nc_strrpos($file_name, "."));
                    // расширение файла
                    if ($file_data[3]) {
                        $new_name = nc_get_filename_for_original_fs($file_name, $nc_core->FILES_FOLDER . $rel[$sub_id] . "/");
                        @copy($nc_core->FILES_FOLDER . $file_data[3], $nc_core->FILES_FOLDER . $rel[$sub_id] . "/" . $new_name);
                        $dt = $file_data[0] . ":" . $file_data[1] . ":" . $file_data[3] . ":" . $rel[$sub_id] . "/" . $new_name;
                        $db->query("UPDATE `Subdivision` SET `" . $field_name . "` = '" . $dt . "' WHERE `Subdivision_ID` = '" . $rel[$sub_id] . "'  ");
                        //   $db->debug();
                    } else {
                        @copy($nc_core->FILES_FOLDER . $field_id . "_" . $sub_id . $ext, $nc_core->FILES_FOLDER . $field_id . "_" . $rel[$sub_id] . $ext);
                    }
                }
            }
        }
    }
    // update filetable
    if (!empty($to_filetable)) {
        $db->query("INSERT INTO `Filetable` (`Real_Name`, `Virt_Name`, `File_Path`,\n                                         `File_Type`, `File_Size`, `Message_ID`, `Field_ID`, `Content_Disposition` )\n                          VALUES " . join(',', $to_filetable) . " ");
    }
    // рекурсивное копирование подразделов
    if ($with_child) {
        foreach ($rel as $k => $v) {
            $childs = $db->get_col("SELECT `Subdivision_ID` FROM `Subdivision` WHERE `Parent_Sub_ID` = '" . $k . "' ");
            if ($childs) {
                nc_copy_subdivision($childs, 0, $v, $with_child, $with_сс, $with_object, $templates);
            }
        }
    }
    return 0;
}
Esempio n. 10
0
         ClassForm($ClassID, "index.php", 17, 2, 0);
     }
     break;
 case 18:
     // спросить, действительно ли удалять шаблон компонента
     BeginHtml($Title6, $Title3 . $Delimeter . $Title6, "http://" . $DOC_DOMAIN . "/management/class/");
     $perm->ExitIfNotAccess(NC_PERM_CLASS, 0, 0, 0, 0);
     ConfirmClassTemplateDeletion($ClassTemplate);
     break;
 case 19:
     // удаление шаблонов компонента
     BeginHtml($Title2, $Title2, "http://" . $DOC_DOMAIN . "/management/class/");
     $perm->ExitIfNotAccess(NC_PERM_CLASS, 0, 0, 0, 1);
     $UI_CONFIG = new ui_config_class_templates('edit', $ClassTemplate);
     foreach ($_POST as $key => $val) {
         if (nc_substr($key, 0, 6) == "Delete" && $val) {
             $isMoreClasses = CascadeDeleteClassTemplate($val);
         }
     }
     ClassTemplatesList($ClassTemplate);
     break;
 case 20:
     // список шаблонов компонента
     BeginHtml($Title2, $Title2, "http://" . $DOC_DOMAIN . "/management/class/");
     $perm->ExitIfNotAccess(NC_PERM_CLASS, 0, 0, 0, 0);
     if ($ClassID) {
         $UI_CONFIG = new ui_config_class_templates('edit', $ClassID);
     }
     ClassTemplatesList($ClassID);
     break;
 case 22:
Esempio n. 11
0
/**
 * Пропарсить формат поля
 * Для поля типа "Файл" возвращаемое значение - хэш-массив с ключами:
 * size - размер;
 * type - массив с mimetype. Каждый элемент - массив, 0 - то, что стоит до /, 1 - то, что стоит после
 * fs - тип файловой системы
 * disposition - content-disposition, 0 - inline, 1 - attachment
 * download - считать скачивания?
 *
 * Для поле "Текстовы блок":
 * html - разрешить тэги
 * br - перенос строки - <br>
 * fck - встроить редактор в поле
 * rows, cols - высота и шириина
 * bbcode - доступены bb-коды
 *
 * @param string format
 * @param int field type
 * @return array
 */
function nc_field_parse_format($format, $fieldtype)
{
    $ret = array();
    //возвращаемое значение
    $format = str_replace(' ', '', $format);
    // уберем пробелы
    switch ($fieldtype) {
        case NC_FIELDTYPE_FILE:
            // значения по умолчанию
            $ret['size'] = 0;
            $ret['type'] = '';
            $ret['fs'] = NC_FS_PROTECTED;
            $ret['download'] = 0;
            $ret['disposition'] = 0;
            // если формат пустой - вернуть значения по умолчанию
            if (!$format) {
                break;
            }
            // формат в общем случае:   size:type1/type,type2/type:fs1|fs2|fs3:inline|attachment:download
            //уберем из формата лишнее
            $format = array_shift(explode(';', $format));
            // определение фс
            if (preg_match('/(:?)(fs)(\\d+)/', $format, $match)) {
                $ret['fs'] = $match[3];
                // уберем из формата тип фс
                $format = nc_preg_replace('/(:?)(fs)(\\d+)/', '', $format);
            }
            if (!$format) {
                break;
            }
            // определение download
            if (strstr($format, 'download') !== false) {
                $ret['download'] = 1;
            }
            $format = nc_preg_replace('/(:?)(download)/', '', $format);
            // уберем download
            // определение content-disposition
            if (strstr($format, 'attachment') !== false) {
                $ret['disposition'] = 1;
            }
            $format = nc_preg_replace('/(:?)((attachment)|(inline))/', '', $format);
            // уберем attachment
            $format_array = explode(':', $format);
            if (empty($format_array)) {
                break;
            }
            if ($format_array[0]) {
                $ret['size'] = $format_array[0];
            }
            // размер
            //определение mimetype
            if ($format_array[1]) {
                $fileformat = explode(",", $format_array[1]);
                // определим каждый тип
                foreach ($fileformat as $k => $v) {
                    $ret['type'][$k] = explode('/', $v);
                }
            }
            break;
        case NC_FIELDTYPE_TEXT:
            // значения по умолчанию
            $ret['rows'] = 5;
            // количество строк
            $ret['cols'] = 60;
            // и столбцов
            $ret['html'] = 0;
            // разрешить тэги
            $ret['br'] = 0;
            // перенос строки - br
            $ret['fck'] = 0;
            // редактор встроен в поле
            $ret['panel'] = 0;
            $ret['typo'] = 0;
            $ret['bbcode'] = 0;
            if (!$format) {
                return $ret;
            }
            $params = array('html', 'br', 'fck', 'panel', 'typo', 'bbcode');
            // пробуем найти каждый параметр
            foreach ($params as $param) {
                if (($start = nc_strpos($format, $param)) !== false) {
                    $ret[$param] = intval(nc_substr($format, $start + nc_strlen($param) + 1, 1));
                }
            }
            // высоту и ширину ищем отдельно
            if ($format[0] > 0) {
                $format = strtok($format, ';');
                $ret['rows'] = strtok($format, ':');
                $ret['cols'] = strtok(':');
            }
            break;
        case NC_FIELDTYPE_DATETIME:
            $ret['type'] = '';
            $ret['calendar'] = 0;
            if (nc_strpos($format, 'calendar') !== false) {
                $ret['calendar'] = 1;
                $format = str_replace(array(';', 'calendar'), '', $format);
            }
            if ($format) {
                $ret['type'] = $format;
            }
            break;
        case NC_FIELDTYPE_STRING:
            $format = explode(':', $format);
            $ret['format'] = $format[0];
            $ret['protect_email'] = isset($format[1]) && $format[1] == 'protect';
            $ret['use_transliteration'] = $format[2];
            $ret['transliteration_field'] = $format[3];
            $ret['use_url_rules'] = $format[4];
            break;
    }
    return $ret;
}
Esempio n. 12
0
 /**
  * Получить информацию о разделе по url
  *
  * @param string $uri
  * @param int $catalogue номер сайта, по умолчанию определяется по домену
  * @param string $item требуемый параметр, если не задан - функция возврщает массив
  * @param bool $remove_date
  * @param bool $return_null_when_not_found если false и раздел не найден, возвращает информацию для раздела 404, иначе - null
  * @return mixed
  */
 public function get_by_uri($uri, $catalogue = 0, $item = '', $remove_date = true, $return_null_when_not_found = false)
 {
     $nc_core = nc_Core::get_object();
     // определение сайта
     if (!$catalogue) {
         $catalogue = $nc_core->catalogue->get_by_host_name($_SERVER['HTTP_HOST']);
         $catalogue = $catalogue['Catalogue_ID'];
     }
     $uri = rtrim(nc_substr($uri, 0, strrpos($uri, '/')), '/') . '/';
     if ($remove_date) {
         // find date in url
         $uri = preg_replace('|/\\d{4}/(?:\\d{2}/)?(?:\\d{2}/)?$|', '/', $uri);
     }
     // титульная страница
     if ($uri == "/" || $uri == "") {
         $res = $this->get_by_id($nc_core->catalogue->get_by_id($catalogue, "Title_Sub_ID"));
     }
     // поиск в кэше
     if (empty($res) && !empty($this->data)) {
         foreach ($this->data as $id => $values) {
             if ($values['Catalogue_ID'] == $catalogue && $values['Hidden_URL'] == $uri) {
                 $res = $this->data[$id];
             }
         }
     }
     // из базы
     if (empty($res)) {
         $res = $this->db->get_row("SELECT * FROM `Subdivision`\n                                        WHERE `Catalogue_ID` = '" . intval($catalogue) . "'\n                                          AND `Hidden_URL` = '" . $this->db->escape($uri) . "'", ARRAY_A);
         if ($res) {
             $res['_nc_final'] = 0;
             $this->data[$res['Subdivision_ID']] = $res;
         } else {
             if (!$return_null_when_not_found) {
                 $res = $this->get_by_id($nc_core->catalogue->get_current("E404_Sub_ID"));
             } else {
                 return null;
             }
         }
     }
     // processing system fields, inherit
     if (!$res['_nc_final']) {
         $res = $this->get_by_id($res['Subdivision_ID']);
     }
     if ($item) {
         return array_key_exists($item, $res) ? $res[$item] : "";
     }
     return $res;
 }
Esempio n. 13
0
function CascadeExportClass($ClassID)
{
    // system superior object
    $nc_core = nc_Core::get_object();
    include $nc_core->DOCUMENT_ROOT . $nc_core->ADMIN_PATH . "tar.inc.php";
    $db =& $nc_core->db;
    $VersionNumber = $nc_core->get_settings("VersionNumber");
    $SystemID = $nc_core->get_settings("SystemID");
    $LastPatch = $nc_core->get_settings("LastPatch");
    $ClassID = intval($ClassID);
    // Блокируем таблицы
    $LockTables = "LOCK TABLES `Class` WRITE, `Field` WRITE, ";
    $LockTables .= "`Message" . $ClassID . "` WRITE, ";
    $LockTables .= "`Sub_Class` WRITE";
    $LockResult = $db->query($LockTables);
    // Экспортируем данные из таблицы Class
    $SelectClass = $db->get_row("SELECT * FROM `Class` WHERE `Class_ID` = '" . $ClassID . "'", ARRAY_A);
    $File_Mode = $SelectClass['File_Mode'];
    $FieldsForExport = array_keys($SelectClass);
    $Qry = array();
    foreach ($FieldsForExport as $Field) {
        if ($Field == "Class_ID") {
            continue;
        }
        // component template export aborted!
        if ($Field == "ClassTemplate" && $SelectClass[$Field] != 0) {
            return false;
        }
        $Qry[] = "`" . $Field . "` = '" . addcslashes($SelectClass[$Field], "\\'\r\n") . "'";
    }
    $TempText .= "<class><![CDATA[INSERT INTO `Class` SET " . join(", ", $Qry) . ";]]></class>\n";
    // component templates
    $ClassTemplatesArr = $db->get_results("SELECT * FROM `Class` WHERE `ClassTemplate` = '" . $ClassID . "'", ARRAY_A);
    if (!empty($ClassTemplatesArr)) {
        $TempText .= "<templates>";
        $TempIds = "<tpl_ids>";
        foreach ($ClassTemplatesArr as $row) {
            $Qry = array();
            foreach ($FieldsForExport as $Field) {
                // skip ID
                if ($Field == "Class_ID") {
                    $TempIds .= "<tpl_id>{$row[$Field]}</tpl_id>";
                    continue;
                }
                // set `ClassTemplate`
                if ($Field == "ClassTemplate") {
                    $Qry[] = "`ClassTemplate` = '%INSERT_ID%'";
                    continue;
                }
                if (!$File_Mode && strpos($row[$Field], '<![CDATA[')) {
                    $row[$Field] = str_replace('<![CDATA[', '%CDATA_START%', $row[$Field]);
                    $row[$Field] = str_replace(']]>', '%CDATA_END%', $row[$Field]);
                }
                $Qry[] = "`" . $Field . "` = '" . addcslashes($row[$Field], "\\'\r\n") . "'";
            }
            // template str
            $TempText .= "<template><![CDATA[INSERT INTO `Class` SET " . join(", ", $Qry) . ";]]></template>\n";
        }
        $TempText .= "</templates>";
        $TempIds .= "</tpl_ids>";
    }
    #Экспортируем данные из таблицы Field
    $classFields = $db->get_results("SELECT * FROM `Field` WHERE `Class_ID` = '" . $ClassID . "'");
    $db->query("SET SQL_QUOTE_SHOW_CREATE = 1");
    $temp_result = $db->get_row("SHOW CREATE TABLE `Message" . $ClassID . "`", ARRAY_N);
    $lastpos = strrpos($temp_result[1], ")");
    $CreateTable = nc_substr($temp_result[1], 0, $lastpos);
    $CreateTable = str_ireplace("CREATE TABLE `message" . $ClassID . "`", "CREATE TABLE `Message%INSERT_ID%`", $CreateTable);
    $CreateTable = str_ireplace(array("\r", "\n"), "", $CreateTable);
    $CreateTable .= ") ENGINE=MyISAM;\n";
    $TempText .= '<message_tbl>' . $CreateTable . '</message_tbl>';
    // Экспортируем данные из таблицы Field
    $classFields = $db->get_results("SELECT * FROM `Field` WHERE `Class_ID` = '" . $ClassID . "'");
    if (!empty($classFields)) {
        $insert = "<fields>";
        foreach ($classFields as $SelectField) {
            //определяем тип данных
            $alter = " ";
            switch ($SelectField->TypeOfData_ID) {
                case 1:
                    $alter .= "char(255)";
                    break;
                case 2:
                    $alter .= "int";
                    break;
                case 3:
                    $alter .= "text";
                    break;
                case 4:
                    $alter .= "int";
                    break;
                case 5:
                    $alter .= "tinyint";
                    break;
                case 6:
                    $alter .= "char(255)";
                    break;
                case 7:
                    $alter .= "double";
                    break;
                case 8:
                    $alter .= "datetime";
                    break;
                case 9:
                    $alter .= "int";
                    break;
                case 10:
                    $alter .= "text";
                    break;
            }
            if ($SelectField->DefaultState != "" && $SelectField->TypeOfData_ID != 3) {
                $alter .= " NOT NULL DEFAULT '" . $SelectField->DefaultState . "'";
            } elseif ($SelectField->NotNull) {
                $alter .= " NOT NULL";
            } else {
                $alter .= " NULL";
            }
            $insert .= "<field>INSERT INTO Field (`Class_ID`, `Field_Name`, `Description`, `TypeOfData_ID`, `Format`, `NotNull`, `Priority`, `DoSearch`, `DefaultState`, `TypeOfEdit_ID`) VALUES";
            $insert .= " (%INSERT_ID%, '" . str_replace("'", "\\'", $SelectField->Field_Name) . "', '" . str_replace("'", "\\'", $SelectField->Description) . "', " . $SelectField->TypeOfData_ID . ", '" . str_replace("'", "\\'", $SelectField->Format) . "', " . $SelectField->NotNull . ", " . $SelectField->Priority . ", " . $SelectField->DoSearch . ", '" . str_replace("'", "\\'", $SelectField->DefaultState) . "', " . $SelectField->TypeOfEdit_ID . ");</field>\n";
        }
        $insert .= "</fields>";
    }
    $TempText .= $insert;
    $db->query("UNLOCK TABLES");
    list($SystemName, $SystemColor) = nc_system_name_by_id($SystemID);
    $export_id_str = "-- NetCat " . $VersionNumber . " " . $SystemName . " [" . $LastPatch . "] component file, generated " . date("Y-m-d H:i:s");
    $output = "<?xml version=\"1.0\"?>\n<data>\n    <version>{$VersionNumber}</version>\n    <export_id>{$export_id_str}</export_id>\n    <class_id>{$ClassID}</class_id>";
    if (isset($TempIds)) {
        $output .= $TempIds;
    }
    $output .= "<sql_data>\n        {$TempText}</sql_data>\n";
    if ($File_Mode) {
        $tmp_file_name = $nc_core->TMP_FOLDER . "netcat_class_{$ClassID}.tgz";
        $dump_file = nc_tgz_create($tmp_file_name, $ClassID, $nc_core->HTTP_TEMPLATE_PATH . 'class/');
        $tar_contents = file_get_contents($tmp_file_name);
        $output .= "<tar_data>" . base64_encode($tar_contents) . "</tar_data>\n";
        unlink($tmp_file_name);
    }
    $output .= "</data>";
    // все компоненты в utf-8
    if (!$nc_core->NC_UNICODE) {
        $ret = $nc_core->utf8->win2utf($ret);
    }
    return $output;
}
Esempio n. 14
0
function ConfirmDeletion($Class_Group = '')
{
    global $db;
    global $UI_CONFIG;
    $ask = false;
    $class_id = 0;
    $class_id_array = array();
    print "<form method='post' action='index.php'>";
    $nc_core = nc_Core::get_object();
    $template_class_id_array = array();
    $input = $nc_core->input->fetch_get_post();
    if (!empty($input)) {
        foreach ($input as $key => $val) {
            if (nc_substr($key, 0, 6) == "Delete" && $val) {
                $ask = true;
                $class_id = intval($val);
                $SelectArray = $db->get_var("SELECT `Class_Name` FROM `Class` WHERE `Class_ID`='" . $class_id . "'");
                // check template existence
                if (!$SelectArray) {
                    nc_print_status(sprintf(CONTROL_CLASS_CLASS_NOT_FOUND, $class_id), 'error');
                    continue;
                }
                $class_id_array[] = $class_id;
                print "<input type='hidden' name='" . $key . "' value='" . $val . "'>";
                $class_counter++;
                $template_ids = $db->get_col("SELECT Class_ID FROM Class WHERE ClassTemplate = '" . $class_id . "'");
                if ($template_ids) {
                    $template_class_id_array = array_merge($template_class_id_array, $template_ids);
                }
            }
        }
    }
    if (!$ask) {
        return false;
    }
    if ($class_counter > 1) {
        $UI_CONFIG = new ui_config_class("delete", "", $ClassGroup);
        $post_f1 = CONTROL_CONTENT_CATALOUGE_FUNCS_CATALOGUEFORM_WARNING_SITEDELETE_I;
        $post_f2 = CONTROL_CONTENT_CATALOUGE_FUNCS_CATALOGUEFORM_WARNING_SITEDELETE_U;
    } else {
        print "<input type='hidden' name='ClassGroup' value='" . $db->get_var("SELECT md5(`Class_Group`) FROM `Class` WHERE `Class_ID` = '" . $class_id . "' GROUP BY `Class_Group`") . "'>";
        $UI_CONFIG = new ui_config_class('delete', $class_id, $ClassGroup);
    }
    print $nc_core->token->get_input();
    print "<input type='hidden' name='fs' value='" . $_REQUEST['fs'] . "'>" . "<input type='hidden' name='phase' value='7'>" . "</form>";
    if (!empty($class_id_array)) {
        nc_print_status(CONTROL_CLASS_CLASS_DELETE_WARNING, 'info', array($post_f1, $post_f2));
        nc_list_class_use($class_id_array, 0, 0);
        if ($template_class_id_array) {
            echo "<br/>";
            nc_list_class_template_use($template_class_id_array);
        }
    }
    $UI_CONFIG->actionButtons[] = array("id" => "submit", "caption" => CONTROL_CONTENT_CATALOUGE_FUNCS_CATALOGUEFORM_CONFIRMDELETE, "action" => "mainView.submitIframeForm()", "red_border" => true);
    return true;
}
Esempio n. 15
0
 $widget_id = $post['widget_id'];
 $res = (array) $db->get_results("SELECT `Field_Name`, `Field_ID`, `NotNull`, `Description`, `Format`, `TypeOfData_ID` FROM `Field` WHERE `Widget_Class_ID`={$widget_class_id}");
 $widget_fields = array();
 foreach ($res as $res_row) {
     $fieldIDs[$res_row->Field_Name] = $res_row->Field_ID;
     $fieldNotNull[$res_row->Field_ID] = $res_row->NotNull;
     $fieldDescriptions[$res_row->Field_ID] = $res_row->Description;
     $fieldTypes[$res_row->Field_ID] = $res_row->TypeOfData_ID;
     $fieldFormats[$res_row->Field_ID] = $res_row->Format;
     $widget_fields[$res_row->Field_Name] = $res_row;
 }
 foreach ($post as $key => $val) {
     if (nc_substr($key, 0, 5) == "field") {
         $fields[intval(nc_substr($key, 5))] = $val;
     } elseif (nc_substr($key, 0, 2) == "f_") {
         $field_name = nc_substr($key, 2);
         $fieldId = $fieldIDs[$field_name];
         if ($fieldId) {
             $fields[$fieldId] = $val;
         }
     }
 }
 BeginHtml($Title2, $Title2, "http://" . $DOC_DOMAIN . "/management/class/");
 // проверка символов для ключевого слова
 if (!$nc_core->widget->validate_keyword($post['Keyword'])) {
     nc_print_status(CONTROL_CONTENT_SUBDIVISION_SUBCLASS_ERROR_KEYWORD_INVALID, 'error');
     nc_widget_edit_form($post, $widget_id);
     exit;
 }
 if (is_exist_keyword($post['Keyword'], 0, $widget_id)) {
     nc_print_status(WIDGET_ADD_ERROR_KEYWORD_EXIST, 'error');
Esempio n. 16
0
/**
 * Insert into DB properties of field
 *
 * @param bool is field in system table
 * @return int field id ,0 -  unknown error, -1 = incorrect field name, -2 = field name is mysql_keyword, -3 = field already exits
 *                                           -4 = incorrect field format
 *
 */
function FieldCompleted()
{
    global $db;
    global $ClassID, $SystemTableID, $widgetclass_id;
    global $Inheritance, $DoSearch, $InTableView;
    global $FieldID, $FieldName, $Description, $TypeOfData_ID, $TypeOfEdit_ID, $Format, $Format_String, $Format_FS, $Extension, $NotNull, $Priority, $DefaultState, $attachment, $download;
    global $format_height, $format_width, $format_html, $format_br, $format_fck, $format_panel, $format_typo, $format_bbcode, $use_calendar, $protect_email, $use_transliteration, $transliteration_field, $use_url_rules;
    global $isSys, $widgetclass_id;
    $nc_core = nc_Core::get_object();
    $input = $nc_core->input;
    $ClassID = intval($ClassID);
    $FieldID = intval($FieldID);
    if ($TypeOfData_ID == 1) {
        $Format = $Format_String;
    }
    if ($FieldID) {
        $TableName = $isSys ? GetSystemTableName(GetSystemTableIDByFieldID($FieldID)) : "Message" . GetClassIDByFieldID($FieldID);
    } else {
        $TableName = $isSys ? GetSystemTableName($SystemTableID) : "Message" . $ClassID;
    }
    // widgets
    $widgetclass_id += 0;
    if ($FieldID) {
        $widgetclass_id = $db->get_var("SELECT `Widget_Class_ID` FROM `Field` WHERE `Field_ID`= '" . $FieldID . "'");
    }
    $NotNull += 0;
    $DoSearch += 0;
    $InTableView += 0;
    $Inheritance += 0;
    $Priority += 0;
    $format_height += 0;
    $format_width += 0;
    $format_html += 0;
    $format_br += 0;
    $format_fck += 0;
    $format_panel += 0;
    $format_typo += 0;
    $format_bbcode += 0;
    $format_use_resize = (int) $input->fetch_post('format_use_resize');
    $format_resize_width = (int) $input->fetch_post('format_resize_width');
    $format_resize_height = (int) $input->fetch_post('format_resize_height');
    $format_use_crop = (int) $input->fetch_post('format_use_crop');
    $format_crop_x0 = (int) $input->fetch_post('format_crop_x0');
    $format_crop_y0 = (int) $input->fetch_post('format_crop_y0');
    $format_crop_x1 = (int) $input->fetch_post('format_crop_x1');
    $format_crop_y1 = (int) $input->fetch_post('format_crop_y1');
    $format_crop_ignore = (int) $input->fetch_post('format_crop_ignore');
    $format_crop_ignore_width = (int) $input->fetch_post('format_crop_ignore_width');
    $format_crop_ignore_height = (int) $input->fetch_post('format_crop_ignore_height');
    $format_use_preview = (int) $input->fetch_post('format_use_preview');
    $format_preview_width = (int) $input->fetch_post('format_preview_width');
    $format_preview_height = (int) $input->fetch_post('format_preview_height');
    $use_calendar += 0;
    // float field
    if ($TypeOfData_ID == 7) {
        $DefaultState = str_replace(",", ".", $DefaultState);
    }
    $FieldName = str_replace(' ', '', $FieldName);
    if (!isCorrectFormat($Format, $TypeOfData_ID)) {
        return -4;
    }
    if (nc_is_mysql_keyword($FieldName)) {
        return -2;
    }
    // Добавим к Формату тип файловой системы\ настройки textarea
    if ($TypeOfData_ID == NC_FIELDTYPE_FILE) {
        if (!$Format_FS) {
            $Format_FS = NC_FS_SIMPLE;
        }
        $Format .= ":fs" . $Format_FS;
        $Format .= ":" . ($attachment ? 'attachment' : 'inline');
        $Format .= $download ? ':download' : '';
        if (nc_substr($Format, 0, 1) == ':') {
            $Format = nc_substr($Format, 1);
        }
        $Format .= ";";
        $Format .= "use_resize:" . $format_use_resize . ";";
        $Format .= "resize_width:" . $format_resize_width . ";";
        $Format .= "resize_height:" . $format_resize_height . ";";
        $Format .= "use_crop:" . $format_use_crop . ";";
        $Format .= "crop_x0:" . $format_crop_x0 . ";";
        $Format .= "crop_y0:" . $format_crop_y0 . ";";
        $Format .= "crop_x1:" . $format_crop_x1 . ";";
        $Format .= "crop_y1:" . $format_crop_y1 . ";";
        $Format .= "crop_ignore:" . $format_crop_ignore . ";";
        $Format .= "crop_ignore_width:" . $format_crop_ignore_width . ";";
        $Format .= "crop_ignore_height:" . $format_crop_ignore_height . ";";
        $Format .= "use_preview:" . $format_use_preview . ";";
        $Format .= "preview_width:" . $format_preview_width . ";";
        $Format .= "preview_height:" . $format_preview_height . ";";
    } else {
        if ($TypeOfData_ID == NC_FIELDTYPE_TEXT) {
            $Format = ($format_height ? $format_height : 5) . ":" . ($format_width ? $format_width : 60) . ";";
            $Format .= "html:" . $format_html . ";br:" . $format_br . ";fck:" . $format_fck . ";";
            $Format .= "panel:" . $format_panel . ";typo:" . $format_typo . ";bbcode:" . $format_bbcode . ";";
        } else {
            if ($TypeOfData_ID == NC_FIELDTYPE_DATETIME && $use_calendar) {
                $Format .= ($Format ? ";" : "") . 'calendar';
            } else {
                if ($TypeOfData_ID == NC_FIELDTYPE_STRING) {
                    if ($Format == 'email' && $protect_email) {
                        $Format .= ':protect';
                    } else {
                        $Format .= ':';
                    }
                    if ($use_transliteration) {
                        $Format .= ':' . $use_transliteration;
                        $Format .= ':' . $transliteration_field;
                        $Format .= ':' . $use_url_rules;
                    }
                } else {
                    if ($TypeOfData_ID == NC_FIELDTYPE_MULTIFILE) {
                        $Format .= ";";
                        $Format .= "use_resize:" . $format_use_resize . ";";
                        $Format .= "resize_width:" . $format_resize_width . ";";
                        $Format .= "resize_height:" . $format_resize_height . ";";
                        $Format .= "use_crop:" . $format_use_crop . ";";
                        $Format .= "crop_x0:" . $format_crop_x0 . ";";
                        $Format .= "crop_y0:" . $format_crop_y0 . ";";
                        $Format .= "crop_x1:" . $format_crop_x1 . ";";
                        $Format .= "crop_y1:" . $format_crop_y1 . ";";
                        $Format .= "crop_ignore:" . $format_crop_ignore . ";";
                        $Format .= "crop_ignore_width:" . $format_crop_ignore_width . ";";
                        $Format .= "crop_ignore_height:" . $format_crop_ignore_height . ";";
                        $Format .= "use_preview:" . $format_use_preview . ";";
                        $Format .= "preview_width:" . $format_preview_width . ";";
                        $Format .= "preview_height:" . $format_preview_height . ";";
                    }
                }
            }
        }
    }
    $Description = htmlspecialchars($Description);
    $Extension = $db->escape($Extension);
    // Add new field
    if (!$FieldID) {
        if (count($db->get_results($widgetclass_id ? "SELECT * FROM `Field` WHERE `Widget_Class_ID`='" . $widgetclass_id . "' AND `Field_Name`='" . $FieldName . "'" : "SHOW FIELDS FROM `" . $TableName . "` LIKE '" . $FieldName . "'"))) {
            return -3;
        }
        $fl1 = $isSys ? "`System_Table_ID`" : ($widgetclass_id ? "`Widget_Class_ID`" : "`Class_ID`");
        $fl2 = $isSys ? "`Inheritance`" : "`DoSearch`";
        $insert_field = "`Field` (" . $fl1 . ", " . $fl2 . ", `Field_Name`,`Description`,`TypeOfData_ID`,`Format`,`Extension`, `NotNull`,`Priority`,`DefaultState`,`TypeOfEdit_ID`,`InTableView`)";
        $value = " VALUES ('";
        $value .= $isSys ? $SystemTableID . "','" . $Inheritance : ($widgetclass_id ? $widgetclass_id . "','" . $DoSearch : $ClassID . "','" . $DoSearch);
        $value .= "','" . $FieldName . "','" . $Description . "'," . $TypeOfData_ID . ",'" . $Format . "', '" . $Extension . "' ," . $NotNull . "," . $Priority . ",'" . $DefaultState . "','" . $TypeOfEdit_ID . "','" . $InTableView . "')";
        $query = "INSERT INTO " . $insert_field . $value;
        if (!$FieldName || nc_preg_match("/[^a-zA-Z0-9_]/", $FieldName)) {
            return -1;
        }
        if (!$FieldName || nc_preg_match("/^[\\d]+/", $FieldName)) {
            return -5;
        }
        // check if field name is already exists
        if (!$widgetclass_id) {
            $table = $ClassID ? "`Message" . $ClassID . "`" : $db->get_var("select `System_Table_Name` from `System_Table` where `System_Table_ID`=" . $SystemTableID);
            if ($db->column_exists($table, $FieldName)) {
                return -3;
            }
        }
        if ($db->query($query)) {
            $CurrentFieldID = $db->insert_id;
            if (!$widgetclass_id) {
                ColumnInMessage($CurrentFieldID, 1, $db);
            }
        }
        return $CurrentFieldID;
    } else {
        $NewFieldName = false;
        if (!$widgetclass_id) {
            if (!$FieldName || nc_preg_match("/[^a-zA-Z0-9_]/", $FieldName)) {
                return -1;
            }
            if (!$FieldName || nc_preg_match("/^[\\d]+/", $FieldName)) {
                return -5;
            }
            $sql = "SELECT `Field_Name` FROM `Field` WHERE `Field_ID` = {$FieldID} LIMIT 1";
            $OldFieldName = $db->get_var($sql);
            if ($FieldName != $OldFieldName) {
                if ($db->column_exists($TableName, $FieldName)) {
                    return -3;
                }
                $NewFieldName = $FieldName;
            }
        }
        $query = "UPDATE `Field` SET `Description`='" . $Description . "',`TypeOfData_ID`='" . $TypeOfData_ID . "',`Format`='" . $Format . "', `Extension` = '" . $Extension . "', `NotNull`='" . $NotNull;
        $query .= "',`Priority`='" . $Priority . "',`DefaultState`='" . $DefaultState . "',`TypeOfEdit_ID`='" . $TypeOfEdit_ID . "',`InTableView`='" . $InTableView . "'";
        $query .= $isSys ? ", `Inheritance`='" . $Inheritance . "'" : ", `DoSearch`='" . $DoSearch . "'";
        $query .= " WHERE `Field_ID`='" . $FieldID . "'";
        if (($db->query($query) || $NewFieldName) && !$widgetclass_id) {
            ColumnInMessage($FieldID, 2, $db, $NewFieldName);
        }
        return $FieldID;
    }
    return 0;
}