Example #1
0
 public function match(nc_routing_request $request, nc_routing_result $result)
 {
     if (!nc_preg_match($this->get_keyword_regexp(), $result->get_remainder(), $matches)) {
         return false;
         // --- RETURN ---
     }
     $possible_keywords = $this->get_possible_keywords($matches[1]);
     $infoblocks_in_folder = array();
     $infoblock_id = $result->get_resource_parameter('infoblock_id');
     // sic, not get_infoblock_id()
     $folder_id = $result->get_resource_parameter('folder_id');
     $infoblock_manager = nc_core::get_object()->sub_class;
     if ($infoblock_id) {
         $infoblocks_in_folder = array($infoblock_manager->get_by_id($infoblock_id));
     } else {
         if ($folder_id) {
             $infoblocks_in_folder = $infoblock_manager->get_by_subdivision_id($folder_id);
         }
     }
     foreach ($possible_keywords as $object_keyword) {
         foreach ($infoblocks_in_folder as $infoblock_settings) {
             list($object_id, $real_object_keyword) = (array) ObjectExists($infoblock_settings['Class_ID'], $infoblock_settings['sysTbl'], $infoblock_settings['Sub_Class_ID'], $object_keyword, $result->get_resource_parameter('date'), true);
             if ($object_id) {
                 $result->set_resource_parameter('infoblock_id', $infoblock_settings['Sub_Class_ID']);
                 $result->set_resource_parameter('object_keyword', $real_object_keyword);
                 $result->set_resource_parameter('object_id', $object_id);
                 $result->truncate_remainder(strlen($object_keyword));
                 return true;
                 // --- RETURN ---
             }
         }
     }
     return false;
     // --- RETURN ---
 }
Example #2
0
 /**
  * @param string $path
  * @param nc_Db $db
  * @param string $type
  */
 public function __construct($path, nc_Db $db, $type = null)
 {
     $this->path_to_root_folder = $path;
     $this->db = $db;
     $this->type = $type;
     $this->catalogue_id = nc_core::get_object()->catalogue->id();
 }
Example #3
0
 public static function init()
 {
     $listener = new self();
     $event_manager = nc_core::get_object()->event;
     $event_manager->bind($listener, array('addCatalogue' => 'create_site'));
     $event_manager->bind($listener, array('dropCatalogue' => 'delete_site'));
 }
Example #4
0
 public function parse_url()
 {
     if (is_array($this->parsed_url)) {
         return $this->parsed_url;
     }
     $nc_core = nc_core::get_object();
     // parse entire url
     $parsed_url = @parse_url($this->url);
     $query_string = isset($parsed_url['query']) ? $parsed_url['query'] : null;
     // validate query parameter
     if ($query_string) {
         parse_str('&' . $query_string, $parsed_query_arr);
         // validate
         $parsed_query_arr = $nc_core->input->clear_system_vars($parsed_query_arr);
         //            // in error_document $_GET is empty, so set them at this line
         //            $_GET = $parsed_query_arr ? $parsed_query_arr : array();
         // build new query
         $parsed_url['query'] = $this->build_url($parsed_query_arr);
     }
     if ($this->remove_sub_folder && isset($parsed_url['path'])) {
         $parsed_url['path'] = nc_preg_replace("#^(" . preg_quote($nc_core->SUB_FOLDER) . ")(.*?)\$#is", "\$2", $parsed_url['path']);
     }
     // for other methods
     $this->parsed_url = $parsed_url;
     // return array
     return $this->parsed_url;
 }
Example #5
0
 public function __toString()
 {
     try {
         return $this->make();
     } catch (Exception $e) {
         return strval(nc_core::get_object()->ui->alert->error($e->getMessage()));
     }
 }
Example #6
0
 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;
 }
Example #7
0
 protected function prepare_resource_parameters()
 {
     try {
         $folder_settings = nc_core::get_object()->subdivision->get_by_id($this->folder_id);
     } catch (Exception $e) {
         return false;
     }
     $folder_params = array('site_id' => $folder_settings['Catalogue_ID'], 'folder' => $folder_settings['Hidden_URL'], 'folder_id' => $folder_settings['Subdivision_ID'], 'action' => 'index', 'format' => 'html', 'date' => $this->date, 'variables' => $this->query_variables);
     return $folder_params;
 }
Example #8
0
/**
 * Быстрый доступ к объекту nc_Core;
 *
 * @param string|null $sub_object
 * @return mixed
 */
function nc_core($sub_object = null)
{
    static $nc_core;
    if ($nc_core === null) {
        $nc_core = nc_core::get_object();
    }
    if ($sub_object) {
        return $nc_core->{$sub_object};
    }
    return $nc_core;
}
Example #9
0
 protected function prepare_resource_parameters()
 {
     if ($this->resource_parameters) {
         return $this->resource_parameters;
     }
     try {
         $infoblock_settings = nc_core::get_object()->sub_class->get_by_id($this->infoblock_id);
     } catch (Exception $e) {
         return false;
     }
     $infoblock_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'], 'action' => $this->action ? $this->action : $infoblock_settings['DefaultAction'], 'format' => $this->format, 'date' => $this->date, 'variables' => $this->query_variables);
     return $infoblock_params;
 }
Example #10
0
 /**
  * Создаёт стандартные маршруты на указанном сайте.
  *
  * @param int $site_id
  * @return bool
  */
 public static function create($site_id)
 {
     if (!nc_core::get_object()->catalogue->get_by_id($site_id, 'Catalogue_ID')) {
         return false;
     }
     // Пути по умолчанию в порядке убывания приоритета
     $all_patterns = array("folder /{folder}/{date}/", "folder /{folder}/{date}", "folder /{folder}/", "folder /{folder}", "infoblock /{folder}/{infoblock_action}_{infoblock_keyword}.{format}", "infoblock /{folder}/{date}/{infoblock_action}_{infoblock_keyword}.{format}", "object /{folder}/{date}/{object_action}_{object_keyword}.{format}", "object /{folder}/{object_action}_{object_keyword}.{format}", "object /{folder}/{date}/{object_action}_{infoblock_keyword}_{object_id}.{format}", "object /{folder}/{object_action}_{infoblock_keyword}_{object_id}.{format}", "object /{folder}/{date}/{object_keyword}.{format}", "object /{folder}/{object_keyword}.{format}", "object /{folder}/{date}/{infoblock_keyword}_{object_id}.{format}", "object /{folder}/{infoblock_keyword}_{object_id}.{format}", "infoblock /{folder}/{infoblock_keyword}.{format}", "infoblock /{folder}/{date}/{infoblock_keyword}.{format}");
     $all_patterns = array_reverse($all_patterns);
     foreach ($all_patterns as $pattern_data) {
         list($resource_type, $pattern) = explode(" ", $pattern_data, 2);
         $route = new nc_routing_route(array('site_id' => $site_id, 'description' => '', 'is_builtin' => true, 'pattern' => $pattern, 'resource_type' => $resource_type, 'enabled' => true));
         $route->save();
     }
     return true;
 }
Example #11
0
File: id.php Project: Blu2z/implsk
 public function match(nc_routing_request $request, nc_routing_result $result)
 {
     $infoblock_id = $result->get_infoblock_id();
     if ($infoblock_id && preg_match('/^(\\d+)/', $result->get_remainder(), $matches)) {
         $object_id = $matches[0];
         $infoblock_settings = nc_core::get_object()->sub_class->get_by_id($infoblock_id);
         list($object_id, $real_object_keyword) = (array) ObjectExistsByID($infoblock_settings['Class_ID'], $infoblock_settings['sysTbl'], $object_id, $result->get_resource_parameter('date'), true);
         if ($object_id) {
             $result->set_resource_parameter('object_id', $object_id);
             $result->set_resource_parameter('object_keyword', $real_object_keyword);
             $result->truncate_remainder(strlen($object_id));
             return true;
         }
     }
     return false;
 }
Example #12
0
 /**
  * @param int $site_id
  * @param string $path_remainder
  * @return mixed
  */
 protected function get_folder_settings($site_id, $path_remainder)
 {
     static $cache = array();
     if (!array_key_exists($path_remainder, $cache)) {
         $cache[$path_remainder] = false;
         $current_remainder = $path_remainder;
         while ($last_slash = strrpos($current_remainder, '/')) {
             $current_remainder = substr($current_remainder, 0, $last_slash);
             $sub = nc_core::get_object()->subdivision->get_by_uri("{$current_remainder}/", $site_id, null, false, true);
             if ($sub) {
                 $cache[$path_remainder] = $sub;
                 break;
                 // --- exit while() ---
             }
         }
     }
     return $cache[$path_remainder];
 }
Example #13
0
 public function substitute_values_for(nc_routing_path $path, nc_routing_pattern_parameters $parameters)
 {
     $infoblock_keyword = $path->get_resource_parameter('infoblock_keyword');
     if (!$infoblock_keyword && $infoblock_keyword !== '0') {
         $infoblock_id = $path->get_resource_parameter('infoblock_id');
         if ($infoblock_id) {
             try {
                 $infoblock_keyword = nc_core::get_object()->sub_class->get_by_id($infoblock_id, 'EnglishName');
             } catch (Exception $e) {
             }
         }
     }
     if ($infoblock_keyword || strlen($infoblock_keyword)) {
         //            $path->set_route_resource_parameter('infoblock_keyword', $infoblock_keyword);
         //            $parameters->infoblock_keyword = $infoblock_keyword;
         return $infoblock_keyword;
     } else {
         return false;
     }
 }
Example #14
0
 protected function set_query_params()
 {
     static $display_type;
     if ($display_type === null) {
         $display_type = $this->nc_core->get_display_type();
     }
     // Условия
     if ($this->result_mode != 'custom') {
         if (!$this->ignore_check) {
             $this->table->where('Checked', 1);
         }
         $this->table->where('Catalogue_ID', $this->site_id);
         if (in_array($display_type, array('longpage_vertical', 'shortpage'))) {
             $this->table->where_in('DisplayType', array('inherit', $display_type));
         }
     }
     // Сортировка
     if (!$this->custom_ordering) {
         $this->table->order_by('Priority')->order_by('Subdivision_Name');
     }
 }
Example #15
0
 /**
  * @return int
  */
 public function determine_site_id()
 {
     $new_id = (int) nc_core('input')->fetch_post_get('site_id');
     $cookie_name = 'nc_admin_site_id';
     $nc_catalogue = nc_core::get_object()->catalogue;
     if ($new_id) {
         $nc_core = nc_core::get_object();
         setcookie($cookie_name, $new_id, 0, $nc_core->SUB_FOLDER . $nc_core->HTTP_ROOT_PATH);
         $site_id = $new_id;
     } else {
         if ((int) $_COOKIE[$cookie_name]) {
             $site_id = $_COOKIE[$cookie_name];
         } else {
             $site_id = (int) $nc_catalogue->get_current('Catalogue_ID');
         }
     }
     // Проверка сайта на существование
     try {
         $nc_catalogue->get_by_id($site_id);
     } catch (Exception $e) {
         $site_id = (int) $nc_catalogue->get_current('Catalogue_ID');
     }
     return $site_id;
 }
 public function __construct($backup)
 {
     @set_time_limit(0);
     $this->backup = $backup;
     $this->nc_core = nc_core::get_object();
     $this->db = $this->nc_core->db;
     $this->save_ids = (bool) $this->backup->config('save_ids');
     if (!$this->type) {
         $class = get_class($this);
         if ($class != 'nc_backup_driver') {
             $this->type = substr($class, strlen('nc_backup_'));
         }
     }
     if (!$this->name) {
         $this->name = ucfirst($this->type);
     }
     if ($this->export_steps) {
         $this->export_steps = array('init' => TOOLS_DATA_BACKUP_STEP_INIT) + $this->export_steps + array('end' => TOOLS_DATA_BACKUP_STEP_END);
     }
     if ($this->import_steps) {
         $this->import_steps = array('init' => TOOLS_DATA_BACKUP_STEP_INIT) + $this->import_steps + array('end' => TOOLS_DATA_BACKUP_STEP_END);
     }
     $this->init();
 }
Example #17
0
/**
 * @param nc_url|string $url Объект nc_url или строка
 * @param string $method GET|POST
 * @param int|null $site_id    Если null — текущий сайт
 * @return array|false   Массив с информацией об объекте, на который ссылается путь,
 *    или FALSE.
 *    array(
 *         resource_type => folder|infoblock|object|script
 *         site_id => идентификатор сайта
 *         folder_id => идентификатор раздела
 *         infoblock_id => [идентификатор инфоблока]
 *         object_id => идентификатор объекта в инфоблоке
 *         action => действие над инфоблоком или объектом
 *         format => html|rss|xml
 *         variables => массив с дополнительными переменными (только для модуля маршрутизации)
 *         date => дата в пути
 *         script_path => путь к скрипту от папки DOCUMENT_ROOT/SUB_FOLDER (только для модуля маршрутизации для resource_type=script)
 *         redirect_to_url => при запросе всегда будет выполняться переадресация
 *    )
 */
function nc_resolve_url($url, $method = null, $site_id = null)
{
    $nc_core = nc_core::get_object();
    $routing_module_enabled = nc_module_check_by_keyword('routing');
    // --- Приведение параметра $url к nc_url ---
    if (!$url instanceof nc_url) {
        $url = new nc_url($url);
    } else {
        if (!$routing_module_enabled) {
            // Создадим клон $url, так как в процессе работы будут изменяться свойства этого объекта
            $url = clone $url;
        }
    }
    // --- Определение сайта ---
    if (!$site_id) {
        $site_settings = $nc_core->catalogue->get_by_host_name($url->get_parsed_url('host'));
        if (isset($site_settings['Catalogue_ID'])) {
            $site_id = $site_settings['Catalogue_ID'];
        } else {
            $site_id = $nc_core->catalogue->id();
        }
    }
    if (!$site_id) {
        return false;
    }
    // --- Использование модуля маршрутизации ---
    if ($routing_module_enabled) {
        $result = nc_routing::resolve(new nc_routing_request($site_id, $method, $url->get_parsed_url()));
        if ($result) {
            $result = $result->to_array();
            $result['site_id'] = $site_id;
            return $result;
        } else {
            return false;
        }
    }
    // --- «Классическая» маршрутизация ---
    $result = array('resource_type' => 'folder', 'site_id' => $site_id, 'folder_id' => null, 'infoblock_id' => null, 'object_id' => null, 'action' => null, 'format' => 'html', 'variables' => array(), 'date' => null, 'redirect_to_url' => null);
    // Инициализация переменных
    $component_id = 0;
    $default_action = null;
    $page_not_found = false;
    // Имя «файла»
    $req_file = strrchr($url->get_parsed_url('path'), '/');
    // Определяем раздел по пути
    $result['folder_id'] = $nc_core->subdivision->get_by_uri($url->get_parsed_url('path'), $site_id, 'Subdivision_ID', true, true);
    // Если раздел не найден, дальнейшая обработка адреса не имеет смысла,
    // так как мы в любом случае должны вернуть FALSE
    if (!$result['folder_id']) {
        return false;
    }
    $file_name = '';
    $file_extension = '';
    $uri_date = $url->get_uri_date();
    if ($req_file != '/') {
        $req_file = substr($req_file, 1);
        if (strpos($req_file, '.')) {
            $req_file_parts = explode(".", $req_file);
            $file_name = $req_file_parts[0];
            $file_extension = strtolower($req_file_parts[count($req_file_parts) - 1]);
        }
        if (in_array($file_extension, array('html', 'rss', 'xml'))) {
            // name without extension
            $url->set_parsed_url_item('path', substr($url->get_parsed_url('path'), 0, strlen($url->get_parsed_url('path')) - strlen($req_file)));
        } else {
            // append trailing slash
            $url->set_parsed_url_item('path', rtrim($url->get_parsed_url('path'), "/") . "/");
        }
        // Адрес имеет расширение (.html, .rss, .xml) — это адрес объекта или инфоблока
        if (in_array($file_extension, array('html', 'rss', 'xml'))) {
            $result['format'] = $file_extension;
            $infoblocks_in_folder = $nc_core->sub_class->get_by_subdivision_id($result['folder_id']);
            // keyword.html — совпадение по ключевому слову объекта
            if (nc_preg_match("/^([_a-zа-я0-9-]+)\$/i", $file_name, $regs)) {
                if (!empty($infoblocks_in_folder)) {
                    foreach ($infoblocks_in_folder as $infoblock_settings) {
                        if ($file_extension == 'rss' && !$infoblock_settings['AllowRSS']) {
                            continue;
                        }
                        if ($file_extension == 'xml' && !$infoblock_settings['AllowXML']) {
                            continue;
                        }
                        // Находим объект, подходящий под имеющиеся параметры
                        if ($object_id = ObjectExists($infoblock_settings['Class_ID'], $infoblock_settings['sysTbl'], $infoblock_settings['Sub_Class_ID'], $file_name, $uri_date)) {
                            $component_id = $infoblock_settings['Class_ID'];
                            $result['resource_type'] = 'object';
                            $result['infoblock_id'] = $_db_cc = $infoblock_settings['Sub_Class_ID'];
                            $result['object_id'] = $object_id;
                            $result['action'] = 'full';
                            break;
                        }
                    }
                }
            }
            // news.html — ключевое слово компонента, при условии, что нет такого объекта
            if (!$result['object_id'] && nc_preg_match("/^([a-zа-я0-9-]+)\$/i", $file_name, $regs)) {
                if (!empty($infoblocks_in_folder)) {
                    foreach ($infoblocks_in_folder as $infoblock_settings) {
                        if ($infoblock_settings['EnglishName'] == $regs[1]) {
                            if ($file_extension == 'rss' && !$infoblock_settings['AllowRSS']) {
                                continue;
                            }
                            if ($file_extension == 'xml' && !$infoblock_settings['AllowXML']) {
                                continue;
                            }
                            $result['resource_type'] = 'infoblock';
                            $result['infoblock_id'] = $_db_cc = $infoblock_settings['Sub_Class_ID'];
                            // action может быть задан в get'e или post'e
                            if (!$result['action']) {
                                $result['action'] = $infoblock_settings['DefaultAction'];
                            }
                            break;
                        }
                    }
                }
            }
            // add_news.html, search_news.html, subscribe_news.html — добавление, поиск, подписка в компоненте
            if (nc_preg_match("/^(add|search|subscribe)_((?i:[a-zа-я0-9-]+))\$/", $file_name, $regs)) {
                if (!empty($infoblocks_in_folder)) {
                    foreach ($infoblocks_in_folder as $infoblock_settings) {
                        if ($infoblock_settings['EnglishName'] != $regs[2]) {
                            continue;
                        }
                        $result['resource_type'] = 'infoblock';
                        $result['infoblock_id'] = $_db_cc = $infoblock_settings['Sub_Class_ID'];
                        $result['action'] = $regs[1];
                        break;
                    }
                }
            }
            // news_5.html — отображение объекта по компоненту и идентификатору
            if (nc_preg_match("/^([a-zа-я0-9-]+)_([0-9]+)\$/i", $file_name, $regs) && $file_name == $regs[1] . "_" . $regs[2]) {
                if (!empty($infoblocks_in_folder)) {
                    foreach ($infoblocks_in_folder as $infoblock_settings) {
                        // check component in sub keyword
                        if ($infoblock_settings['EnglishName'] != $regs[1]) {
                            continue;
                        }
                        if ($file_extension == 'rss' && !$infoblock_settings['AllowRSS']) {
                            continue;
                        }
                        if ($file_extension == 'xml' && !$infoblock_settings['AllowXML']) {
                            continue;
                        }
                        // find message with requested params
                        if ($object_id = ObjectExistsByID($infoblock_settings['Class_ID'], $infoblock_settings['sysTbl'], $regs[2], $uri_date)) {
                            $component_id = $infoblock_settings['Class_ID'];
                            $result['resource_type'] = 'object';
                            $result['infoblock_id'] = $_db_cc = $infoblock_settings['Sub_Class_ID'];
                            $result['object_id'] = $object_id;
                            $result['action'] = 'full';
                            break;
                        }
                    }
                }
            }
            // edit_object.html — изменение объекта по ДЕЙСТВИЮ и КЛЮЧЕВОМУ СЛОВУ, при условии, что нет объекта по компоненту и идентификатору
            if (!$result['object_id'] && nc_preg_match("/^(edit|delete|drop|checked|subscribe)_((?i:[_a-zа-я0-9-]+))\$/", $file_name, $regs)) {
                if (!empty($infoblocks_in_folder)) {
                    foreach ($infoblocks_in_folder as $infoblock_settings) {
                        // find message with need params
                        if ($object_id = ObjectExists($infoblock_settings['Class_ID'], $infoblock_settings['sysTbl'], $infoblock_settings['Sub_Class_ID'], $regs[2])) {
                            $component_id = $infoblock_settings['Class_ID'];
                            $result['resource_type'] = 'object';
                            $result['infoblock_id'] = $_db_cc = $infoblock_settings['Sub_Class_ID'];
                            $result['object_id'] = $object_id;
                            $result['action'] = $regs[1];
                            break;
                        }
                    }
                }
            }
            // edit_news_5.html — изменение объекта по действию, компоненту и идентификатору объекта
            if (nc_preg_match("/^(edit|delete|drop|checked|subscribe)_((?i:[_a-zа-я0-9-]+))_([0-9]+)\$/", $file_name, $regs)) {
                if (!empty($infoblocks_in_folder)) {
                    foreach ($infoblocks_in_folder as $infoblock_settings) {
                        // check component in sub keyword
                        if ($infoblock_settings['EnglishName'] != $regs[2]) {
                            continue;
                        }
                        // find message with need params
                        if ($object_id = ObjectExistsByID($infoblock_settings['Class_ID'], $infoblock_settings['sysTbl'], $regs[3])) {
                            $component_id = $infoblock_settings['Class_ID'];
                            $result['resource_type'] = 'object';
                            $result['infoblock_id'] = $_db_cc = $infoblock_settings['Sub_Class_ID'];
                            $result['object_id'] = $object_id;
                            $result['action'] = $regs[1];
                            break;
                        }
                    }
                }
            }
        } else {
            // У «файла» нет расширения, либо нестандартное расширение
            // Добавить "/" и сделать переадресацию
            $result['redirect_to_url'] = $url->source_url() . ($url->get_parsed_url('query') ? "?" . $url->get_parsed_url('query') : "") . ($url->get_parsed_url('fragment') ? "#" . $url->get_parsed_url('fragment') : "");
        }
    }
    // Для разделов установить ID первого инфоблока
    if ($result['resource_type'] == 'folder' && !$file_name && $result['folder_id']) {
        if (empty($infoblocks_in_folder)) {
            $infoblocks_in_folder = $nc_core->sub_class->get_by_subdivision_id($result['folder_id']);
        }
        foreach ((array) $infoblocks_in_folder as $infoblock_settings) {
            if ($infoblock_settings['Checked'] || $infoblock_settings['sysTbl'] == 3) {
                $component_id = $infoblock_settings['Class_ID'];
                if ($uri_date && !$nc_core->get_component($component_id)->get_date_field()) {
                    continue;
                }
                $result['infoblock_id'] = $infoblock_settings['Sub_Class_ID'];
                if (!$result['action']) {
                    $result['action'] = $infoblock_settings['DefaultAction'];
                }
                break;
            }
        }
    }
    // Если есть «имя файла», но не определён по крайней мере ID инфоблока, то это неправильный путь
    if ($file_name && !$result['infoblock_id']) {
        $page_not_found = true;
    }
    // Дата в пути
    if (!$page_not_found && $uri_date) {
        if (!$result['infoblock_id'] || $result['infoblock_id'] && !$nc_core->get_component($component_id)->get_date_field()) {
            // if there is a date in URI segments and no "event" field in the corresponding component, it is an incorrect path
            $page_not_found = true;
        } else {
            $result['date'] = $uri_date;
        }
    }
    return $page_not_found ? false : $result;
}
Example #18
0
 protected function folder_has_component_with_event_field($folder_id)
 {
     $nc_core = nc_core::get_object();
     foreach ((array) $nc_core->sub_class->get_by_subdivision_id($folder_id) as $infoblock_settings) {
         if ($nc_core->get_component($infoblock_settings['Class_ID'])->get_date_field()) {
             return true;
         }
     }
     return false;
 }
Example #19
0
 /**
  * Устанавливает значение настройки модуля
  *
  * @param string $setting
  * @param string $value
  * @param int null $site_id
  * @return bool
  */
 public static function set_setting($setting, $value, $site_id = null)
 {
     return nc_core::get_object()->set_settings($setting, $value, 'routing', $site_id);
 }
Example #20
0
/**
 * Удаление директории относительно
 * @param  [string] $path Путь к директории
 * @return [int|bool]     Кол-во удаленных файлов | false - если директория не существует или ее удаление запрещено
 */
function remove_dir($path)
{
    static $exclude_pathes;
    static $DS = DIRECTORY_SEPARATOR;
    if (is_null($exclude_pathes)) {
        $nc_core = nc_core::get_object();
        $exclude_pathes = array($nc_core->DOCUMENT_ROOT, $nc_core->NETCAT_FOLDER, $nc_core->ADMIN_FOLDER, $nc_core->SYSTEM_FOLDER, $nc_core->INCLUDE_FOLDER);
    }
    $result = 0;
    $path = rtrim($path, $DS);
    if (in_array($path . $DS, $exclude_pathes)) {
        return false;
    }
    if (!file_exists($path)) {
        return false;
    }
    if (is_dir($path)) {
        $dh = opendir($path);
        while ($f = readdir($dh)) {
            if ($f == '.' || $f == '..') {
                continue;
            }
            $result += remove_dir($path . $DS . $f);
        }
        closedir($dh);
        $result += rmdir($path);
    } else {
        $result += unlink($path);
    }
    return $result;
}
Example #21
0
 public function __construct()
 {
     parent::__construct();
     $this->core = nc_core::get_object();
     $this->core->register_macrofunc('NC_WIDGET_SHOW', 'show_macrofunc', $this);
 }
Example #22
0
 /**
  *
  */
 public function get_action()
 {
     $action = $this->get_resource_parameter('action');
     if ($action) {
         return $action;
     }
     // no $action, but there is an $infoblock_id
     $infoblock_id = $this->get_infoblock_id();
     if ($infoblock_id) {
         return nc_core::get_object()->sub_class->get_by_id($infoblock_id, 'DefaultAction');
     }
     return null;
 }
Example #23
0
/**
 * Возвращает путь к объекту.
 *
 * @param int $component_id
 * @param int $object_id
 * @param string $action full|edit|delete|drop|checked|subscribe
 * @param string $format html|rss|xml
 * @param bool $add_date Если true и у компонента есть поле формата event, добавляет дату к пути
 * @param array $variables
 * @param bool $add_domain (недокументировано, существует для оптимизации — используйте nc_object_url())
 *                          Если TRUE, возвращает URL с именем домена
 * @return string|nc_routing_path|false
 */
function nc_object_path($component_id, $object_id, $action = 'full', $format = 'html', $add_date = false, array $variables = null, $add_domain = false)
{
    if (!$action) {
        $action = 'full';
    }
    if (nc_module_check_by_keyword('routing')) {
        return nc_routing::get_object_path($component_id, $object_id, $action, $format, $add_date, $variables, $add_domain);
    } else {
        $object_id = (int) $object_id;
        $component_id = (int) $component_id;
        if (!$object_id || !$component_id) {
            return false;
        }
        $db = nc_db();
        $nc_core = nc_core::get_object();
        $date_field = false;
        if ($add_date) {
            $date_field = $nc_core->get_component($component_id)->get_date_field();
        }
        // основной запрос для построения пути
        list($site_id, $object_path) = $db->get_row("SELECT sub.`Catalogue_ID`,\n                    CONCAT(\n                        sub.`Hidden_URL`, " . ($add_date && $date_field ? "DATE_FORMAT(`" . $db->escape($date_field) . "`, '%Y/%m/%d/'), " : "") . ($action && $action != 'full' ? "'" . $db->escape($action) . "_', " : "") . "\n                        IF(m.`Keyword` <> '', m.`Keyword`, CONCAT(cc.`EnglishName`, '_', m.`Message_ID`)),\n                        '." . $db->escape($format) . "'\n                    )\n               FROM `Message{$component_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` = {$object_id}", ARRAY_N);
        if (!$object_path) {
            return false;
        }
        $object_path = $nc_core->SUB_FOLDER . $object_path . nc_array_to_url_query($variables);
        if ($add_domain) {
            $object_path = "//" . $nc_core->catalogue->get_by_id($site_id, 'Domain') . $object_path;
        }
        return $object_path;
    }
}
Example #24
0
<?php

ob_start("ob_gzhandler");
define("NC_ADMIN_ASK_PASSWORD", false);
$NETCAT_FOLDER = realpath(dirname(__FILE__) . '/../../..') . DIRECTORY_SEPARATOR;
require_once $NETCAT_FOLDER . "vars.inc.php";
require $ADMIN_FOLDER . "function.inc.php";
// Показываем дерево разработчика, если у пользователя есть на это права
if (!$perm->isAccess(NC_PERM_MODULE, 0, 0, 0)) {
    exit(NETCAT_MODERATION_ERROR_NORIGHT);
}
//--------------------------------------------------------------------------
$nc_core = nc_core::get_object();
@(list($node_type, $node_id) = explode("-", $node));
$module_list = $nc_core->modules->get_data();
switch ($node_type) {
    case 'root':
        // widgets
        $ret_modules[] = array("nodeId" => "widgets", "name" => WIDGETS, "href" => "#widgets", "sprite" => "mod-widgets", "hasChildren" => false, "dragEnabled" => false);
        foreach ($module_list as $module) {
            $module_keyword = $module['Keyword'];
            $module_path = $MODULE_FOLDER . $module_keyword . DIRECTORY_SEPARATOR;
            if (file_exists($module_path . MAIN_LANG . ".lang.php")) {
                require_once $module_path . MAIN_LANG . ".lang.php";
            } else {
                require_once $module_path . "en.lang.php";
            }
            $custom_location = $nc_core->modules->get_vars($module_keyword, 'ADMIN_SETTINGS_LOCATION');
            $ret_modules[] = array("nodeId" => "module-{$module['Module_ID']}", "name" => constant($module["Module_Name"]), "href" => file_exists($module_path . 'admin.php') && $module['Checked'] ? "#module.{$module_keyword}" : "#module.settings({$module_keyword})", "sprite" => "mod-{$module_keyword}", "hasChildren" => file_exists($module_path . 'admin_tree.php'), "dragEnabled" => false, "buttons" => array(array("image" => "i_settings.gif", "label" => TOOLS_MODULES_MOD_PREFS, "href" => $custom_location ? $custom_location : "module.settings({$module_keyword})")));
        }
        $ret = array_reverse($ret_modules);
Example #25
0
 /**
  * @param nc_routing_path $path
  * @return bool|string
  */
 public function get_path_string_for(nc_routing_path $path)
 {
     $requested_resource_parameters = $path->get_resource_parameters();
     // Поскольку генерирование путей, особенно при наличии большого количества маршрутов —
     // затратный процесс, для оптимизации сюда были вынесены знания о функционировании
     // некоторых типов частей шаблонов пути (в основном для генерации путей объектов —
     // их на страницах с длинными списками объектов больше всего)...
     // Оптимизация: не пытаться вычислять значение, если в пути есть {object_keyword},
     // а у объекта нет свойства для подстановки (может быть часто в списках объектов)
     if ($this->pattern_contains_object_keyword) {
         $requested_object_keyword = isset($requested_resource_parameters['object_keyword']) ? $requested_resource_parameters['object_keyword'] : false;
         if (!$requested_object_keyword && $requested_object_keyword !== '0') {
             return false;
             // --- RETURN ---
         }
     }
     // Эти свойства нам будут дальше нужны:
     $route_resource_type = $this->properties['resource_type'];
     $route_resource_type_is_object = $route_resource_type === 'object';
     $route_resource_parameters = $this->properties['resource_parameters'];
     // Оптимизация: не пытаться вычислять значение, если в пути есть {date},
     // а у ресурса дата не задана (отбрасываем почти половину стандартных путей),
     // и при противоположном раскладе (если не установлено, что дата является опциональной)
     $path_has_date = isset($requested_resource_parameters['date']) && $requested_resource_parameters['date'];
     $path_date_is_optional = $route_resource_type_is_object && isset($requested_resource_parameters['date_is_optional']) && $requested_resource_parameters['date_is_optional'];
     if ($this->pattern_contains_date && !$path_has_date || !$path_date_is_optional && $path_has_date && !$this->pattern_contains_date) {
         return false;
         // --- RETURN ---
     }
     // Оптимизация: действие = "full", а в шаблоне пути есть {object_action} — совпадения не будет
     // (подразумевается, что это должен быть путь к объекту — дополнительных проверок не проводим)
     if ($this->pattern_contains_object_action && $requested_resource_parameters['action'] === 'full') {
         return false;
         // --- RETURN ---
     }
     // Оптимизация: путь до объекта, действие ≠ "full", в пути нет {object_action}
     // и action не задан в настройках маршрута
     if (!$this->pattern_contains_object_action && $route_resource_type_is_object && $requested_resource_parameters['action'] !== 'full' && $route_resource_parameters['action'] !== $requested_resource_parameters['action']) {
         return false;
         // --- RETURN ---
     }
     // То же самое для {infoblock_action} и action = "index"
     if ($this->pattern_contains_infoblock_action && $requested_resource_parameters['action'] === 'index') {
         return false;
         // -- RETURN ---
     }
     // Если у маршрута задан один из «определяющих» параметров ресурса,
     // он должен совпадать с параметром у $path
     if ($route_resource_parameters) {
         static $parameters_to_check_before_substitution = array('folder_id', 'infoblock_id', 'object_id', 'script_path');
         foreach ($parameters_to_check_before_substitution as $p) {
             if (isset($route_resource_parameters[$p]) && $route_resource_parameters[$p] && $route_resource_parameters[$p] != $requested_resource_parameters[$p]) {
                 return false;
                 // --- RETURN ---
             }
         }
     }
     // Подготовка объекта для сбора параметров, накопленных при подстановке частей шаблона пути
     $result_parameters = new nc_routing_pattern_parameters($this);
     if (isset($route_resource_parameters['action'])) {
         $result_parameters->action = $route_resource_parameters['action'];
     }
     if (isset($route_resource_parameters['format'])) {
         $result_parameters->format = $route_resource_parameters['format'];
     }
     // Подстановка параметров пути — вычисление результата:
     $result = $this->get_pattern()->substitute_values_for($path, $result_parameters);
     // Дополнительные проверки на соответствие результата запросу
     if ($result) {
         $requested_resource_type = $path->get_resource_type();
         if ($requested_resource_type === 'infoblock') {
             $nc_core = nc_core::get_object();
             // Если для инфоблока использован путь к разделу, необходимо проверить,
             // является ли инфоблок первым включённым
             if ($route_resource_type === 'folder') {
                 $folder_infoblock_id = $nc_core->sub_class->get_first_checked_id_by_subdivision_id($requested_resource_parameters['folder_id']);
                 if ($requested_resource_parameters['infoblock_id'] != $folder_infoblock_id) {
                     return false;
                     // --- RETURN ---
                 }
                 $result_parameters->format = 'html';
             }
             // Если при генерировании пути не установлен параметр action,
             // то action = DefaultAction инфоблока
             if (!$result_parameters->action) {
                 try {
                     $default_action = $nc_core->sub_class->get_by_id($path->get_resource_parameter('infoblock_id'), 'DefaultAction');
                     $result_parameters->action = $default_action;
                 } catch (Exception $e) {
                     return false;
                 }
             }
         }
         // Сверяем параметры запроса и результата
         // Параметры format, action могут быть у путей объектов, инфоблоков
         // и путей разделов, если последние используются как путь к инфоблоку.
         // Если нужен путь к разделу, а не к инфоблоку, эти параметры
         // не являются обязательными.
         if (!($requested_resource_type === 'folder' && $route_resource_type === 'folder') && $requested_resource_type !== 'script') {
             if ($route_resource_type_is_object && !$result_parameters->action) {
                 $result_parameters->action = 'full';
             }
             if ($requested_resource_parameters['action'] != $result_parameters->action) {
                 return false;
                 // --- RETURN ---
             }
             if ($requested_resource_parameters['format'] != $result_parameters->format) {
                 return false;
                 // --- RETURN ---
             }
         }
         // Добавляем отсутствующие в созданном пути переменные
         $path_variables = $path->get_resource_parameter('variables');
         if ($path_variables) {
             $extra_variables = array_diff_key($path_variables, $result_parameters->used_variables);
             foreach ($extra_variables as $k => $v) {
                 if ($v === false || $v === null) {
                     unset($extra_variables[$k]);
                 }
             }
             if ($extra_variables) {
                 $result .= "?" . http_build_query($extra_variables, null, '&');
             }
         }
         // Добавляем $SUB_FOLDER
         $result = nc_routing::$SUB_FOLDER . $result;
     }
     return $result;
 }