protected function prepare_resource_parameters() { $component_id = $this->component_id; $object_data = $this->object_data; $action = $this->action; $format = $this->format; $add_date = $this->add_date; $query_variables = $this->query_variables; $object_data_is_numeric = (int) $object_data == $object_data; $object_data_is_array = !$object_data_is_numeric && is_array($object_data); if ((int) $component_id != $component_id && $component_id != 'User' || !$object_data_is_array && !$object_data_is_numeric) { return false; } if (!$action) { $action = 'full'; } if ($object_data_is_array) { $object_params = $object_data; if (!isset($object_params['action']) || $object_params['action'] != $action) { $object_params['action'] = $action; } if (!isset($object_params['format']) || $object_params['format'] != $format) { $object_params['format'] = $format; } if (!$add_date) { $object_params['date'] = null; } } else { // it must be an ID then if ($add_date) { $date_field = nc_core::get_object()->get_component($component_id)->get_date_field(); } else { $date_field = false; } $db = nc_db(); $object_id = (int) $object_data; $object_data = $db->get_row("SELECT `Message_ID`, `Sub_Class_ID`, `Keyword`" . ($date_field ? ", `" . $db->escape($date_field) . "`" : "") . "\n FROM `Message{$component_id}`\n WHERE `Message_ID` = {$object_id}", ARRAY_A); if (!is_array($object_data)) { return false; } try { $infoblock_settings = nc_core::get_object()->sub_class->get_by_id($object_data['Sub_Class_ID']); } catch (Exception $e) { return false; } $object_params = array('site_id' => $infoblock_settings['Catalogue_ID'], 'folder' => $infoblock_settings['Hidden_URL'], 'folder_id' => $infoblock_settings['Subdivision_ID'], 'infoblock_id' => $infoblock_settings['Sub_Class_ID'], 'infoblock_keyword' => $infoblock_settings['EnglishName'], 'object_id' => $object_data['Message_ID'], 'object_keyword' => $object_data['Keyword'], 'action' => $action, 'format' => $format, 'date' => $date_field && $object_data[$date_field] ? date("Y-m-d", strtotime($object_data[$date_field])) : null, 'variables' => null); } if ($query_variables) { if (isset($object_params['variables'])) { $object_params['variables'] = array_merge($object_params['variables'], $query_variables); } else { $object_params['variables'] = $query_variables; } } return $object_params; }
public function __construct(nc_template_view $template_view, $partial_file, array $data = array()) { $this->template_view = $template_view; if (nc_check_file($partial_file)) { $this->partial_file = $partial_file; } $this->data = $data; $this->data['nc_core'] = nc_core(); $this->data['db'] = nc_db(); }
/** * @throws Exception * @throws nc_record_exception * @return static */ public function delete() { $site_id = (int) $this->get('site_id'); $priority = (int) $this->get('priority'); try { parent::delete(); if ($site_id && $priority) { nc_db()->query("UPDATE `{$this->table_name}`\n SET `Priority` = `Priority` - 1\n WHERE `Site_ID` = {$site_id}\n AND `Priority` > {$priority}"); } } catch (nc_record_exception $e) { throw $e; } return $this; }
protected function execute($type, $exec_method = 'query', $force = false) { if ($this->before_execute($type) === FALSE) { return; } $result_type = $this->result_type ? $this->result_type : $this->default_result_type; $sql = $this->make_query($type, $force); $this->reset_data(); $this->last_query = $sql; $this->result_type = null; if ($sql) { $this->last_result = nc_db()->{$exec_method}($sql, $result_type); } else { $this->last_result = false; } $this->after_execute($type); return $this->last_result; }
protected function generate_aggregator($widget_id, $settings) { if (is_string($settings) && $settings[0] == 'a') { $settings = unserialize($settings); } else { $settings = (array) $settings; } $widget = nc_db_table::make('Widget')->where_id($widget_id)->get_row(); $fields = array(); $nc_core = nc_core(); $db = nc_db(); $widget_class_id = $widget['Widget_Class_ID']; $field_values = nc_db_table::make('Widget_Field')->where('Widget_ID', $widget_id)->get_list('Field_ID', 'Value'); $result = $db->get_results("SELECT `Field_ID`, `Field_Name`, `DefaultState` FROM `Field` WHERE `Widget_Class_ID`='" . $widget_class_id . "'", ARRAY_A); foreach ($result as $row) { $field_id = $row['Field_ID']; $fields[$row['Field_Name']] = isset($field_values[$field_id]) ? $field_values[$field_id] : $row['DefaultState']; } extract($fields, EXTR_PREFIX_ALL, 'f'); $widget_view = new nc_widget_view($this->core->WIDGET_TEMPLATE_FOLDER, nc_db()); $widget_view->load($widget['Widget_Class_ID']); include $widget_view->get_field_path('Settings'); ob_start(); include $widget_view->get_field_path('Template'); return ob_get_clean(); }
protected function load_classificator() { static $cache = array(); if (!isset($cache[$this->classificator])) { $db = nc_db(); $clft = $db->escape($this->classificator); $res = $db->get_results("SELECT * FROM `Classificator` WHERE `Table_Name` = '" . $clft . "' ", ARRAY_A); if (!$res) { return sprintf(NETCAT_CUSTOM_ONCE_ERROR_CLASSIFICATOR, $this->classificator); } switch ($res['Sort_Type']) { case 1: $sort = "`" . $clft . "_Name`"; break; case 2: $sort = "`" . $clft . "_Priority`"; break; default: $sort = "`" . $clft . "_ID`"; } // просто узнаем элементы списка $elements = $db->get_results("SELECT `" . $clft . "_ID` as `id`, `" . $clft . "_Name` as `name`\n FROM `Classificator_" . $clft . "`\n WHERE `Checked` = '1'\n ORDER BY " . $sort . " " . ($res['Sort_Direction'] == 1 ? "DESC" : "ASC") . "", ARRAY_A); if (!$elements) { return sprintf(NETCAT_CUSTOM_ONCE_ERROR_CLASSIFICATOR_EMPTY, $res['Classificator_Name']); } $cache[$this->classificator] = $elements; } foreach ($cache[$this->classificator] as $v) { $this->values[$v['id']] = $v['name']; } return true; }
/** * Возвращает имя записи в списке (классификаторе) $classifier с ID = $id. * @param string $classifier * @param int $id * @param bool $should_cache * @return null|string */ function nc_get_list_item_name($classifier, $id, $should_cache = true) { static $local_cache = array(); $cache_key = "{$classifier}:{$id}"; $id = (int) $id; if (!$id || !preg_match("/^\\w+\$/", $classifier)) { return ''; } if (!array_key_exists($cache_key, $local_cache)) { $name = nc_db()->get_var("SELECT `{$classifier}_Name`\n FROM `Classificator_{$classifier}`\n WHERE `{$classifier}_ID` = {$id}"); if (!$should_cache) { return $name; } $local_cache[$cache_key] = $name; } return $local_cache[$cache_key]; }
/** * Загружает данные из таблицы Filetable для всех объектов с указанными ID. * * @param int|string $component_id * @param array $object_ids */ public function preload_filetable_values($component_id, array $object_ids) { $fields = $this->get_all_fields($component_id); if (!$fields) { return; // no file fields } $empty_values = array(); $field_ids = ""; foreach ($fields as $field_name => $field_settings) { $field_ids .= "," . $field_settings['id']; foreach ($object_ids as $object_id) { $empty_values["{$component_id}:{$object_id}:{$field_name}"] = null; } } $field_ids = substr($field_ids, 1); // remove unwanted comma from the beginning of the string $db = nc_db(); $object_ids = join(",", $object_ids); if (!preg_match("/^[\\d,]+\$/", $object_ids)) { return; // $ids array seems to contain incorrect values } $this->filetable_values = array_merge($empty_values, $this->filetable_values, (array) $db->get_results("SELECT ft.*, CONCAT('" . $db->escape($component_id) . "', ':', ft.`Message_ID`, ':', f.`Field_Name`) AS `Cache_Key`" . " FROM `Filetable` AS ft JOIN `Field` AS f USING (`Field_ID`)" . " WHERE ft.`Message_ID` IN ({$object_ids})" . " AND ft.`Field_ID` IN ({$field_ids})", ARRAY_A, "Cache_Key")); }
protected function get_data_from_source($source) { $data = array(); if (!empty($source['class_id'])) { $table = nc_db_table::make('Message' . (int) $source['class_id'], 'Message_ID'); if (!empty($source['subclass_id'])) { $table->where('Sub_Class_ID', $source['subclass_id']); } if ($source['order_by']) { $table->raw('order_by', $source['order_by']); } if ($source['where']) { $table->where($source['where']); } if ($source['limit']) { $table->limit($source['limit']); } $data = $table->get_result(); if ($source['bindings']) { $this->bind_fields($data, $source['bindings']); } $message_ids = array(); foreach ($data as $i => $row) { $message_ids[] = $row['Message_ID']; } $full_links = array(); # основной запрос для построения пути $result = nc_db()->get_results("SELECT m.`Message_ID`, CONCAT(sub.`Hidden_URL`, IF(m.`Keyword` <> '', m.`Keyword`, CONCAT(cc.`EnglishName`, '_', m.`Message_ID`)), '.html') AS fullLink\n FROM `Message" . $source['class_id'] . "` AS m\n LEFT JOIN `Subdivision` AS sub\n ON m.`Subdivision_ID` = sub.`Subdivision_ID`\n LEFT JOIN `Sub_Class` AS cc\n ON m.`Sub_Class_ID` = cc.`Sub_Class_ID`\n WHERE m.`Message_ID` IN (" . implode(',', $message_ids) . ")", ARRAY_A); foreach ($result as $row) { $full_links[$row['Message_ID']] = $row['fullLink']; } $result = array(); foreach ($data as $i => $row) { foreach ($row as $k => $v) { $result[$i]['f_' . $k] = $v; } $result[$i]['f_RowID'] = $row['Message_ID']; $result[$i]['fullLink'] = 'http://' . $_SERVER['HTTP_HOST'] . $full_links[$row['Message_ID']]; // $result[$i]['fullLink'] = 'http://' . $_SERVER['HTTP_HOST'] . nc_message_link($row['Message_ID'], $source['class_id']); } } return (array) $result; }
/** * (POST only) * params: route_id, priority */ protected function action_change_priority() { $input = $this->input; $route = new nc_routing_route($input->fetch_post('route_id')); $old_priority = (int) $route->get('priority'); $new_priority = (int) $input->fetch_post('priority'); if ($new_priority && $old_priority != $new_priority) { if ($new_priority < $old_priority) { // moving upward $direction = '+'; $min = $new_priority; $max = $old_priority; } else { // moving downward $direction = '-'; $min = $old_priority; $max = $new_priority; } nc_db()->query("UPDATE `{$route->get_table_name()}`\n SET `Priority` = `Priority` {$direction} 1\n WHERE `Site_ID` = " . (int) $route->get('site_id') . "\n AND `Priority` BETWEEN {$min} AND {$max}"); $route->set('priority', $new_priority)->save(); } exit; }
/** * Загрузка записи из БД по указанному SQL-запросу. * Можно использовать %t% для подстановки имени таблицы: * $record->select_from_database("SELECT * FROM `%t` WHERE id=123") * * @param $query * @throws nc_record_exception * @return static|bool */ protected function select_from_database($query) { $this->check_mapping_settings(); $db = nc_db(); $query = str_replace('%t%', $this->table_name, $query); $result = $db->get_row($query, ARRAY_A); if ($db->is_error) { $this->process_error("cannot load data object: '%s'", $db->last_error); } if (!$result) { return false; } return $this->set_values_from_database_result($result); }
/** * @param int|string $component_id ID/тип компонента (например: 'User', 'Template', 123) * @param int|int[] $object_id_or_ids ID или массив с ID объектов * @param string|null $returned_field_name Если указано — вернуть значения только для указанного поля * @return array|null|nc_multifield * Если $object_ids — массив, то массив с массивом nc_multifield для каждого объекта (ключ — ID объекта). * Если $object_ids — число, то массив с полями для указанного объекта. * Если $object_ids — число и указано $field_name — объект nc_multifile. * Если у компонента нет полей типа MULTIFILE — NULL. */ function nc_get_multifile_field_values($component_id, $object_id_or_ids, $returned_field_name = null) { $object_ids = (array) $object_id_or_ids; $component = new nc_component($component_id); $fields = $component->get_fields(NC_FIELDTYPE_MULTIFILE, false); if ($returned_field_name) { // fetch data for a single field only $returned_field_id = array_search($returned_field_name, $fields); $fields = array($returned_field_id => $fields[$returned_field_id]); } if (!$fields) { return null; } /** @var nc_multifield[][] $results */ $result = array(); foreach ($object_ids as $object_id) { foreach ($fields as $field_name) { $result[$object_id][$field_name] = new nc_multifield($field_name); } } $rows = (array) nc_db()->get_results("SELECT `Field_ID`,\n `Message_ID`,\n `Priority`,\n `Name`,\n `Size`,\n `Path`,\n `Preview`,\n `ID`\n FROM `Multifield`\n WHERE `Message_ID` IN (" . join(",", array_map('intval', $object_ids)) . ")\n AND `Field_ID` IN (" . join(",", array_keys($fields)) . ")\n ORDER BY `Priority`", ARRAY_A); foreach ($rows as $row) { $object_id = $row['Message_ID']; $field_name = $fields[$row['Field_ID']]; $result[$object_id][$field_name]->add_record($row); } if (!is_array($object_id_or_ids)) { if ($returned_field_name) { return $result[$object_id_or_ids][$returned_field_name]; } else { return $result[$object_id_or_ids]; } } else { return $result; } }
/** * * @param string $query SQL query * Вместо имени таблицы можно использовать '%t%' * @throws nc_record_exception * @return $this */ public function select_from_database($query) { $item_class = $this->get_items_class(); $db = nc_db(); if (strpos($query, "%t")) { $query = str_replace("%t%", $this->get_table_name(), $query); } $result = $db->get_results($query, ARRAY_A); if ($db->is_error) { throw new nc_record_exception("Cannot load items from the database: '{$db->last_error}'"); } if (sizeof($result)) { foreach ($result as $row) { /** @var nc_record $item */ $item = new $item_class(); $item->set_values_from_database_result($row); $this->add($item); } } return $this; }
public function optimize_tables() { $table_names = "`" . join("`, `", $this->get_all_table_names()) . "`"; nc_db()->query("OPTIMIZE TABLE {$table_names}"); return $this; }
/** * */ public function delete() { $db = nc_db(); // delete associated schedule and task entries $id = $db->escape($this->get_id()); $db->query("DELETE FROM `Search_Schedule` WHERE `AreaString` = '{$id}'"); $db->query("DELETE FROM `Search_Task` WHERE `Rule_ID` = '{$id}'"); return parent::delete(); }
/** * */ protected function restore_mysql_encoding() { if ($this->internal_encoding == 'utf-8' && nc_core('MYSQL_CHARSET') != 'utf8') { nc_db()->query("SET NAMES " . nc_core('MYSQL_CHARSET')); } }
protected function sql_make_create($table) { $db = nc_db(); $db->query("SET SQL_QUOTE_SHOW_CREATE = 1;"); $result = $db->get_row("SHOW CREATE TABLE `{$table}`", ARRAY_N); if (!$result) { return false; } return preg_replace('/ AUTO_INCREMENT=\\d+/', '', $result[1]); }
/** * */ protected function restore_mysql_encoding() { if (nc_core('MYSQL_CHARSET') != 'utf8') { nc_db()->query("SET NAMES " . nc_core('MYSQL_CHARSET')); } }