/** * Формирование кодя для картинки * @param string $captcha_hash соответствующий хэш-код * @return string символы для каптчи */ function nc_captcha_generate_code($captcha_hash) { $nc_core = nc_Core::get_object(); // БД и настройки модуля $db = $nc_core->db; $MODULE_VARS = $nc_core->modules->get_module_vars(); // Настройки параметров алгоритма генерации кода $alphabet = $MODULE_VARS['captcha']['ALPHABET'] ? $MODULE_VARS['captcha']['ALPHABET'] : 'ABCDEFGHKLMNOPRSTUVWXYZ'; $num_chars = $MODULE_VARS['captcha']['NUMBER_OF_CHARS'] ? $MODULE_VARS['captcha']['NUMBER_OF_CHARS'] : 5; if (strpos($num_chars, "..")) { $num_chars = nc_preg_split("|\\.+|", $num_chars); $num_chars = rand($num_chars[0], $num_chars[1]); } // Генерация случайной последовательности символов $alphabet_size = strlen($alphabet); $captcha_code = ''; for ($i = 0; $i < $num_chars; $i++) { $captcha_code .= $alphabet[rand(0, $alphabet_size - 1)]; } // Сохранить сгенерированный код $db->query("REPLACE INTO `Captchas` (`Captcha_Hash`, `Captcha_Code`)\n VALUES ('" . $db->escape($captcha_hash) . "', '" . $db->escape($captcha_code) . "')"); // Обновление захешированных файлов для аудиокаптчи $res = $nc_core->db->get_results("SELECT * FROM `Captchas_Settings`", ARRAY_A); if (!empty($res)) { foreach ($res as $v) { $captcha_settings[$v['Key']] = $v['Value']; } } if ($MODULE_VARS['captcha']['AUDIOCAPTCHA_ENABLED'] && $captcha_settings && is_writable($nc_core->FILES_FOLDER) && is_dir($nc_core->MODULE_FOLDER . 'captcha/voice/' . $MODULE_VARS['captcha']['VOICE'] . '/') && time() - 3600 >= strtotime($captcha_settings['time'])) { $db->query("UPDATE `Captchas_Settings` SET `Value`= Now() WHERE `Key` = 'time'"); $from = $nc_core->MODULE_FOLDER . 'captcha/voice/' . $MODULE_VARS['captcha']['VOICE'] . '/'; $to = $nc_core->FILES_FOLDER . 'captcha/current_voice/'; $nc_core->files->create_dir($to); $enc_mp3_files[] = ''; $enc_mp3_folder = opendir($to); while ($one = readdir($enc_mp3_folder)) { if ($one != '.' && $one != '..' && substr(strrchr($one, '.'), 1) == 'mp3') { $enc_mp3_files[] = $one; } } $normal_mp3_folder = opendir($from); while ($one = readdir($normal_mp3_folder)) { $file_hash = nc_captcha_generate_hash(); if ($one != '.' && $one != '..' && substr(strrchr($one, '.'), 1) == 'mp3') { if ($captcha_settings['current_voice'] != $MODULE_VARS['captcha']['VOICE'] || !in_array($captcha_settings[$one], $enc_mp3_files)) { $db->query("UPDATE `Captchas_Settings` SET `Value`= '" . $MODULE_VARS['captcha']['VOICE'] . "' WHERE `Key` = 'current_voice'"); if ($captcha_settings['current_voice'] != $MODULE_VARS['captcha']['VOICE']) { unlink($to . $captcha_settings[$one]); } copy($from . $one, $to . $file_hash . '.mp3'); $db->query("UPDATE `Captchas_Settings` SET `Value`='" . $db->escape($file_hash) . ".mp3' WHERE `Key` ='" . $one . "'"); } else { rename($to . $captcha_settings[$one], $to . $file_hash . '.mp3'); $db->query("UPDATE `Captchas_Settings` SET `Value`='" . $db->escape($file_hash) . ".mp3' WHERE `Key` ='" . $one . "'"); } } } } }
/** * Разбивает ключевое слово на более мелкие части, * которые теоретически также могут быть ключевыми словами. * Разделителями ключевого слова могут выступать любые не-буквы и * не-числа (@see self::get_keyword_delimiter()). * Варианты в результирующем массиве располагаются по убыванию длины. * * @param $max_keyword * @return array */ protected function get_possible_keywords($max_keyword) { $keyword_parts = nc_preg_split($this->get_keyword_delimiter(), $max_keyword, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $possible_keywords = array(); while (sizeof($keyword_parts)) { $possible_keywords[] = join('', $keyword_parts); array_pop($keyword_parts); } return $possible_keywords; }
public function match(nc_routing_request $request, nc_routing_result $result) { $folder_id = $result->get_resource_parameter('folder_id'); $date = $result->get_resource_parameter('date'); if ($folder_id && nc_preg_match($this->get_keyword_regexp(), $result->get_remainder(), $matches)) { // Сначала попробовать максимально возможное совпадение; // затем, если есть возможность частичного совпадения — // более короткие варианты (для того, чтобы, к примеру, // была возможность использовать символ подчёркивания в // ключевых словах или "-" в качестве разделителя частей // адреса) $keyword_parts = nc_preg_split($this->get_keyword_delimiter(), $matches[1], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $possible_keywords = array(); while (sizeof($keyword_parts)) { $possible_keywords[] = join('', $keyword_parts); array_pop($keyword_parts); } $infoblocks_in_folder = nc_core::get_object()->sub_class->get_by_subdivision_id($folder_id); foreach ($possible_keywords as $keyword) { foreach ($infoblocks_in_folder as $infoblock) { if ($infoblock['EnglishName'] == $keyword) { // KEYWORD MATCH! if ($date) { $has_event_field = nc_core::get_object()->get_component($infoblock['Class_ID'])->get_date_field(); if (!$has_event_field) { continue; } } $result->set_resource_parameter('infoblock_id', $infoblock['Sub_Class_ID']); $result->truncate_remainder(strlen($keyword)); return true; } } } } return false; }
if ($nc_core->AUTHORIZATION_TYPE == 'session') { $redirect_to_url .= strpos($redirect_to_url, "?") ? "&" : "?"; $redirect_to_url .= session_name() . "=" . session_id(); } header("Location: " . $redirect_to_url, true, 301); exit; } } // старый способ работы с настройками модулей $MODULE_VARS = $nc_core->modules->load_env('', false, true); // *** Подключение файла для обработки выбранного действия с инфоблоком или объектом *** // Front user mode if (!in_array($action, array("index", "full", "add", "search", "subscribe", "message"))) { $action = "index"; } if ($cc && in_array($sub, nc_preg_split("/\\s*,\\s*/", $nc_core->get_settings('modify_sub', 'auth')))) { $action = "message"; $user_table_mode = true; } if (!$sub || $sub == $e404_sub && $title_sub != $sub) { $page_not_found = true; } if ($page_not_found) { $sub = $e404_sub; $nc_core->subdivision->set_current_by_id($sub); $use_multi_sub_class = $nc_core->subdivision->get_by_id($sub, "UseMultiSubClass"); // get 404 cc's $cc_in_sub = $nc_core->sub_class->get_by_subdivision_id($sub); $cc_array = array(); if (!empty($cc_in_sub)) { foreach ($cc_in_sub as $row) {
/** * Check, is param is mysql keyword * * http://dev.mysql.com/doc/refman/4.1/en/reserved-words.html * http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html * * @param string Field Name * @return bool true - if keyword */ function nc_is_mysql_keyword($FieldName) { // old values (removed): accessible connection goto label linear range read_only read_write title upgrade x509 return in_array(strtolower($FieldName), nc_preg_split("/\\s+/", "add all alter analyze and as asc asensitive\n before between bigint binary blob both by call cascade\n case change char character check collate column condition\n constraint continue convert create cross current_date\n current_time current_timestamp current_user\n cursor database databases day_hour day_microsecond day_minute\n day_second dec decimal declare default delayed delete desc describe\n deterministic distinct distinctrow div double drop dual each else\n elseif enclosed escaped exists exit explain false fetch float\n float4 float8 for force foreign from fulltext grant\n group having high_priority hour_microsecond hour_minute hour_second\n if ignore in index infile inner inout insensitive insert\n int int1 int2 int3 int4 int8 integer interval into is iterate join\n key keys kill leading leave left like limit lines load\n localtime localtimestamp lock long longblob longtext\n loop low_priority match mediumblob mediumint mediumtext\n middleint minute_microsecond minute_second mod modifies natural\n not no_write_to_binlog null numeric on optimize\n option optionally or order out outer outfile precision primary\n procedure purge read reads real references\n regexp release rename repeat replace require restrict return revoke\n right rlike schema schemas second_microsecond select sensitive separator set\n show smallint soname spatial specific sql sqlexception sqlstate sqlwarning sql_big_result\n sql_calc_found_rows sql_small_result ssl starting straight_join table\n terminated then tinyblob tinyint tinytext to trailing trigger true\n undo union unique unlock unsigned update usage use\n using utc_date utc_time utc_timestamp values varbinary\n varchar varcharacter varying when where while with write\n xor year_month zerofill _nc_final UserGroup")); }
public function load_env($catalogue, $sub, $cc) { global $admin_mode; global $catalogue, $sub, $cc; global $current_catalogue, $cc; global $current_sub; global $current_cc; global $cc_array; global $use_multi_sub_class; global $system_table_fields, $user_table_mode; global $parent_sub_tree, $sub_level_count; // load catalogue if (!$catalogue) { try { $current_catalogue = $this->catalogue->get_by_host_name($this->HTTP_HOST, true); $catalogue = $current_catalogue['Catalogue_ID']; } catch (Exception $e) { die("No site in project"); } } else { $current_catalogue = $this->catalogue->set_current_by_id($catalogue); } // load sub if (!$sub) { $sub = $this->catalogue->get_by_id($catalogue, "Title_Sub_ID"); if (!$sub) { throw new Exception("Unable to find the index page for catalog"); } } $this->subdivision->set_current_by_id($sub); // load cc if (!$cc) { $checked_only = $admin_mode ? "" : " AND `Checked` = 1"; $cc = $this->db->get_var("SELECT `Sub_Class_ID` FROM `Sub_Class` WHERE `Subdivision_ID` = '" . intval($sub) . "'" . $checked_only . " ORDER BY `Priority` LIMIT 1"); } if ($cc) { try { $this->sub_class->set_current_by_id($cc); } catch (Exception $e) { // todo } } // Load all sub_class id's into array, may be exist in if (!is_array($cc_array)) { $cc_array = array(); // get cc(s) data $res = $this->sub_class->get_by_subdivision_id($sub); if (!empty($res)) { foreach ($res as $row) { if ($row['Checked']) { $cc_array[] = $row['Sub_Class_ID']; } } } } // load system table fields $system_table_fields = $this->get_system_table_fields(); // set global variables $current_catalogue = $this->catalogue->get_current(); $current_sub = $this->subdivision->get_current(); $current_cc = $this->sub_class->get_current(); if ($current_cc['System_Table_ID'] == 3 || in_array($current_sub['Subdivision_ID'], nc_preg_split("/\\s*,\\s*/", $this->get_settings('modify_sub', 'auth')))) { // $action = "message"; $user_table_mode = true; } else { $user_table_mode = false; } $parent_sub_tree[$sub_level_count]["Subdivision_Name"] = $current_catalogue["Catalogue_Name"]; $parent_sub_tree[$sub_level_count]["Hidden_URL"] = "/"; return; }